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
056c498973c1f63c73f43710dc327664a0811b6d
src/org/mangui/hls/loader/LevelLoader.as
src/org/mangui/hls/loader/LevelLoader.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.loader { import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.utils.clearTimeout; import flash.utils.getTimer; import flash.utils.setTimeout; import org.mangui.hls.constant.HLSLoaderTypes; import org.mangui.hls.constant.HLSPlayStates; import org.mangui.hls.constant.HLSTypes; 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.HLSSettings; import org.mangui.hls.model.Fragment; import org.mangui.hls.model.Level; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.playlist.DataUri; import org.mangui.hls.playlist.Manifest; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class LevelLoader { /** Reference to the hls framework controller. **/ private var _hls : HLS; /** levels vector. **/ private var _levels : Vector.<Level>; /** Object that fetches the manifest. **/ private var _urlloader : URLLoader; /** Link to the M3U8 file. **/ private var _url : String; /** are all playlists filled ? **/ private var _canStart : Boolean; /** Timeout ID for reloading live playlists. **/ private var _timeoutID : uint; /** Streaming type (live, ondemand). **/ private var _type : String; /** last reload manifest time **/ private var _reloadPlaylistTimer : uint; /** current load level **/ private var _loadLevel : int; /** reference to manifest being loaded **/ private var _manifestLoading : Manifest; /** is this loader closed **/ private var _closed : Boolean = false; /* playlist retry timeout */ private var _retryTimeout : Number; private var _retryCount : int; /* alt audio tracks */ private var _altAudioTracks : Vector.<AltAudioTrack>; /* manifest load metrics */ private var _metrics : HLSLoadMetrics; /** Setup the loader. **/ public function LevelLoader(hls : HLS) { _hls = hls; _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); _levels = new Vector.<Level>(); } public function dispose() : void { _close(); if(_urlloader) { _urlloader.removeEventListener(Event.COMPLETE, _loadCompleteHandler); _urlloader.removeEventListener(ProgressEvent.PROGRESS, _loadProgressHandler); _urlloader.removeEventListener(IOErrorEvent.IO_ERROR, _errorHandler); _urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler); _urlloader = null; } _hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); } /** Loading failed; return errors. **/ private function _errorHandler(event : ErrorEvent) : void { var txt : String; var code : int; if (event is SecurityErrorEvent) { code = HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR; txt = "Cannot load M3U8: crossdomain access denied:" + event.text; } else if (event is IOErrorEvent && (HLSSettings.manifestLoadMaxRetry == -1 || _retryCount < HLSSettings.manifestLoadMaxRetry)) { CONFIG::LOGGING { Log.warn("I/O Error while trying to load Playlist, retry in " + _retryTimeout + " ms"); } if(_levels.length) { _timeoutID = setTimeout(_loadActiveLevelPlaylist, _retryTimeout); } else { _timeoutID = setTimeout(_loadManifest, _retryTimeout); } /* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */ _retryTimeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retryTimeout); _retryCount++; return; } else { // if we have redundant streams left for that level, switch to it if(_loadLevel < _levels.length && _levels[_loadLevel].redundantStreamId < _levels[_loadLevel].redundantStreamsNb) { CONFIG::LOGGING { Log.warn("max load retry reached, switch to redundant stream"); } _levels[_loadLevel].redundantStreamId++; _timeoutID = setTimeout(_loadActiveLevelPlaylist, 0); _retryTimeout = 1000; _retryCount = 0; return; } else { code = HLSError.MANIFEST_LOADING_IO_ERROR; txt = "Cannot load M3U8: " + event.text; } } var hlsError : HLSError = new HLSError(code, _url, txt); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); } /** Return the current manifest. **/ public function get levels() : Vector.<Level> { return _levels; } /** Return the stream type. **/ public function get type() : String { return _type; } public function get altAudioTracks() : Vector.<AltAudioTrack> { return _altAudioTracks; } /** Load the manifest file. **/ public function load(url : String) : void { if(!_urlloader) { //_urlloader = new URLLoader(); var urlLoaderClass : Class = _hls.URLloader as Class; _urlloader = (new urlLoaderClass()) as URLLoader; _urlloader.addEventListener(Event.COMPLETE, _loadCompleteHandler); _urlloader.addEventListener(ProgressEvent.PROGRESS, _loadProgressHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler); } _close(); _closed = false; _url = url; _levels = new Vector.<Level>(); _canStart = false; _reloadPlaylistTimer = getTimer(); _retryTimeout = 1000; _retryCount = 0; _altAudioTracks = null; _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, url)); _metrics = new HLSLoadMetrics(HLSLoaderTypes.MANIFEST); _metrics.loading_request_time = getTimer(); if (DataUri.isDataUri(url)) { CONFIG::LOGGING { Log.debug("Identified main manifest <" + url + "> as a data URI."); } _metrics.loading_begin_time = getTimer(); var data : String = new DataUri(url).extractData(); _metrics.loading_end_time = getTimer(); _parseManifest(data || ""); } else { _urlloader.load(new URLRequest(url)); } } /** loading progress handler, use to determine loading latency **/ private function _loadProgressHandler(event : Event) : void { if(_metrics.loading_begin_time == 0) { _metrics.loading_begin_time = getTimer(); } } /** Manifest loaded; check and parse it **/ private function _loadCompleteHandler(event : Event) : void { _metrics.loading_end_time = getTimer(); // successful loading, reset retry counter _retryTimeout = 1000; _retryCount = 0; _parseManifest(String(_urlloader.data)); } /** parse a playlist **/ private function _parseLevelPlaylist(string : String, url : String, level : int, metrics : HLSLoadMetrics) : void { var frags : Vector.<Fragment>; if (string != null) { CONFIG::LOGGING { Log.debug("level " + level + " playlist:\n" + string); } frags = Manifest.getFragments(string, url, level); } if(frags && frags.length) { // successful loading, reset retry counter _retryTimeout = 1000; _retryCount = 0; // set fragment and update sequence number range _levels[level].updateFragments(frags); _levels[level].targetduration = Manifest.getTargetDuration(string); _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYLIST_DURATION_UPDATED, _levels[level].duration)); } else { if(HLSSettings.manifestLoadMaxRetry == -1 || _retryCount < HLSSettings.manifestLoadMaxRetry) { CONFIG::LOGGING { Log.warn("empty level Playlist, retry in " + _retryTimeout + " ms"); } _timeoutID = setTimeout(_loadActiveLevelPlaylist, _retryTimeout); /* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */ _retryTimeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retryTimeout); _retryCount++; return; } else { var hlsError : HLSError = new HLSError(HLSError.MANIFEST_LOADING_IO_ERROR, _url, "no fragments in playlist"); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); return; } } // Check whether the stream is live or not finished yet if (Manifest.hasEndlist(string)) { setType(HLSTypes.VOD); _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_ENDLIST, level)); } else { setType(HLSTypes.LIVE); /* in order to determine playlist reload timer, check playback position against playlist duration. if we are near the edge of a live playlist, reload playlist quickly to discover quicker new fragments and avoid buffer starvation. */ var _reloadInterval : Number = 1000*Math.min((_levels[level].duration - _hls.position)/2,_levels[level].averageduration); // avoid spamming the server if we are at the edge ... wait 500ms between 2 reload at least var timeout : int = Math.max(500, _reloadPlaylistTimer + _reloadInterval - getTimer()); CONFIG::LOGGING { Log.debug("Level " + level + " Live Playlist parsing finished: reload in " + timeout + " ms"); } _timeoutID = setTimeout(_loadActiveLevelPlaylist, timeout); } if (!_canStart) { _canStart = (_levels[level].fragments.length > 0); if (_canStart) { CONFIG::LOGGING { Log.debug("first level filled with at least 1 fragment, notify event"); } _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADED, _levels, _metrics)); } } metrics.id = _levels[level].start_seqnum; metrics.id2 = _levels[level].end_seqnum; _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADED, metrics)); _manifestLoading = null; } /** Parse First Level Playlist **/ private function _parseManifest(string : String) : void { var errorTxt : String = null; // Check for M3U8 playlist or manifest. if (string.indexOf(Manifest.HEADER) == 0) { // 1 level playlist, create unique level and parse playlist if (string.indexOf(Manifest.FRAGMENT) > 0) { var level : Level = new Level(); level.urls = new Vector.<String>(); level.urls.push(_url); _levels.push(level); _metrics.parsing_end_time = getTimer(); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels)); _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, 0)); CONFIG::LOGGING { Log.debug("1 Level Playlist, load it"); } _loadLevel = 0; _metrics.type = HLSLoaderTypes.LEVEL_MAIN; _parseLevelPlaylist(string, _url, 0,_metrics); } else if (string.indexOf(Manifest.LEVEL) > 0) { CONFIG::LOGGING { Log.debug("adaptive playlist:\n" + string); } // adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(string, _url); if (_levels.length) { _metrics.parsing_end_time = getTimer(); _loadLevel = -1; _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels)); if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) { CONFIG::LOGGING { Log.debug("alternate audio level found"); } // parse alternate audio tracks _altAudioTracks = Manifest.extractAltAudioTracks(string, _url); CONFIG::LOGGING { if (_altAudioTracks.length > 0) { Log.debug(_altAudioTracks.length + " alternate audio tracks found"); } } } } else { errorTxt = "No level found in Manifest"; } } else { // manifest start with correct header, but it does not contain any fragment or level info ... errorTxt = "empty Manifest"; } } else { errorTxt = "Manifest is not a valid M3U8 file"; } if(errorTxt) { _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, errorTxt))); } } /** load/reload manifest **/ private function _loadManifest() : void { _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, _url)); _metrics = new HLSLoadMetrics(HLSLoaderTypes.MANIFEST); _metrics.loading_request_time = getTimer(); if (DataUri.isDataUri(_url)) { CONFIG::LOGGING { Log.debug("Identified manifest <" + _url + "> as a data URI."); } _metrics.loading_begin_time = getTimer(); var data : String = new DataUri(_url).extractData(); _metrics.loading_end_time = getTimer(); _parseManifest(data || ""); } else { _urlloader.load(new URLRequest(_url)); } } /** load/reload active M3U8 playlist **/ private function _loadActiveLevelPlaylist() : void { if (_closed) { return; } _reloadPlaylistTimer = getTimer(); // load active M3U8 playlist only _manifestLoading = new Manifest(); _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, _loadLevel)); _manifestLoading.loadPlaylist(_hls,_levels[_loadLevel].url, _parseLevelPlaylist, _errorHandler, _loadLevel, _type, HLSSettings.flushLiveURLCache); } /** When level switch occurs, assess the need of (re)loading new level playlist **/ private function _levelSwitchHandler(event : HLSEvent) : void { if (_loadLevel != event.level || _levels[_loadLevel].fragments.length == 0) { _loadLevel = event.level; CONFIG::LOGGING { Log.debug("switch to level " + _loadLevel); } if (type == HLSTypes.LIVE || _levels[_loadLevel].fragments.length == 0) { _closed = false; CONFIG::LOGGING { Log.debug("(re)load Playlist"); } if(_manifestLoading) { _manifestLoading.close(); _manifestLoading = null; } clearTimeout(_timeoutID); _timeoutID = setTimeout(_loadActiveLevelPlaylist, 0); } } } private function _close() : void { CONFIG::LOGGING { Log.debug("cancel any manifest load in progress"); } _closed = true; clearTimeout(_timeoutID); try { _urlloader.close(); if (_manifestLoading) { _manifestLoading.close(); } } catch(e : Error) { } } /** When the framework idles out, stop reloading manifest **/ private function _stateHandler(event : HLSEvent) : void { if (event.state == HLSPlayStates.IDLE) { _close(); } } private function setType(value: String):void{ if(value != _type){ _type = value; CONFIG::LOGGING { Log.debug("Stream type did change to " + value); } _hls.dispatchEvent(new HLSEvent(HLSEvent.STREAM_TYPE_DID_CHANGE, _type)); } } } }
/* 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.loader { import flash.events.ErrorEvent; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.utils.clearTimeout; import flash.utils.getTimer; import flash.utils.setTimeout; import org.mangui.hls.constant.HLSLoaderTypes; import org.mangui.hls.constant.HLSPlayStates; import org.mangui.hls.constant.HLSTypes; 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.HLSSettings; import org.mangui.hls.model.Fragment; import org.mangui.hls.model.Level; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.playlist.DataUri; import org.mangui.hls.playlist.Manifest; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class LevelLoader { /** Reference to the hls framework controller. **/ private var _hls : HLS; /** levels vector. **/ private var _levels : Vector.<Level>; /** Object that fetches the manifest. **/ private var _urlloader : URLLoader; /** Link to the M3U8 file. **/ private var _url : String; /** are all playlists filled ? **/ private var _canStart : Boolean; /** Timeout ID for reloading live playlists. **/ private var _timeoutID : uint; /** Streaming type (live, ondemand). **/ private var _type : String; /** last reload manifest time **/ private var _reloadPlaylistTimer : uint; /** current load level **/ private var _loadLevel : int; /** reference to manifest being loaded **/ private var _manifestLoading : Manifest; /** is this loader closed **/ private var _closed : Boolean = false; /* playlist retry timeout */ private var _retryTimeout : Number; private var _retryCount : int; /* alt audio tracks */ private var _altAudioTracks : Vector.<AltAudioTrack>; /* manifest load metrics */ private var _metrics : HLSLoadMetrics; /** Setup the loader. **/ public function LevelLoader(hls : HLS) { _hls = hls; _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); _levels = new Vector.<Level>(); } public function dispose() : void { _close(); if(_urlloader) { _urlloader.removeEventListener(Event.COMPLETE, _loadCompleteHandler); _urlloader.removeEventListener(ProgressEvent.PROGRESS, _loadProgressHandler); _urlloader.removeEventListener(IOErrorEvent.IO_ERROR, _errorHandler); _urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler); _urlloader = null; } _hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); } /** Loading failed; return errors. **/ private function _errorHandler(event : ErrorEvent) : void { var txt : String; var code : int; if (event is SecurityErrorEvent) { code = HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR; txt = "Cannot load M3U8: crossdomain access denied:" + event.text; } else if (event is IOErrorEvent && (HLSSettings.manifestLoadMaxRetry == -1 || _retryCount < HLSSettings.manifestLoadMaxRetry)) { CONFIG::LOGGING { Log.warn("I/O Error while trying to load Playlist, retry in " + _retryTimeout + " ms"); } if(_levels.length) { _timeoutID = setTimeout(_loadActiveLevelPlaylist, _retryTimeout); } else { _timeoutID = setTimeout(_loadManifest, _retryTimeout); } /* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */ _retryTimeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retryTimeout); _retryCount++; return; } else { // if we have redundant streams left for that level, switch to it if(_loadLevel < _levels.length && _levels[_loadLevel].redundantStreamId < _levels[_loadLevel].redundantStreamsNb) { CONFIG::LOGGING { Log.warn("max load retry reached, switch to redundant stream"); } _levels[_loadLevel].redundantStreamId++; _timeoutID = setTimeout(_loadActiveLevelPlaylist, 0); _retryTimeout = 1000; _retryCount = 0; return; } else { code = HLSError.MANIFEST_LOADING_IO_ERROR; txt = "Cannot load M3U8: " + event.text; } } var hlsError : HLSError = new HLSError(code, _url, txt); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); } /** Return the current manifest. **/ public function get levels() : Vector.<Level> { return _levels; } /** Return the stream type. **/ public function get type() : String { return _type; } public function get altAudioTracks() : Vector.<AltAudioTrack> { return _altAudioTracks; } /** Load the manifest file. **/ public function load(url : String) : void { if(!_urlloader) { //_urlloader = new URLLoader(); var urlLoaderClass : Class = _hls.URLloader as Class; _urlloader = (new urlLoaderClass()) as URLLoader; _urlloader.addEventListener(Event.COMPLETE, _loadCompleteHandler); _urlloader.addEventListener(ProgressEvent.PROGRESS, _loadProgressHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler); } _close(); _closed = false; _url = url; _levels = new Vector.<Level>(); _canStart = false; _reloadPlaylistTimer = getTimer(); _retryTimeout = 1000; _retryCount = 0; _altAudioTracks = null; _loadManifest(); } /** loading progress handler, use to determine loading latency **/ private function _loadProgressHandler(event : Event) : void { if(_metrics.loading_begin_time == 0) { _metrics.loading_begin_time = getTimer(); } } /** Manifest loaded; check and parse it **/ private function _loadCompleteHandler(event : Event) : void { _metrics.loading_end_time = getTimer(); // successful loading, reset retry counter _retryTimeout = 1000; _retryCount = 0; _parseManifest(String(_urlloader.data)); } /** parse a playlist **/ private function _parseLevelPlaylist(string : String, url : String, level : int, metrics : HLSLoadMetrics) : void { var frags : Vector.<Fragment>; if (string != null) { CONFIG::LOGGING { Log.debug("level " + level + " playlist:\n" + string); } frags = Manifest.getFragments(string, url, level); } if(frags && frags.length) { // successful loading, reset retry counter _retryTimeout = 1000; _retryCount = 0; // set fragment and update sequence number range _levels[level].updateFragments(frags); _levels[level].targetduration = Manifest.getTargetDuration(string); _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYLIST_DURATION_UPDATED, _levels[level].duration)); } else { if(HLSSettings.manifestLoadMaxRetry == -1 || _retryCount < HLSSettings.manifestLoadMaxRetry) { CONFIG::LOGGING { Log.warn("empty level Playlist, retry in " + _retryTimeout + " ms"); } _timeoutID = setTimeout(_loadActiveLevelPlaylist, _retryTimeout); /* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */ _retryTimeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retryTimeout); _retryCount++; return; } else { var hlsError : HLSError = new HLSError(HLSError.MANIFEST_LOADING_IO_ERROR, _url, "no fragments in playlist"); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); return; } } // Check whether the stream is live or not finished yet if (Manifest.hasEndlist(string)) { setType(HLSTypes.VOD); _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_ENDLIST, level)); } else { setType(HLSTypes.LIVE); /* in order to determine playlist reload timer, check playback position against playlist duration. if we are near the edge of a live playlist, reload playlist quickly to discover quicker new fragments and avoid buffer starvation. */ var _reloadInterval : Number = 1000*Math.min((_levels[level].duration - _hls.position)/2,_levels[level].averageduration); // avoid spamming the server if we are at the edge ... wait 500ms between 2 reload at least var timeout : int = Math.max(500, _reloadPlaylistTimer + _reloadInterval - getTimer()); CONFIG::LOGGING { Log.debug("Level " + level + " Live Playlist parsing finished: reload in " + timeout + " ms"); } _timeoutID = setTimeout(_loadActiveLevelPlaylist, timeout); } if (!_canStart) { _canStart = (_levels[level].fragments.length > 0); if (_canStart) { CONFIG::LOGGING { Log.debug("first level filled with at least 1 fragment, notify event"); } _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADED, _levels, _metrics)); } } metrics.id = _levels[level].start_seqnum; metrics.id2 = _levels[level].end_seqnum; _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADED, metrics)); _manifestLoading = null; } /** Parse First Level Playlist **/ private function _parseManifest(string : String) : void { var errorTxt : String = null; // Check for M3U8 playlist or manifest. if (string.indexOf(Manifest.HEADER) == 0) { // 1 level playlist, create unique level and parse playlist if (string.indexOf(Manifest.FRAGMENT) > 0) { var level : Level = new Level(); level.urls = new Vector.<String>(); level.urls.push(_url); _levels.push(level); _metrics.parsing_end_time = getTimer(); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels)); _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, 0)); CONFIG::LOGGING { Log.debug("1 Level Playlist, load it"); } _loadLevel = 0; _metrics.type = HLSLoaderTypes.LEVEL_MAIN; _parseLevelPlaylist(string, _url, 0,_metrics); } else if (string.indexOf(Manifest.LEVEL) > 0) { CONFIG::LOGGING { Log.debug("adaptive playlist:\n" + string); } // adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(string, _url); if (_levels.length) { _metrics.parsing_end_time = getTimer(); _loadLevel = -1; _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels)); if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) { CONFIG::LOGGING { Log.debug("alternate audio level found"); } // parse alternate audio tracks _altAudioTracks = Manifest.extractAltAudioTracks(string, _url); CONFIG::LOGGING { if (_altAudioTracks.length > 0) { Log.debug(_altAudioTracks.length + " alternate audio tracks found"); } } } } else { errorTxt = "No level found in Manifest"; } } else { // manifest start with correct header, but it does not contain any fragment or level info ... errorTxt = "empty Manifest"; } } else { errorTxt = "Manifest is not a valid M3U8 file"; } if(errorTxt) { _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, errorTxt))); } } /** load/reload manifest **/ private function _loadManifest() : void { _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, _url)); _metrics = new HLSLoadMetrics(HLSLoaderTypes.MANIFEST); _metrics.loading_request_time = getTimer(); if (DataUri.isDataUri(_url)) { CONFIG::LOGGING { Log.debug("Identified manifest <" + _url + "> as a data URI."); } _metrics.loading_begin_time = getTimer(); var data : String = new DataUri(_url).extractData(); _metrics.loading_end_time = getTimer(); _parseManifest(data || ""); } else { _urlloader.load(new URLRequest(_url)); } } /** load/reload active M3U8 playlist **/ private function _loadActiveLevelPlaylist() : void { if (_closed) { return; } _reloadPlaylistTimer = getTimer(); // load active M3U8 playlist only _manifestLoading = new Manifest(); _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, _loadLevel)); _manifestLoading.loadPlaylist(_hls,_levels[_loadLevel].url, _parseLevelPlaylist, _errorHandler, _loadLevel, _type, HLSSettings.flushLiveURLCache); } /** When level switch occurs, assess the need of (re)loading new level playlist **/ private function _levelSwitchHandler(event : HLSEvent) : void { if (_loadLevel != event.level || _levels[_loadLevel].fragments.length == 0) { _loadLevel = event.level; CONFIG::LOGGING { Log.debug("switch to level " + _loadLevel); } if (type == HLSTypes.LIVE || _levels[_loadLevel].fragments.length == 0) { _closed = false; CONFIG::LOGGING { Log.debug("(re)load Playlist"); } if(_manifestLoading) { _manifestLoading.close(); _manifestLoading = null; } clearTimeout(_timeoutID); _timeoutID = setTimeout(_loadActiveLevelPlaylist, 0); } } } private function _close() : void { CONFIG::LOGGING { Log.debug("cancel any manifest load in progress"); } _closed = true; clearTimeout(_timeoutID); try { _urlloader.close(); if (_manifestLoading) { _manifestLoading.close(); } } catch(e : Error) { } } /** When the framework idles out, stop reloading manifest **/ private function _stateHandler(event : HLSEvent) : void { if (event.state == HLSPlayStates.IDLE) { _close(); } } private function setType(value: String):void{ if(value != _type){ _type = value; CONFIG::LOGGING { Log.debug("Stream type did change to " + value); } _hls.dispatchEvent(new HLSEvent(HLSEvent.STREAM_TYPE_DID_CHANGE, _type)); } } } }
fix wrong merge commit https://github.com/mangui/flashls/commit/533d1336dd0be7f586a0b709d67f9fcebddc46e3#diff-ea71d040ba29d01d23b9f8d40a0174b0R136
fix wrong merge commit https://github.com/mangui/flashls/commit/533d1336dd0be7f586a0b709d67f9fcebddc46e3#diff-ea71d040ba29d01d23b9f8d40a0174b0R136
ActionScript
mpl-2.0
NicolasSiver/flashls,loungelogic/flashls,vidible/vdb-flashls,clappr/flashls,hola/flashls,codex-corp/flashls,tedconf/flashls,hola/flashls,jlacivita/flashls,jlacivita/flashls,NicolasSiver/flashls,clappr/flashls,loungelogic/flashls,mangui/flashls,neilrackett/flashls,codex-corp/flashls,neilrackett/flashls,fixedmachine/flashls,fixedmachine/flashls,vidible/vdb-flashls,tedconf/flashls,mangui/flashls
9c539f20e6151e501dd33f98433b86ba154a62f9
src/flash/utils/SetIntervalTimer.as
src/flash/utils/SetIntervalTimer.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 *totalMemory * 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 { import flash.events.Event; import flash.events.TimerEvent; internal final class SetIntervalTimer extends Timer { internal var reference:uint; private var closure:Function; private var rest:Array; private static var intervalArray:Array = []; public function SetIntervalTimer(closure:Function, delay:Number, repeats:Boolean, rest:Array) { super(delay, repeats ? 1 : 0); this.closure = closure; this.rest = rest; reference = intervalArray.push(this); addEventListener(TimerEvent.TIMER, onTimer); start(); } private function onTimer(event:Event):void { closure.apply(null, rest); if (1 == repeatCount) { if (this == intervalArray[reference-1]) { delete intervalArray[reference-1]; } } } internal static function _clearInterval(id:uint):void { var index = id - 1; if (intervalArray[index] is SetIntervalTimer) { intervalArray[index].stop(); delete intervalArray[index]; } } } public function setTimeout(closure:Function, delay:Number, ... args):uint { return new SetIntervalTimer(closure, delay, false, args).reference; } public function clearTimeout(id:uint):void { SetIntervalTimer._clearInterval(id); } public function setInterval(closure:Function, delay:Number, ... args):uint { return new SetIntervalTimer(closure, delay, true, args).reference; } public function clearInterval(id:uint):void { SetIntervalTimer._clearInterval(id); } }
/* * 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 *totalMemory * 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 { import flash.events.Event; import flash.events.TimerEvent; internal final class SetIntervalTimer extends Timer { internal var reference:uint; private var closure:Function; private var rest:Array; private static var intervalArray:Array = []; public function SetIntervalTimer(closure:Function, delay:Number, repeats:Boolean, rest:Array) { super(delay, repeats ? 0 : 1); this.closure = closure; this.rest = rest; reference = intervalArray.push(this); addEventListener(TimerEvent.TIMER, onTimer); start(); } private function onTimer(event:Event):void { closure.apply(null, rest); if (1 == repeatCount) { if (this == intervalArray[reference-1]) { delete intervalArray[reference-1]; } } } internal static function _clearInterval(id:uint):void { var index = id - 1; if (intervalArray[index] is SetIntervalTimer) { intervalArray[index].stop(); delete intervalArray[index]; } } } public function setTimeout(closure:Function, delay:Number, ... args):uint { return new SetIntervalTimer(closure, delay, false, args).reference; } public function clearTimeout(id:uint):void { SetIntervalTimer._clearInterval(id); } public function setInterval(closure:Function, delay:Number, ... args):uint { return new SetIntervalTimer(closure, delay, true, args).reference; } public function clearInterval(id:uint):void { SetIntervalTimer._clearInterval(id); } }
Fix SetIntervalTimer to not switch behavior of setTimout and setInterval
Fix SetIntervalTimer to not switch behavior of setTimout and setInterval
ActionScript
apache-2.0
mbebenita/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway
c67bf70e249f2eb53ecde9408c466b3c6a030b11
src/goplayer/ConfigurationParser.as
src/goplayer/ConfigurationParser.as
package goplayer { public class ConfigurationParser { public static const DEFAULT_API_URL : String = "http://staging.streamio.se/api" public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf" public static const DEFAULT_TRACKER_ID : String = "global" public static const VALID_PARAMETERS : Array = [ "api", "tracker", "skin", "movie", "bitrate", "enablertmp", "enableautoplay", "enablelooping", "enablechrome", "enabletitle" ] private const result : Configuration = new Configuration private var parameters : Object private var originalParameterNames : Object public function ConfigurationParser (parameters : Object, originalParameterNames : Object) { this.parameters = parameters this.originalParameterNames = originalParameterNames } public function execute() : void { result.apiURL = getString("api", DEFAULT_API_URL) result.trackerID = getString("tracker", DEFAULT_TRACKER_ID) result.skinURL = getString("skin", DEFAULT_SKIN_URL) result.movieID = getString("movie", null) result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST) result.enableRTMP = getBoolean("enablertmp", true) result.enableAutoplay = getBoolean("enableautoplay", false) result.enableLooping = getBoolean("enablelooping", false) result.enableChrome = getBoolean("enablechrome", true) result.enableTitle = getBoolean("enabletitle", true) } public static function parse(parameters : Object) : Configuration { const normalizedParameters : Object = {} const originalParameterNames : Object = {} for (var name : String in parameters) if (VALID_PARAMETERS.indexOf(normalize(name)) == -1) reportUnknownParameter(name) else normalizedParameters[normalize(name)] = parameters[name], originalParameterNames[normalize(name)] = name const parser : ConfigurationParser = new ConfigurationParser (normalizedParameters, originalParameterNames) parser.execute() return parser.result } private static function normalize(name : String) : String { return name.toLowerCase().replace(/[^a-z]/g, "") } private static function reportUnknownParameter(name : String) : void { debug("Error: Unknown parameter: " + name) } // ----------------------------------------------------- private function getString(name : String, fallback : String) : String { return name in parameters ? parameters[name] : fallback } private function getBoolean (name : String, fallback : Boolean) : Boolean { if (name in parameters) return $getBoolean(name, parameters[name], fallback) else return fallback } private function $getBoolean (name : String, value : String, fallback : Boolean) : Boolean { try { return $$getBoolean(value) } catch (error : Error) { reportInvalidParameter(name, value, ["true", "false"]) return fallback } throw new Error } private function $$getBoolean(value : String) : Boolean { if (value == "true") return true else if (value == "false") return false else throw new Error } // ----------------------------------------------------- private function getBitratePolicy (name : String, fallback : BitratePolicy) : BitratePolicy { if (name in parameters) return $getBitratePolicy(name, parameters[name], fallback) else return fallback } private function $getBitratePolicy (name : String, value : String, fallback : BitratePolicy) : BitratePolicy { try { return $$getBitratePolicy(value) } catch (error : Error) { reportInvalidParameter(name, value, BITRATE_POLICY_VALUES) return fallback } throw new Error } private const BITRATE_POLICY_VALUES : Array = ["<number>kbps", "min", "max", "best"] private function $$getBitratePolicy(value : String) : BitratePolicy { if (value == "max") return BitratePolicy.MAX else if (value == "min") return BitratePolicy.MIN else if (value == "best") return BitratePolicy.BEST else if (Bitrate.parse(value)) return BitratePolicy.specific(Bitrate.parse(value)) else throw new Error } // ----------------------------------------------------- private function reportInvalidParameter (name : String, value : String, validValues : Array) : void { debug("Error: Invalid parameter: " + "“" + originalParameterNames[name] + "=" + value + "”; " + getInvalidParameterHint(validValues) + ".") } private function getInvalidParameterHint(values : Array) : String { return $getInvalidParameterHint(getQuotedValues(values)) } private function $getInvalidParameterHint(values : Array) : String { return "please use " + "either " + values.slice(0, -1).join(", ") + " " + "or " + values[values.length - 1] } private function getQuotedValues(values : Array) : Array { var result : Array = [] for each (var value : String in values) result.push("“" + value + "”") return result } } }
package goplayer { public class ConfigurationParser { public static const DEFAULT_API_URL : String = "http://staging.streamio.se/api" public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf" public static const DEFAULT_TRACKER_ID : String = "global" public static const VALID_PARAMETERS : Array = [ "api", "tracker", "skin", "movie", "bitrate", "enablertmp", "autoplay", "loop", "enablechrome", "enabletitle" ] private const result : Configuration = new Configuration private var parameters : Object private var originalParameterNames : Object public function ConfigurationParser (parameters : Object, originalParameterNames : Object) { this.parameters = parameters this.originalParameterNames = originalParameterNames } public function execute() : void { result.apiURL = getString("api", DEFAULT_API_URL) result.trackerID = getString("tracker", DEFAULT_TRACKER_ID) result.skinURL = getString("skin", DEFAULT_SKIN_URL) result.movieID = getString("movie", null) result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST) result.enableRTMP = getBoolean("enablertmp", true) result.enableAutoplay = getBoolean("autoplay", false) result.enableLooping = getBoolean("loop", false) result.enableChrome = getBoolean("enablechrome", true) result.enableTitle = getBoolean("enabletitle", true) } public static function parse(parameters : Object) : Configuration { const normalizedParameters : Object = {} const originalParameterNames : Object = {} for (var name : String in parameters) if (VALID_PARAMETERS.indexOf(normalize(name)) == -1) reportUnknownParameter(name) else normalizedParameters[normalize(name)] = parameters[name], originalParameterNames[normalize(name)] = name const parser : ConfigurationParser = new ConfigurationParser (normalizedParameters, originalParameterNames) parser.execute() return parser.result } private static function normalize(name : String) : String { return name.toLowerCase().replace(/[^a-z]/g, "") } private static function reportUnknownParameter(name : String) : void { debug("Error: Unknown parameter: " + name) } // ----------------------------------------------------- private function getString(name : String, fallback : String) : String { return name in parameters ? parameters[name] : fallback } private function getBoolean (name : String, fallback : Boolean) : Boolean { if (name in parameters) return $getBoolean(name, parameters[name], fallback) else return fallback } private function $getBoolean (name : String, value : String, fallback : Boolean) : Boolean { try { return $$getBoolean(value) } catch (error : Error) { reportInvalidParameter(name, value, ["true", "false"]) return fallback } throw new Error } private function $$getBoolean(value : String) : Boolean { if (value == "true") return true else if (value == "false") return false else throw new Error } // ----------------------------------------------------- private function getBitratePolicy (name : String, fallback : BitratePolicy) : BitratePolicy { if (name in parameters) return $getBitratePolicy(name, parameters[name], fallback) else return fallback } private function $getBitratePolicy (name : String, value : String, fallback : BitratePolicy) : BitratePolicy { try { return $$getBitratePolicy(value) } catch (error : Error) { reportInvalidParameter(name, value, BITRATE_POLICY_VALUES) return fallback } throw new Error } private const BITRATE_POLICY_VALUES : Array = ["<number>kbps", "min", "max", "best"] private function $$getBitratePolicy(value : String) : BitratePolicy { if (value == "max") return BitratePolicy.MAX else if (value == "min") return BitratePolicy.MIN else if (value == "best") return BitratePolicy.BEST else if (Bitrate.parse(value)) return BitratePolicy.specific(Bitrate.parse(value)) else throw new Error } // ----------------------------------------------------- private function reportInvalidParameter (name : String, value : String, validValues : Array) : void { debug("Error: Invalid parameter: " + "“" + originalParameterNames[name] + "=" + value + "”; " + getInvalidParameterHint(validValues) + ".") } private function getInvalidParameterHint(values : Array) : String { return $getInvalidParameterHint(getQuotedValues(values)) } private function $getInvalidParameterHint(values : Array) : String { return "please use " + "either " + values.slice(0, -1).join(", ") + " " + "or " + values[values.length - 1] } private function getQuotedValues(values : Array) : Array { var result : Array = [] for each (var value : String in values) result.push("“" + value + "”") return result } } }
Change `enable-autoplay' and `enable-looping' to `autoplay' and `loop'.
Change `enable-autoplay' and `enable-looping' to `autoplay' and `loop'.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
6ad7e7bf7aebed1d4aa97296189931d28e3d6ce8
src/main/as/flump/export/Preview.as
src/main/as/flump/export/Preview.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.BitmapData; import flash.filesystem.File; import executor.Executor; import executor.load.ImageLoader; import executor.load.LoadedImage; import flump.display.Movie; import flump.xfl.XflLibrary; import flump.xfl.XflMovie; import flump.xfl.XflTexture; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Sprite; import starling.textures.Texture; import com.threerings.util.Map; import com.threerings.util.Maps; import com.threerings.display.Animation; public class Preview extends Sprite { public function displayAnimation (base :File, lib :XflLibrary, xflMovie :XflMovie) :void { loadTextures(base, lib, function (..._) :void { var movie :Movie = new Movie(xflMovie, function (symbol :String) :DisplayObject { const xflTex :XflTexture = _xflTextures.get(symbol); const packed :PackedTexture = PackedTexture.fromTexture(xflTex, lib); const image :Image = new Image(Texture.fromBitmapData(packed.toBitmapData())); image.x = packed.offset.x; image.y = packed.offset.y; const holder :Sprite = new Sprite(); holder.addChild(image); return holder; }); addChild(movie); }); } public function loadTextures (base :File, lib :XflLibrary, onLoaded :Function) :void { var loader :Executor = new Executor(); for each (var tex :XflTexture in lib.textures) { if (_textures.containsKey(tex.name)) continue; new ImageLoader().loadFromUrl(tex.exportPath(base).url, loader).succeeded.add( textureAdder(tex)); } loader.terminated.add(function (..._) :void { onLoaded(); }); loader.shutdown(); } public function textureAdder (tex :XflTexture) :Function { return function (img :LoadedImage) :void { _xflTextures.put(tex.name, tex); _textures.put(tex.name, Texture.fromBitmap(img.bitmap)); }; } public function displayTextures (base :File, lib :XflLibrary) :void { loadTextures(base, lib, function (..._) :void { var x :int = 0; for each (var tex :Texture in _textures.values()) { var img :Image = new Image(tex); img.x = x; x += img.width; addChild(img); } }); } protected const _xflTextures :Map = Maps.newMapOf(String); protected const _textures :Map = Maps.newMapOf(String); } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.display.BitmapData; import flash.filesystem.File; import flump.display.Movie; import flump.xfl.XflLibrary; import flump.xfl.XflMovie; import flump.xfl.XflTexture; import starling.display.DisplayObject; import starling.display.Image; import starling.display.Sprite; import starling.textures.Texture; import com.threerings.display.Animation; public class Preview extends Sprite { public function displayAnimation (base :File, lib :XflLibrary, xflMovie :XflMovie) :void { var movie :Movie = new Movie(xflMovie, function (symbol :String) :DisplayObject { const xflTex :XflTexture = lib.lookup(symbol); const packed :PackedTexture = PackedTexture.fromTexture(xflTex, lib); const image :Image = new Image(Texture.fromBitmapData(packed.toBitmapData())); image.x = packed.offset.x; image.y = packed.offset.y; const holder :Sprite = new Sprite(); holder.addChild(image); return holder; }); addChild(movie); } } }
Use XflLibrary's symbol lookup in Preview
Use XflLibrary's symbol lookup in Preview The texture loading from disk is gone for now
ActionScript
mit
mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump
a32a900e000d91766190b58cec3b0afb2f7804b6
as3FlexClient/src/com/kaltura/delegates/WebDelegateBase.as
as3FlexClient/src/com/kaltura/delegates/WebDelegateBase.as
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2011 Kaltura Inc. // // 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/>. // // @ignore // =================================================================================================== package com.kaltura.delegates { import com.kaltura.KalturaClient; import com.kaltura.config.IKalturaConfig; import com.kaltura.config.KalturaConfig; import com.kaltura.core.KClassFactory; import com.kaltura.encryption.MD5; import com.kaltura.errors.KalturaError; import com.kaltura.events.KalturaEvent; import com.kaltura.net.KalturaCall; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.HTTPStatusEvent; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.FileReference; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.utils.Timer; import flash.utils.getDefinitionByName; public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate { public static var CONNECT_TIME:int = 120000; //120 secs public static var LOAD_TIME:int = 120000; //120 secs protected var connectTimer:Timer; protected var loadTimer:Timer; protected var _call:KalturaCall; protected var _config:KalturaConfig; protected var loader:URLLoader; protected var fileRef:FileReference; //Setters & getters public function get call():KalturaCall { return _call; } public function set call(newVal:KalturaCall):void { _call = newVal; } public function get config():IKalturaConfig { return _config; } public function set config(newVal:IKalturaConfig):void { _config = newVal as KalturaConfig; } public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) { this.call = call; this.config = config; if (!call) return; //maybe a multi request if (call.useTimeout) { connectTimer = new Timer(CONNECT_TIME, 1); connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout); loadTimer = new Timer(LOAD_TIME, 1); loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut); } execute(); } public function close():void { try { loader.close(); } catch (e:*) { } if (call.useTimeout) { connectTimer.stop(); loadTimer.stop(); } } protected function onConnectTimeout(event:TimerEvent):void { var kError:KalturaError = new KalturaError(); kError.errorCode = "CONNECTION_TIMEOUT"; kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client."; _call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); loadTimer.stop(); close(); } protected function onLoadTimeOut(event:TimerEvent):void { connectTimer.stop(); close(); var kError:KalturaError = new KalturaError(); kError.errorCode = "POST_TIMEOUT"; kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result."; _call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } protected function execute():void { if (call == null) { throw new Error('No call defined.'); } post(); //post the call } /** * Helper function for sending the call straight to the server */ protected function post():void { addOptionalArguments(); formatRequest(); sendRequest(); if (call.useTimeout) { connectTimer.start(); } } protected function formatRequest():void { //The configuration is stronger then the args if (_config.partnerId != null && _call.args["partnerId"] == -1) _call.setRequestArgument("partnerId", _config.partnerId); if (_config.ks != null) _call.setRequestArgument("ks", _config.ks); if (_config.clientTag != null) _call.setRequestArgument("clientTag", _config.clientTag); _call.setRequestArgument("ignoreNull", _config.ignoreNull); _call.setRequestArgument("apiVersion", KalturaClient.API_VERSION); //Create signature hash. //call.setRequestArgument("kalsig", getMD5Checksum(call)); } protected function getMD5Checksum(call:KalturaCall):String { var props:Array = new Array(); for (var arg:String in call.args) props.push(arg); props.sort(); var s:String = ""; for each (var prop:String in props) { if ( call.args[prop] ) s += prop + call.args[prop]; } return MD5.encrypt(s); } protected function sendRequest():void { //construct the loader createURLLoader(); //Create signature hash. var kalsig:String = getMD5Checksum(call); //create the service request for normal calls var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;; if (_call.method == URLRequestMethod.GET) url += "&"; var req:URLRequest = new URLRequest(url); req.contentType = "application/x-www-form-urlencoded"; req.method = call.method; req.data = call.args; loader.dataFormat = URLLoaderDataFormat.TEXT; loader.load(req); } protected function createURLLoader():void { loader = new URLLoader(); loader.addEventListener(Event.COMPLETE, onDataComplete); loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus); loader.addEventListener(IOErrorEvent.IO_ERROR, onError); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); loader.addEventListener(Event.OPEN, onOpen); } protected function onHTTPStatus(event:HTTPStatusEvent):void { } protected function onOpen(event:Event):void { if (call.useTimeout) { connectTimer.stop(); loadTimer.start(); } } protected function addOptionalArguments():void { //add optional args here } // Event Handlers /** * try to process received data. * if procesing failed, let call handle the processing error * @param event load complete event */ protected function onDataComplete(event:Event):void { try { handleResult(XML(event.target.data)); } catch (e:Error) { var kErr:KalturaError = new KalturaError(); kErr.errorCode = String(e.errorID); kErr.errorMsg = e.message; _call.handleError(kErr); } } /** * handle io or security error events from the loader. * create relevant KalturaError, let the call process it. * @param event */ protected function onError(event:ErrorEvent):void { clean(); var kError:KalturaError = createKalturaError(event, loader.data); if (!kError) { kError = new KalturaError(); kError.errorMsg = event.text; kError.errorCode = event.type; // either IOErrorEvent.IO_ERROR or SecurityErrorEvent.SECURITY_ERROR } call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } /** * parse the server's response and let the call process it. * @param result server's response */ protected function handleResult(result:XML):void { clean(); var error:KalturaError = validateKalturaResponse(result); if (error == null) { var digestedResult:Object = parse(result); call.handleResult(digestedResult); } else { call.handleError(error); } } /** * stop timers and clean event listeners */ protected function clean():void { if (call.useTimeout) { connectTimer.stop(); loadTimer.stop(); } if (loader == null) { return; } loader.removeEventListener(Event.COMPLETE, onDataComplete); loader.removeEventListener(IOErrorEvent.IO_ERROR, onError); loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); loader.removeEventListener(Event.OPEN, onOpen); } /** * create the correct object and populate it with the given values. if the needed class is not found * in the file, a generic object is created with attributes matching the XML attributes. * Override this parssing function in the specific delegate to create the correct object. * @param result instance attributes * @return an instance of the class declared by the given XML. * */ public function parse(result:XML):* { //by defualt create the response object var cls:Class; try { cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class; } catch (e:Error) { cls = Object; } var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result); return obj; } /** * If the result string holds an error, return a KalturaError object with * relevant values. <br/> * Overide this to create validation object and fill it. * @param result the string returned from the server. * @return matching error object */ protected function validateKalturaResponse(result:String):KalturaError { var kError:KalturaError = null; var xml:XML = XML(result); if (xml.result.hasOwnProperty('error') && xml.result.error.hasOwnProperty('code') && xml.result.error.hasOwnProperty('message')) { kError = new KalturaError(); kError.errorCode = String(xml.result.error.code); kError.errorMsg = xml.result.error.message; dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } return kError; } /** * create error object and fill it with relevant details * @param event * @param loaderData * @return detailed KalturaError to be processed */ protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError { var ke:KalturaError = new KalturaError(); ke.errorMsg = event.text; ke.errorCode = event.type; return ke; } /** * create the url that is used for serve actions * @param call the KalturaCall that defines the required parameters * @return URLRequest with relevant parameters * */ public function getServeUrl(call:KalturaCall):URLRequest { var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action; for (var key:String in call.args) { url += "&" + key + "=" + call.args[key]; } var req:URLRequest = new URLRequest(url); req.contentType = "application/x-www-form-urlencoded"; req.method = call.method; // req.data = call.args; return req; } } }
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2011 Kaltura Inc. // // 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/>. // // @ignore // =================================================================================================== package com.kaltura.delegates { import com.kaltura.KalturaClient; import com.kaltura.config.IKalturaConfig; import com.kaltura.config.KalturaConfig; import com.kaltura.core.KClassFactory; import com.kaltura.encryption.MD5; import com.kaltura.errors.KalturaError; import com.kaltura.events.KalturaEvent; import com.kaltura.net.KalturaCall; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.HTTPStatusEvent; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.FileReference; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.utils.Timer; import flash.utils.getDefinitionByName; public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate { public static var CONNECT_TIME:int = 120000; //120 secs public static var LOAD_TIME:int = 120000; //120 secs protected var connectTimer:Timer; protected var loadTimer:Timer; protected var _call:KalturaCall; protected var _config:KalturaConfig; protected var loader:URLLoader; protected var fileRef:FileReference; //Setters & getters public function get call():KalturaCall { return _call; } public function set call(newVal:KalturaCall):void { _call = newVal; } public function get config():IKalturaConfig { return _config; } public function set config(newVal:IKalturaConfig):void { _config = newVal as KalturaConfig; } public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) { this.call = call; this.config = config; if (!call) return; //maybe a multi request if (call.useTimeout) { connectTimer = new Timer(CONNECT_TIME, 1); connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout); loadTimer = new Timer(LOAD_TIME, 1); loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut); } execute(); } public function close():void { try { loader.close(); } catch (e:*) { } if (call.useTimeout) { connectTimer.stop(); loadTimer.stop(); } } protected function onConnectTimeout(event:TimerEvent):void { var kError:KalturaError = new KalturaError(); kError.errorCode = "CONNECTION_TIMEOUT"; kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client."; _call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); loadTimer.stop(); close(); } protected function onLoadTimeOut(event:TimerEvent):void { connectTimer.stop(); close(); var kError:KalturaError = new KalturaError(); kError.errorCode = "POST_TIMEOUT"; kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result."; _call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } protected function execute():void { if (call == null) { throw new Error('No call defined.'); } post(); //post the call } /** * Helper function for sending the call straight to the server */ protected function post():void { addOptionalArguments(); formatRequest(); sendRequest(); if (call.useTimeout) { connectTimer.start(); } } protected function formatRequest():void { //The configuration is stronger then the args if (_config.partnerId != null && (!_call.args["partnerId"] || _call.args["partnerId"]==-1)) _call.setRequestArgument("partnerId", _config.partnerId); if (_config.ks != null) _call.setRequestArgument("ks", _config.ks); if (_config.clientTag != null) _call.setRequestArgument("clientTag", _config.clientTag); _call.setRequestArgument("ignoreNull", _config.ignoreNull); _call.setRequestArgument("apiVersion", KalturaClient.API_VERSION); //Create signature hash. //call.setRequestArgument("kalsig", getMD5Checksum(call)); } protected function getMD5Checksum(call:KalturaCall):String { var props:Array = new Array(); for (var arg:String in call.args) props.push(arg); props.sort(); var s:String = ""; for each (var prop:String in props) { if ( call.args[prop] ) s += prop + call.args[prop]; } return MD5.encrypt(s); } protected function sendRequest():void { //construct the loader createURLLoader(); //Create signature hash. var kalsig:String = getMD5Checksum(call); //create the service request for normal calls var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;; if (_call.method == URLRequestMethod.GET) url += "&"; var req:URLRequest = new URLRequest(url); req.contentType = "application/x-www-form-urlencoded"; req.method = call.method; req.data = call.args; loader.dataFormat = URLLoaderDataFormat.TEXT; loader.load(req); } protected function createURLLoader():void { loader = new URLLoader(); loader.addEventListener(Event.COMPLETE, onDataComplete); loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus); loader.addEventListener(IOErrorEvent.IO_ERROR, onError); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); loader.addEventListener(Event.OPEN, onOpen); } protected function onHTTPStatus(event:HTTPStatusEvent):void { } protected function onOpen(event:Event):void { if (call.useTimeout) { connectTimer.stop(); loadTimer.start(); } } protected function addOptionalArguments():void { //add optional args here } // Event Handlers /** * try to process received data. * if procesing failed, let call handle the processing error * @param event load complete event */ protected function onDataComplete(event:Event):void { try { handleResult(XML(event.target.data)); } catch (e:Error) { var kErr:KalturaError = new KalturaError(); kErr.errorCode = String(e.errorID); kErr.errorMsg = e.message; _call.handleError(kErr); } } /** * handle io or security error events from the loader. * create relevant KalturaError, let the call process it. * @param event */ protected function onError(event:ErrorEvent):void { clean(); var kError:KalturaError = createKalturaError(event, loader.data); if (!kError) { kError = new KalturaError(); kError.errorMsg = event.text; kError.errorCode = event.type; // either IOErrorEvent.IO_ERROR or SecurityErrorEvent.SECURITY_ERROR } call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } /** * parse the server's response and let the call process it. * @param result server's response */ protected function handleResult(result:XML):void { clean(); var error:KalturaError = validateKalturaResponse(result); if (error == null) { var digestedResult:Object = parse(result); call.handleResult(digestedResult); } else { call.handleError(error); } } /** * stop timers and clean event listeners */ protected function clean():void { if (call.useTimeout) { connectTimer.stop(); loadTimer.stop(); } if (loader == null) { return; } loader.removeEventListener(Event.COMPLETE, onDataComplete); loader.removeEventListener(IOErrorEvent.IO_ERROR, onError); loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); loader.removeEventListener(Event.OPEN, onOpen); } /** * create the correct object and populate it with the given values. if the needed class is not found * in the file, a generic object is created with attributes matching the XML attributes. * Override this parssing function in the specific delegate to create the correct object. * @param result instance attributes * @return an instance of the class declared by the given XML. * */ public function parse(result:XML):* { //by defualt create the response object var cls:Class; try { cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class; } catch (e:Error) { cls = Object; } var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result); return obj; } /** * If the result string holds an error, return a KalturaError object with * relevant values. <br/> * Overide this to create validation object and fill it. * @param result the string returned from the server. * @return matching error object */ protected function validateKalturaResponse(result:String):KalturaError { var kError:KalturaError = null; var xml:XML = XML(result); if (xml.result.hasOwnProperty('error') && xml.result.error.hasOwnProperty('code') && xml.result.error.hasOwnProperty('message')) { kError = new KalturaError(); kError.errorCode = String(xml.result.error.code); kError.errorMsg = xml.result.error.message; dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } return kError; } /** * create error object and fill it with relevant details * @param event * @param loaderData * @return detailed KalturaError to be processed */ protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError { var ke:KalturaError = new KalturaError(); ke.errorMsg = event.text; ke.errorCode = event.type; return ke; } /** * create the url that is used for serve actions * @param call the KalturaCall that defines the required parameters * @return URLRequest with relevant parameters * */ public function getServeUrl(call:KalturaCall):URLRequest { var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action; for (var key:String in call.args) { url += "&" + key + "=" + call.args[key]; } var req:URLRequest = new URLRequest(url); req.contentType = "application/x-www-form-urlencoded"; req.method = call.method; // req.data = call.args; return req; } } }
fix client code to send partnerId from client config by default
fix client code to send partnerId from client config by default
ActionScript
agpl-3.0
kaltura/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp
b3707c6df3b826ed6c59eba9c3bbadc7920d9527
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; public class swfcat extends Sprite { private var output_text:TextField; private function puts(s:String):void { output_text.appendText(s + "\n"); } public function swfcat() { output_text = new TextField(); output_text.width = 400; output_text.height = 300; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); var s1:Socket = new Socket(); var s2:Socket = new Socket(); s1.addEventListener(Event.CONNECT, function (e:Event):void { puts("s1 Connected."); }); s1.addEventListener(Event.CLOSE, function (e:Event):void { puts("s1 Closed."); }); s1.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("s1 IO error: " + e.text + "."); }); s1.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("s1 Security error: " + e.text + "."); }); s1.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray; puts("s1 progress: " + e.bytesLoaded + "."); s1.readBytes(bytes, 0, e.bytesLoaded); s2.writeBytes(bytes); }); s2.addEventListener(Event.CONNECT, function (e:Event):void { puts("s2 Connected."); }); s2.addEventListener(Event.CLOSE, function (e:Event):void { puts("s2 Closed."); }); s2.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("s2 IO error: " + e.text + "."); }); s2.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("s2 Security error: " + e.text + "."); }); s2.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray; puts("s2 progress: " + e.bytesLoaded + "."); s2.readBytes(bytes, 0, e.bytesLoaded); s1.writeBytes(bytes); }); puts("Requesting connection."); s1.connect("10.32.16.133", 9998); s2.connect("10.32.16.133", 9999); puts("Connection requested."); } } }
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; public class swfcat extends Sprite { private var output_text:TextField; private function puts(s:String):void { output_text.appendText(s + "\n"); } public function swfcat() { output_text = new TextField(); output_text.width = 400; output_text.height = 300; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); var s1:Socket = new Socket(); var s2:Socket = new Socket(); s1.addEventListener(Event.CONNECT, function (e:Event):void { puts("s1 Connected."); }); s1.addEventListener(Event.CLOSE, function (e:Event):void { puts("s1 Closed."); }); s1.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("s1 IO error: " + e.text + "."); }); s1.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("s1 Security error: " + e.text + "."); }); s1.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); puts("s1 progress: " + e.bytesLoaded + "."); s1.readBytes(bytes, 0, e.bytesLoaded); puts("s1 bytes length: " + bytes.length + "."); s2.writeBytes(bytes); }); s2.addEventListener(Event.CONNECT, function (e:Event):void { puts("s2 Connected."); }); s2.addEventListener(Event.CLOSE, function (e:Event):void { puts("s2 Closed."); }); s2.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("s2 IO error: " + e.text + "."); }); s2.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("s2 Security error: " + e.text + "."); }); s2.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); puts("s2 progress: " + e.bytesLoaded + "."); s2.readBytes(bytes, 0, e.bytesLoaded); puts("s2 bytes length: " + bytes.length + "."); s1.writeBytes(bytes); }); puts("Requesting connection."); s1.connect("10.32.16.133", 9998); s2.connect("10.32.16.133", 9999); puts("Connection requested."); } } }
Fix the last commit; we must actually instantiate the ByteArrays.
Fix the last commit; we must actually instantiate the ByteArrays.
ActionScript
mit
arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy
9168559861b54f0b0af96553b09544927ab99e9d
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; public class swfcat extends Sprite { private var output_text:TextField; private function puts(s:String):void { output_text.appendText(s + "\n"); } public function swfcat() { output_text = new TextField(); output_text.width = 400; output_text.height = 300; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); var s1:Socket = new Socket(); var s2:Socket = new Socket(); s1.addEventListener(Event.CONNECT, function (e:Event):void { puts("s1 Connected."); }); s1.addEventListener(Event.CLOSE, function (e:Event):void { puts("s1 Closed."); }); s1.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("s1 IO error: " + e.text + "."); }); s1.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("s1 Security error: " + e.text + "."); }); s1.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); puts("s1 progress: " + e.bytesLoaded + "."); s1.readBytes(bytes, 0, e.bytesLoaded); puts("s1 bytes length: " + bytes.length + "."); s2.writeBytes(bytes); }); s2.addEventListener(Event.CONNECT, function (e:Event):void { puts("s2 Connected."); }); s2.addEventListener(Event.CLOSE, function (e:Event):void { puts("s2 Closed."); }); s2.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("s2 IO error: " + e.text + "."); }); s2.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("s2 Security error: " + e.text + "."); }); s2.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); puts("s2 progress: " + e.bytesLoaded + "."); s2.readBytes(bytes, 0, e.bytesLoaded); puts("s2 bytes length: " + bytes.length + "."); s1.writeBytes(bytes); }); puts("Requesting connection."); s1.connect("10.32.16.133", 9998); s2.connect("10.32.16.133", 9999); puts("Connection requested."); } } }
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; public class swfcat extends Sprite { private const TOR_ADDRESS:String = "upload.bamsoftware.com"; private const TOR_PORT:int = 9001; private const CLIENT_ADDRESS:String = "192.168.0.2"; private const CLIENT_PORT:int = 9001; private var output_text:TextField; private function puts(s:String):void { output_text.appendText(s + "\n"); } public function swfcat() { output_text = new TextField(); output_text.width = 400; output_text.height = 300; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); var s_t:Socket = new Socket(); var s_c:Socket = new Socket(); s_t.addEventListener(Event.CONNECT, function (e:Event):void { puts("Tor: connected."); }); s_t.addEventListener(Event.CLOSE, function (e:Event):void { puts("Tor: closed."); }); s_t.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Tor: I/O error: " + e.text + "."); }); s_t.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Tor: security error: " + e.text + "."); }); s_t.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_t.readBytes(bytes, 0, e.bytesLoaded); puts("Tor: read " + bytes.length + "."); s_c.writeBytes(bytes); }); s_c.addEventListener(Event.CONNECT, function (e:Event):void { puts("Client: connected."); }); s_c.addEventListener(Event.CLOSE, function (e:Event):void { puts("Client: closed."); }); s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Client: I/O error: " + e.text + "."); }); s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Client: security error: " + e.text + "."); }); s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_c.readBytes(bytes, 0, e.bytesLoaded); puts("Client: read " + bytes.length + "."); s_t.writeBytes(bytes); }); puts("Tor: connecting."); s_t.connect(TOR_ADDRESS, TOR_PORT); puts("Client: connecting."); s_c.connect(CLIENT_ADDRESS, CLIENT_PORT); } } }
Change socket variable names and point them at a real Tor relay and a hardcoded client.
Change socket variable names and point them at a real Tor relay and a hardcoded client.
ActionScript
mit
infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy
16e86dc4cdca97e7879eb816db8ccaecf1b6d813
src/aerys/minko/render/geometry/primitive/TorusGeometry.as
src/aerys/minko/render/geometry/primitive/TorusGeometry.as
package aerys.minko.render.geometry.primitive { 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; import aerys.minko.type.math.Vector4; public class TorusGeometry extends Geometry { private static const EPSILON : Number = 0.00001; private static const DTOR : Number = 0.01745329252; private var _radius : Number; private var _tube : Number; private var _segmentsR : uint; private var _segmentsT : uint; private var _arc : Number; public function TorusGeometry(radius : Number = 100., tube : Number = 40., segmentsR : uint = 8, segmentsT : uint = 6, arc : Number = Math.PI * 2., withUVs : Boolean = true, withNormals : Boolean = true, vertexStreamUsage : uint = StreamUsage.STATIC, indexStreamUsage : uint = StreamUsage.STATIC) { _radius = radius; _tube = tube; _segmentsR = segmentsR; _segmentsT = segmentsT; _arc = arc; super( new <IVertexStream>[buildVertexStream(vertexStreamUsage, withUVs, withNormals)], buildIndexStream(indexStreamUsage) ); } private function buildVertexStream(usage : uint, withUVs : Boolean, withNormals : Boolean) : VertexStream { var vertexData : Vector.<Number> = new <Number>[]; for (var j : uint = 0; j <= _segmentsR; ++j) { for (var i : uint = 0; i <= _segmentsT; ++i) { var u : Number = i / _segmentsT * _arc; var v : Number = j / _segmentsR * _arc; var cosU : Number = Math.cos(u); var sinU : Number = Math.sin(u); var cosV : Number = Math.cos(v); var x : Number = (_radius + _tube * cosV) * cosU; var y : Number = (_radius + _tube * cosV) * sinU; var z : Number = _tube * Math.sin(v); vertexData.push(x, y, z); if (withUVs) vertexData.push(i / _segmentsT, 1 - j / _segmentsR); if (withNormals) { var normalX : Number = x - _radius * cosU; var normalY : Number = y - _radius * sinU; var normalZ : Number = z; var mag : Number = normalX * normalX + normalY * normalY + normalZ * normalZ; normalX /= mag; normalY /= mag; normalZ /= mag; vertexData.push(normalX, normalY, normalZ); } } } var format : VertexFormat = new VertexFormat(VertexComponent.XYZ); if (withUVs) format.addComponent(VertexComponent.UV); if (withNormals) format.addComponent(VertexComponent.NORMAL); return new VertexStream(usage, format, vertexData); } private function buildIndexStream(usage : uint) : IndexStream { var indices : Vector.<uint> = new <uint>[]; for (var j : uint = 1; j <= _segmentsR; ++j) { for (var i : uint = 1; i <= _segmentsT; ++i) { var a : uint = (_segmentsT + 1) * j + i - 1; var b : uint = (_segmentsT + 1) * (j - 1) + i - 1; var c : uint = (_segmentsT + 1) * (j - 1) + i; var d : uint = (_segmentsT + 1) * j + i; indices.push(a, c, b, a, d, c); } } return new IndexStream(usage, indices); } } }
package aerys.minko.render.geometry.primitive { 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; import aerys.minko.type.math.Vector4; public class TorusGeometry extends Geometry { private static const EPSILON : Number = 0.00001; private static const DTOR : Number = 0.01745329252; private var _radius : Number; private var _tube : Number; private var _segmentsR : uint; private var _segmentsT : uint; private var _arc : Number; public function TorusGeometry(radius : Number = .375, tube : Number = .125, segmentsR : uint = 10, segmentsT : uint = 8, arc : Number = Math.PI * 2., withUVs : Boolean = true, withNormals : Boolean = true, vertexStreamUsage : uint = StreamUsage.STATIC, indexStreamUsage : uint = StreamUsage.STATIC) { _radius = radius; _tube = tube; _segmentsR = segmentsR; _segmentsT = segmentsT; _arc = arc; super( new <IVertexStream>[buildVertexStream(vertexStreamUsage, withUVs, withNormals)], buildIndexStream(indexStreamUsage) ); } private function buildVertexStream(usage : uint, withUVs : Boolean, withNormals : Boolean) : VertexStream { var vertexData : Vector.<Number> = new <Number>[]; for (var j : uint = 0; j <= _segmentsR; ++j) { for (var i : uint = 0; i <= _segmentsT; ++i) { var u : Number = i / _segmentsT * _arc; var v : Number = j / _segmentsR * _arc; var cosU : Number = Math.cos(u); var sinU : Number = Math.sin(u); var cosV : Number = Math.cos(v); var x : Number = (_radius + _tube * cosV) * cosU; var y : Number = (_radius + _tube * cosV) * sinU; var z : Number = _tube * Math.sin(v); vertexData.push(x, y, z); if (withUVs) vertexData.push(i / _segmentsT, 1 - j / _segmentsR); if (withNormals) { var normalX : Number = x - _radius * cosU; var normalY : Number = y - _radius * sinU; var normalZ : Number = z; var mag : Number = normalX * normalX + normalY * normalY + normalZ * normalZ; normalX /= mag; normalY /= mag; normalZ /= mag; vertexData.push(normalX, normalY, normalZ); } } } var format : VertexFormat = new VertexFormat(VertexComponent.XYZ); if (withUVs) format.addComponent(VertexComponent.UV); if (withNormals) format.addComponent(VertexComponent.NORMAL); return new VertexStream(usage, format, vertexData); } private function buildIndexStream(usage : uint) : IndexStream { var indices : Vector.<uint> = new <uint>[]; for (var j : uint = 1; j <= _segmentsR; ++j) { for (var i : uint = 1; i <= _segmentsT; ++i) { var a : uint = (_segmentsT + 1) * j + i - 1; var b : uint = (_segmentsT + 1) * (j - 1) + i - 1; var c : uint = (_segmentsT + 1) * (j - 1) + i; var d : uint = (_segmentsT + 1) * j + i; indices.push(a, c, b, a, d, c); } } return new IndexStream(usage, indices); } } }
fix TorusGeometry to be unit sized by default
fix TorusGeometry to be unit sized by default
ActionScript
mit
aerys/minko-as3
f0b83ce52c2d9133f0a105a5e1c72a46a02d11df
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMP2TSFileHandler.as
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMP2TSFileHandler.as
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.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 the at.matthew.httpstreaming package. * * The Initial Developer of the Original Code is * Matthew Kaufman. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ package org.denivip.osmf.net.httpstreaming.hls { import flash.utils.ByteArray; import flash.utils.IDataInput; import com.hurlant.util.Hex; import org.denivip.osmf.utility.decrypt.AES; import org.osmf.logging.Log; import org.osmf.logging.Logger; import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase; [Event(name="notifySegmentDuration", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] [Event(name="notifyTimeBias", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] public class HTTPStreamingMP2TSFileHandler extends HTTPStreamingFileHandlerBase { private var _syncFound:Boolean; private var _pmtPID:uint; private var _audioPID:uint; private var _videoPID:uint; private var _mp3AudioPID:uint; private var _audioPES:HTTPStreamingMP2PESAudio; private var _videoPES:HTTPStreamingMP2PESVideo; private var _mp3audioPES:HTTPStreamingMp3Audio2ToPESAudio; private var _cachedOutputBytes:ByteArray; private var alternatingYieldCounter:int = 0; private var _key:HTTPStreamingM3U8IndexKey = null; private var _iv:ByteArray = null; private var _decryptBuffer:ByteArray = new ByteArray; // AES-128 specific variables private var _decryptAES:AES = null; public function HTTPStreamingMP2TSFileHandler() { _audioPES = new HTTPStreamingMP2PESAudio; _videoPES = new HTTPStreamingMP2PESVideo; _mp3audioPES = new HTTPStreamingMp3Audio2ToPESAudio; } override public function beginProcessFile(seek:Boolean, seekTime:Number):void { _syncFound = false; } override public function get inputBytesNeeded():Number { return _syncFound ? 187 : 1; } override public function processFileSegment(input:IDataInput):ByteArray { var bytesAvailableStart:uint = input.bytesAvailable; var output:ByteArray; if (_cachedOutputBytes !== null) { output = _cachedOutputBytes; _cachedOutputBytes = null; } else { output = new ByteArray(); } while (true) { if(!_syncFound) { if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 16) { if (_decryptBuffer.bytesAvailable < 1) { break; } } else { if (!decryptToBuffer(input, 16)) { break; } } if (_decryptBuffer.readByte() == 0x47) { _syncFound = true; } } } else { if(input.bytesAvailable < 1) break; if(input.readByte() == 0x47) _syncFound = true; } } else { _syncFound = false; var packet:ByteArray = new ByteArray(); if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 176) { if (_decryptBuffer.bytesAvailable < 187) { break; } } else { var bytesLeft:uint = input.bytesAvailable - 176; if (bytesLeft > 0 && bytesLeft < 15) { if (!decryptToBuffer(input, input.bytesAvailable)) { break; } } else { if (!decryptToBuffer(input, 176)) { break; } } } _decryptBuffer.readBytes(packet, 0, 187); } } else { if(input.bytesAvailable < 187) break; input.readBytes(packet, 0, 187); } var result:ByteArray = processPacket(packet); if (result !== null) { output.writeBytes(result); } if (bytesAvailableStart - input.bytesAvailable > 10000) { alternatingYieldCounter = (alternatingYieldCounter + 1) & 0x03; if (alternatingYieldCounter /*& 0x01 === 1*/) { _cachedOutputBytes = output; return null; } break; } } } output.position = 0; return output.length === 0 ? null : output; } private function decryptToBuffer(input:IDataInput, blockSize:int):Boolean{ if (_key) { // Clear buffer if (_decryptBuffer.bytesAvailable == 0) { _decryptBuffer.clear(); } if (_key.type == "AES-128" && blockSize % 16 == 0 && _key.key) { if (!_decryptAES) { _decryptAES = new AES(_key.key); _decryptAES.pad = "none"; _decryptAES.iv = _iv; } // Save buffer position var currentPosition:uint = _decryptBuffer.position; _decryptBuffer.position += _decryptBuffer.bytesAvailable; // Save block to decrypt var decrypt:ByteArray = new ByteArray; input.readBytes(decrypt, 0, blockSize); // Save new IV from ciphertext var newIv:ByteArray = new ByteArray; decrypt.position += (decrypt.bytesAvailable-16); decrypt.readBytes(newIv, 0, 16); decrypt.position = 0; // Decrypt if (input.bytesAvailable == 0) { _decryptAES.pad = "pkcs7"; } _decryptAES.decrypt(decrypt); decrypt.position = 0; // Write into buffer _decryptBuffer.writeBytes(decrypt); _decryptBuffer.position = currentPosition; // Update AES IV _decryptAES.iv = newIv; return true; } } return false; } override public function endProcessFile(input:IDataInput):ByteArray { _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; return null; } public function resetCache():void{ _cachedOutputBytes = null; alternatingYieldCounter = 0; _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set initialOffset(offset:Number):void{ offset *= 1000; // convert to ms _videoPES.initialTimestamp = offset; _audioPES.initialTimestamp = offset; _mp3audioPES.initialTimestamp = offset; } public function set key(key:HTTPStreamingM3U8IndexKey):void { _key = key; if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set iv(iv:String):void { if (iv) { _iv = Hex.toArray(iv); } } private function processPacket(packet:ByteArray):ByteArray { // decode rest of transport stream prefix (after the 0x47 flag byte) // top of second byte var value:uint = packet.readUnsignedByte(); //var tei:Boolean = Boolean(value & 0x80); // error indicator var pusi:Boolean = Boolean(value & 0x40); // payload unit start indication //var tpri:Boolean = Boolean(value & 0x20); // transport priority indication // bottom of second byte and all of third value <<= 8; value += packet.readUnsignedByte(); var pid:uint = value & 0x1fff; // packet ID // fourth byte value = packet.readUnsignedByte(); //var scramblingControl:uint = (value >> 6) & 0x03; // scrambling control bits var hasAF:Boolean = Boolean(value & 0x20); // has adaptation field var hasPD:Boolean = Boolean(value & 0x10); // has payload data //var ccount:uint = value & 0x0f; // continuty count // technically hasPD without hasAF is an error, see spec if(hasAF) { // process adaptation field // don't care about flags // don't care about clocks here var af:uint = packet.readUnsignedByte(); packet.position += af; // skip to end } return hasPD ? processES(pid, pusi, packet) : null; } private function processES(pid:uint, pusi:Boolean, packet:ByteArray):ByteArray { var output:ByteArray = null; if(pid == 0) // PAT { if(pusi) processPAT(packet); } else if(pid == _pmtPID) { if(pusi) processPMT(packet); } else if(pid == _audioPID) { output = _audioPES.processES(pusi, packet); } else if(pid == _videoPID) { output = _videoPES.processES(pusi, packet); } else if(pid == _mp3AudioPID) { output = _mp3audioPES.processES(pusi, packet); } return output; } private function processPAT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint packet.readUnsignedByte(); // tableID:uint var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring misc and reserved bits packet.position += 5; // skip tsid + version/cni + sec# + last sec# remaining -= 5; while(remaining > 4) { packet.readUnsignedShort(); // program number _pmtPID = packet.readUnsignedShort() & 0x1fff; // 13 bits remaining -= 4; //return; // immediately after reading the first pmt ID, if we don't we get the LAST one } // and ignore the CRC (4 bytes) } private function processPMT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint var tableID:uint = packet.readUnsignedByte(); if (tableID != 0x02) { CONFIG::LOGGING { logger.warn("PAT pointed to PMT that isn't PMT"); } return; // don't try to parse it } var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring section syntax and reserved packet.position += 7; // skip program num, rserved, version, cni, section num, last section num, reserved, PCR PID remaining -= 7; var piLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 2; packet.position += piLen; // skip program info remaining -= piLen; while(remaining > 4) { var type:uint = packet.readUnsignedByte(); var pid:uint = packet.readUnsignedShort() & 0x1fff; var esiLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 5; packet.position += esiLen; remaining -= esiLen; switch(type) { case 0x1b: // H.264 video _videoPID = pid; break; case 0x0f: // AAC Audio / ADTS _audioPID = pid; break; case 0x03: // MP3 Audio (3 & 4) case 0x04: _mp3AudioPID = pid; break; default: CONFIG::LOGGING { logger.error("unsupported type "+type.toString(16)+" in PMT"); } break; } } // and ignore CRC } override public function flushFileSegment(input:IDataInput):ByteArray { var flvBytes:ByteArray = new ByteArray(); var flvBytesVideo:ByteArray = _videoPES.processES(false, null, true); var flvBytesAudio:ByteArray = _audioPES.processES(false, null, true); if(flvBytesVideo) flvBytes.readBytes(flvBytesVideo); if(flvBytesAudio) flvBytes.readBytes(flvBytesAudio); return flvBytes; } CONFIG::LOGGING { private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMP2TSFileHandler') as Logger; } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.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 the at.matthew.httpstreaming package. * * The Initial Developer of the Original Code is * Matthew Kaufman. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ package org.denivip.osmf.net.httpstreaming.hls { import flash.utils.ByteArray; import flash.utils.IDataInput; import com.hurlant.util.Hex; import org.denivip.osmf.utility.decrypt.AES; import org.osmf.logging.Log; import org.osmf.logging.Logger; import org.osmf.net.httpstreaming.HTTPStreamingFileHandlerBase; [Event(name="notifySegmentDuration", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] [Event(name="notifyTimeBias", type="org.osmf.events.HTTPStreamingFileHandlerEvent")] public class HTTPStreamingMP2TSFileHandler extends HTTPStreamingFileHandlerBase { private var _syncFound:Boolean; private var _pmtPID:uint; private var _audioPID:uint; private var _videoPID:uint; private var _mp3AudioPID:uint; private var _audioPES:HTTPStreamingMP2PESAudio; private var _videoPES:HTTPStreamingMP2PESVideo; private var _mp3audioPES:HTTPStreamingMp3Audio2ToPESAudio; private var _cachedOutputBytes:ByteArray; private var alternatingYieldCounter:int = 0; private var _key:HTTPStreamingM3U8IndexKey = null; private var _iv:ByteArray = null; private var _decryptBuffer:ByteArray = new ByteArray; // AES-128 specific variables private var _decryptAES:AES = null; public function HTTPStreamingMP2TSFileHandler() { _audioPES = new HTTPStreamingMP2PESAudio; _videoPES = new HTTPStreamingMP2PESVideo; _mp3audioPES = new HTTPStreamingMp3Audio2ToPESAudio; } override public function beginProcessFile(seek:Boolean, seekTime:Number):void { _syncFound = false; } override public function get inputBytesNeeded():Number { return _syncFound ? 187 : 1; } override public function processFileSegment(input:IDataInput):ByteArray { var bytesAvailableStart:uint = input.bytesAvailable; var output:ByteArray; if (_cachedOutputBytes !== null) { output = _cachedOutputBytes; _cachedOutputBytes = null; } else { output = new ByteArray(); } while (true) { if(!_syncFound) { if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 16) { if (_decryptBuffer.bytesAvailable < 1) { break; } } else { if (!decryptToBuffer(input, 16)) { break; } } if (_decryptBuffer.readByte() == 0x47) { _syncFound = true; } } } else { if(input.bytesAvailable < 1) break; if(input.readByte() == 0x47) _syncFound = true; } } else { var packet:ByteArray = new ByteArray(); if (_key) { if (_key.type == "AES-128") { if (input.bytesAvailable < 176) { if (_decryptBuffer.bytesAvailable < 187) { break; } } else { var bytesLeft:uint = input.bytesAvailable - 176; if (bytesLeft > 0 && bytesLeft < 15) { if (!decryptToBuffer(input, input.bytesAvailable)) { break; } } else { if (!decryptToBuffer(input, 176)) { break; } } } _decryptBuffer.readBytes(packet, 0, 187); } } else { if(input.bytesAvailable < 187) break; input.readBytes(packet, 0, 187); } _syncFound = false; var result:ByteArray = processPacket(packet); if (result !== null) { output.writeBytes(result); } if (bytesAvailableStart - input.bytesAvailable > 10000) { alternatingYieldCounter = (alternatingYieldCounter + 1) & 0x03; if (alternatingYieldCounter /*& 0x01 === 1*/) { _cachedOutputBytes = output; return null; } break; } } } output.position = 0; return output.length === 0 ? null : output; } private function decryptToBuffer(input:IDataInput, blockSize:int):Boolean{ if (_key) { // Clear buffer if (_decryptBuffer.bytesAvailable == 0) { _decryptBuffer.clear(); } if (_key.type == "AES-128" && blockSize % 16 == 0 && _key.key) { if (!_decryptAES) { _decryptAES = new AES(_key.key); _decryptAES.pad = "none"; _decryptAES.iv = _iv; } // Save buffer position var currentPosition:uint = _decryptBuffer.position; _decryptBuffer.position += _decryptBuffer.bytesAvailable; // Save block to decrypt var decrypt:ByteArray = new ByteArray; input.readBytes(decrypt, 0, blockSize); // Save new IV from ciphertext var newIv:ByteArray = new ByteArray; decrypt.position += (decrypt.bytesAvailable-16); decrypt.readBytes(newIv, 0, 16); decrypt.position = 0; // Decrypt if (input.bytesAvailable == 0) { _decryptAES.pad = "pkcs7"; } _decryptAES.decrypt(decrypt); decrypt.position = 0; // Write into buffer _decryptBuffer.writeBytes(decrypt); _decryptBuffer.position = currentPosition; // Update AES IV _decryptAES.iv = newIv; return true; } } return false; } override public function endProcessFile(input:IDataInput):ByteArray { _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; return null; } public function resetCache():void{ _cachedOutputBytes = null; alternatingYieldCounter = 0; _decryptBuffer.clear(); if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set initialOffset(offset:Number):void{ offset *= 1000; // convert to ms _videoPES.initialTimestamp = offset; _audioPES.initialTimestamp = offset; _mp3audioPES.initialTimestamp = offset; } public function set key(key:HTTPStreamingM3U8IndexKey):void { _key = key; if (_decryptAES) { _decryptAES.destroy(); } _decryptAES = null; } public function set iv(iv:String):void { if (iv) { _iv = Hex.toArray(iv); } } private function processPacket(packet:ByteArray):ByteArray { // decode rest of transport stream prefix (after the 0x47 flag byte) // top of second byte var value:uint = packet.readUnsignedByte(); //var tei:Boolean = Boolean(value & 0x80); // error indicator var pusi:Boolean = Boolean(value & 0x40); // payload unit start indication //var tpri:Boolean = Boolean(value & 0x20); // transport priority indication // bottom of second byte and all of third value <<= 8; value += packet.readUnsignedByte(); var pid:uint = value & 0x1fff; // packet ID // fourth byte value = packet.readUnsignedByte(); //var scramblingControl:uint = (value >> 6) & 0x03; // scrambling control bits var hasAF:Boolean = Boolean(value & 0x20); // has adaptation field var hasPD:Boolean = Boolean(value & 0x10); // has payload data //var ccount:uint = value & 0x0f; // continuty count // technically hasPD without hasAF is an error, see spec if(hasAF) { // process adaptation field // don't care about flags // don't care about clocks here var af:uint = packet.readUnsignedByte(); packet.position += af; // skip to end } return hasPD ? processES(pid, pusi, packet) : null; } private function processES(pid:uint, pusi:Boolean, packet:ByteArray):ByteArray { var output:ByteArray = null; if(pid == 0) // PAT { if(pusi) processPAT(packet); } else if(pid == _pmtPID) { if(pusi) processPMT(packet); } else if(pid == _audioPID) { output = _audioPES.processES(pusi, packet); } else if(pid == _videoPID) { output = _videoPES.processES(pusi, packet); } else if(pid == _mp3AudioPID) { output = _mp3audioPES.processES(pusi, packet); } return output; } private function processPAT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint packet.readUnsignedByte(); // tableID:uint var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring misc and reserved bits packet.position += 5; // skip tsid + version/cni + sec# + last sec# remaining -= 5; while(remaining > 4) { packet.readUnsignedShort(); // program number _pmtPID = packet.readUnsignedShort() & 0x1fff; // 13 bits remaining -= 4; //return; // immediately after reading the first pmt ID, if we don't we get the LAST one } // and ignore the CRC (4 bytes) } private function processPMT(packet:ByteArray):void { packet.readUnsignedByte(); // pointer:uint var tableID:uint = packet.readUnsignedByte(); if (tableID != 0x02) { CONFIG::LOGGING { logger.warn("PAT pointed to PMT that isn't PMT"); } return; // don't try to parse it } var remaining:uint = packet.readUnsignedShort() & 0x03ff; // ignoring section syntax and reserved packet.position += 7; // skip program num, rserved, version, cni, section num, last section num, reserved, PCR PID remaining -= 7; var piLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 2; packet.position += piLen; // skip program info remaining -= piLen; while(remaining > 4) { var type:uint = packet.readUnsignedByte(); var pid:uint = packet.readUnsignedShort() & 0x1fff; var esiLen:uint = packet.readUnsignedShort() & 0x0fff; remaining -= 5; packet.position += esiLen; remaining -= esiLen; switch(type) { case 0x1b: // H.264 video _videoPID = pid; break; case 0x0f: // AAC Audio / ADTS _audioPID = pid; break; case 0x03: // MP3 Audio (3 & 4) case 0x04: _mp3AudioPID = pid; break; default: CONFIG::LOGGING { logger.error("unsupported type "+type.toString(16)+" in PMT"); } break; } } // and ignore CRC } override public function flushFileSegment(input:IDataInput):ByteArray { var flvBytes:ByteArray = new ByteArray(); var flvBytesVideo:ByteArray = _videoPES.processES(false, null, true); var flvBytesAudio:ByteArray = _audioPES.processES(false, null, true); if(flvBytesVideo) flvBytes.readBytes(flvBytesVideo); if(flvBytesAudio) flvBytes.readBytes(flvBytesAudio); return flvBytes; } CONFIG::LOGGING { private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMP2TSFileHandler') as Logger; } } }
Fix bug where syncFound was flagged as false incorrectly
Fix bug where syncFound was flagged as false incorrectly This was causing byte-level sync issues with throttled (and potentially other) streams
ActionScript
isc
denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,mruse/osmf-hls-plugin,denivip/osmf-hls-plugin
d19c96fe24555677b9b6c4d7c2661515bfe1a93a
src/org/mangui/hls/demux/Nalu.as
src/org/mangui/hls/demux/Nalu.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.demux { import flash.utils.ByteArray; CONFIG::LOGGING { import org.mangui.hls.HLSSettings; import org.mangui.hls.utils.Log; } /** Constants and utilities for the H264 video format. **/ public class Nalu { private static var scratchEscapePositions:Array = new Array(10); private static var _audNalu : ByteArray; // static initializer { _audNalu = new ByteArray(); _audNalu.length = 2; _audNalu.writeByte(0x09); _audNalu.writeByte(0xF0); }; /** Return an array with NAL delimiter indexes. **/ public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> { var len : uint = nalu.length,i : uint = position; var unitHeader : int,lastUnitHeader : int = 0; var unitStart : int,lastUnitStart : int = 0; var unitType : int,lastUnitType : int = 0; var audFound : Boolean = false; var value : uint,state : uint = 0; var units : Vector.<VideoFrame> = new Vector.<VideoFrame>(); // Loop through data to find NAL startcodes. while (i < len) { // finding 3 or 4-byte start codes (00 00 01 OR 00 00 00 01) value = nalu[i++]; switch(state) { case 0: if(!value) { state = 1; // unitHeader is NAL header offset unitHeader=i-1; } break; case 1: if(value) { state = 0; } else { state = 2; } break; case 2: case 3: if(value) { if(value === 1 && i < len) { unitType = nalu[i] & 0x1f; if(unitType == 9) { audFound = true; } if(lastUnitStart) { // use Math.min(4,...) as max header size is 4. // in case there are any leading zeros // such as 00 00 00 00 00 00 01 // ^^ // we need to ignore them as they are part of previous NAL unit units.push(new VideoFrame(Math.min(4,lastUnitStart-lastUnitHeader), i-state-1-lastUnitStart, lastUnitStart, lastUnitType)); } lastUnitStart = i; lastUnitType = unitType; lastUnitHeader = unitHeader; if(audFound == true && (unitType === 1 || unitType === 5)) { // OPTI !!! if AUD unit already parsed and if IDR/NDR unit, consider it is last NALu i = len; } } state = 0; } else { state = 3; } break; default: break; } } //push last unit if(lastUnitStart) { units.push(new VideoFrame(Math.min(4,lastUnitStart-lastUnitHeader), len-lastUnitStart, lastUnitStart, lastUnitType)); } // Reset position and return results. CONFIG::LOGGING { if (HLSSettings.logDebug2) { /** H264 NAL unit names. **/ const NAMES : Array = ['Unspecified',// 0 'NDR', // 1 'Partition A', // 2 'Partition B', // 3 'Partition C', // 4 'IDR', // 5 'SEI', // 6 'SPS', // 7 'PPS', // 8 'AUD', // 9 'End of Sequence', // 10 'End of Stream', // 11 'Filler Data'// 12 ]; if (units.length) { var txt : String = "AVC: "; for (i = 0; i < units.length; i++) { txt += NAMES[units[i].type] + ","; //+ ":" + units[i].length } Log.debug2(txt.substr(0,txt.length-1) + " slices"); } else { Log.debug2('AVC: no NALU slices found'); } } } nalu.position = position; return units; }; public static function get AUD():ByteArray { return _audNalu; } private static function findNextUnescapeIndex(bytes : ByteArray, offset:int, limit:int):int { for (var i:int = offset; i < limit - 2; i++) { if (bytes[i] == 0x00 && bytes[i + 1] == 0x00 && bytes[i + 2] == 0x03) { return i; } } return limit; } private static function arrayCopy(src:ByteArray, srcPos:int, dest:ByteArray, destPos:int, length:int):void { var iterations:int = Math.min(Math.min(length, src.length - srcPos), dest.length - destPos); for(var i:int = 0; i < iterations; i++) dest[destPos + i] = src[srcPos + i]; } public static function unescapeStream(data : ByteArray, position: int,limit: uint):int { var scratchEscapeCount:int = 0; while (position < limit) { position = findNextUnescapeIndex(data, position, limit); if (position < limit) { if (scratchEscapePositions.length <= scratchEscapeCount) { // Grow scratchEscapePositions to hold a larger number of positions. scratchEscapePositions = scratchEscapePositions.concat(new Array(10)); } scratchEscapePositions[scratchEscapeCount++] = position; position += 3; } } var unescapedLength:int = limit - scratchEscapeCount; var escapedPosition:int = 0; // The position being read from. var unescapedPosition:int = 0; // The position being written to. for (var i:int = 0; i < scratchEscapeCount; i++) { var nextEscapePosition:int = scratchEscapePositions[i]; var copyLength:int = nextEscapePosition - escapedPosition; arrayCopy(data, escapedPosition, data, unescapedPosition, copyLength); unescapedPosition += copyLength; data[unescapedPosition++] = 0; data[unescapedPosition++] = 0; escapedPosition += copyLength + 3; } var remainingLength:int = unescapedLength - unescapedPosition; arrayCopy(data, escapedPosition, data, unescapedPosition, remainingLength); return unescapedLength; } } }
/* 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.demux { import flash.utils.ByteArray; CONFIG::LOGGING { import org.mangui.hls.HLSSettings; import org.mangui.hls.utils.Log; } /** Constants and utilities for the H264 video format. **/ public class Nalu { private static var _audNalu : ByteArray; // static initializer { _audNalu = new ByteArray(); _audNalu.length = 2; _audNalu.writeByte(0x09); _audNalu.writeByte(0xF0); }; /** Return an array with NAL delimiter indexes. **/ public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> { var len : uint = nalu.length,i : uint = position; var unitHeader : int,lastUnitHeader : int = 0; var unitStart : int,lastUnitStart : int = 0; var unitType : int,lastUnitType : int = 0; var audFound : Boolean = false; var value : uint,state : uint = 0; var units : Vector.<VideoFrame> = new Vector.<VideoFrame>(); // Loop through data to find NAL startcodes. while (i < len) { // finding 3 or 4-byte start codes (00 00 01 OR 00 00 00 01) value = nalu[i++]; switch(state) { case 0: if(!value) { state = 1; // unitHeader is NAL header offset unitHeader=i-1; } break; case 1: if(value) { state = 0; } else { state = 2; } break; case 2: case 3: if(value) { if(value === 1 && i < len) { unitType = nalu[i] & 0x1f; if(unitType == 9) { audFound = true; } if(lastUnitStart) { // use Math.min(4,...) as max header size is 4. // in case there are any leading zeros // such as 00 00 00 00 00 00 01 // ^^ // we need to ignore them as they are part of previous NAL unit units.push(new VideoFrame(Math.min(4,lastUnitStart-lastUnitHeader), i-state-1-lastUnitStart, lastUnitStart, lastUnitType)); } lastUnitStart = i; lastUnitType = unitType; lastUnitHeader = unitHeader; if(audFound == true && (unitType === 1 || unitType === 5)) { // OPTI !!! if AUD unit already parsed and if IDR/NDR unit, consider it is last NALu i = len; } } state = 0; } else { state = 3; } break; default: break; } } //push last unit if(lastUnitStart) { units.push(new VideoFrame(Math.min(4,lastUnitStart-lastUnitHeader), len-lastUnitStart, lastUnitStart, lastUnitType)); } // Reset position and return results. CONFIG::LOGGING { if (HLSSettings.logDebug2) { /** H264 NAL unit names. **/ const NAMES : Array = ['Unspecified',// 0 'NDR', // 1 'Partition A', // 2 'Partition B', // 3 'Partition C', // 4 'IDR', // 5 'SEI', // 6 'SPS', // 7 'PPS', // 8 'AUD', // 9 'End of Sequence', // 10 'End of Stream', // 11 'Filler Data'// 12 ]; if (units.length) { var txt : String = "AVC: "; for (i = 0; i < units.length; i++) { txt += NAMES[units[i].type] + ","; //+ ":" + units[i].length } Log.debug2(txt.substr(0,txt.length-1) + " slices"); } else { Log.debug2('AVC: no NALU slices found'); } } } nalu.position = position; return units; }; public static function get AUD():ByteArray { return _audNalu; } private static function findNextUnescapeIndex(bytes : ByteArray, offset:int, limit:int):int { for (var i:int = offset; i < limit - 2; i++) { if (bytes[i] == 0x00 && bytes[i + 1] == 0x00 && bytes[i + 2] == 0x03) { return i; } } return limit; } private static function arrayCopy(src:ByteArray, srcPos:int, dest:ByteArray, destPos:int, length:int):void { var iterations:int = Math.min(Math.min(length, src.length - srcPos), dest.length - destPos); for(var i:int = 0; i < iterations; i++) dest[destPos + i] = src[srcPos + i]; } public static function unescapeStream(data : ByteArray, position: int,limit: uint):int { var scratchEscapeCount:int = 0; var scratchEscapePositions:Array = new Array(10); while (position < limit) { position = findNextUnescapeIndex(data, position, limit); if (position < limit) { if (scratchEscapePositions.length <= scratchEscapeCount) { // Grow scratchEscapePositions to hold a larger number of positions. scratchEscapePositions = scratchEscapePositions.concat(new Array(10)); } scratchEscapePositions[scratchEscapeCount++] = position; position += 3; } } var unescapedLength:int = limit - scratchEscapeCount; var escapedPosition:int = 0; // The position being read from. var unescapedPosition:int = 0; // The position being written to. for (var i:int = 0; i < scratchEscapeCount; i++) { var nextEscapePosition:int = scratchEscapePositions[i]; var copyLength:int = nextEscapePosition - escapedPosition; arrayCopy(data, escapedPosition, data, unescapedPosition, copyLength); unescapedPosition += copyLength; data[unescapedPosition++] = 0; data[unescapedPosition++] = 0; escapedPosition += copyLength + 3; } var remainingLength:int = unescapedLength - unescapedPosition; arrayCopy(data, escapedPosition, data, unescapedPosition, remainingLength); return unescapedLength; } } }
move scratchEscapePositions var inside unescapeStream method
move scratchEscapePositions var inside unescapeStream method
ActionScript
mpl-2.0
hola/flashls,hola/flashls,clappr/flashls,mangui/flashls,vidible/vdb-flashls,neilrackett/flashls,fixedmachine/flashls,clappr/flashls,jlacivita/flashls,vidible/vdb-flashls,neilrackett/flashls,fixedmachine/flashls,jlacivita/flashls,tedconf/flashls,mangui/flashls,tedconf/flashls
abdf07b3a902ffe6403103e886ce8b7f568618b5
WeaveUI/src/weave/visualization/plotters/PieChartPlotter.as
WeaveUI/src/weave/visualization/plotters/PieChartPlotter.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.visualization.plotters { import flash.display.BitmapData; import flash.display.Graphics; import flash.display.Shape; import flash.geom.Point; import mx.controls.Alert; import weave.Weave; import weave.api.data.IAttributeColumn; import weave.api.data.IQualifiedKey; import weave.api.linkSessionState; import weave.api.primitives.IBounds2D; import weave.data.AttributeColumns.DynamicColumn; import weave.data.AttributeColumns.EquationColumn; import weave.data.AttributeColumns.FilteredColumn; import weave.data.AttributeColumns.SortedColumn; import weave.primitives.Bounds2D; import weave.utils.BitmapText; import weave.utils.ColumnUtils; import weave.visualization.plotters.styles.DynamicFillStyle; import weave.visualization.plotters.styles.DynamicLineStyle; import weave.visualization.plotters.styles.SolidFillStyle; import weave.visualization.plotters.styles.SolidLineStyle; /** * PieChartPlotter * * @author adufilie */ public class PieChartPlotter extends AbstractPlotter { public function PieChartPlotter() { init(); } private var _beginRadians:EquationColumn; private var _spanRadians:EquationColumn; private var _filteredData:FilteredColumn; private var _labelColumn:DynamicColumn = new DynamicColumn(); public function get data():DynamicColumn { return _filteredData.internalDynamicColumn; } public function get label():DynamicColumn {return _labelColumn;} public const lineStyle:DynamicLineStyle = new DynamicLineStyle(SolidLineStyle); public const fillStyle:DynamicFillStyle = new DynamicFillStyle(SolidFillStyle); private function init():void { var fill:SolidFillStyle = fillStyle.internalObject as SolidFillStyle; fill.color.internalDynamicColumn.globalName = Weave.DEFAULT_COLOR_COLUMN; _beginRadians = new EquationColumn(); _beginRadians.equation.value = "0.5 * PI + getRunningTotal(spanRadians) - getNumber(spanRadians)"; _spanRadians = _beginRadians.requestVariable("spanRadians", EquationColumn, true); _spanRadians.equation.value = "getNumber(sortedData) / getSum(sortedData) * 2 * PI"; var sortedData:SortedColumn = _spanRadians.requestVariable("sortedData", SortedColumn, true); _filteredData = sortedData.internalDynamicColumn.requestLocalObject(FilteredColumn, true); linkSessionState(keySet.keyFilter, _filteredData.filter); registerSpatialProperties(data); registerNonSpatialProperties(fillStyle, lineStyle, label); setKeySource(_filteredData); } override protected function addRecordGraphicsToTempShape(recordKey:IQualifiedKey, dataBounds:IBounds2D, screenBounds:IBounds2D, tempShape:Shape):void { // project data coordinates to screen coordinates and draw graphics var beginRadians:Number = _beginRadians.getValueFromKey(recordKey, Number); var spanRadians:Number = _spanRadians.getValueFromKey(recordKey, Number); var graphics:Graphics = tempShape.graphics; // begin line & fill lineStyle.beginLineStyle(recordKey, graphics); fillStyle.beginFillStyle(recordKey, graphics); // move to center point WedgePlotter.drawProjectedWedge(graphics, dataBounds, screenBounds, beginRadians, spanRadians); // end fill graphics.endFill(); } override public function drawBackground(dataBounds:IBounds2D, screenBounds:IBounds2D, destination:BitmapData):void { if (_labelColumn.keys.length == 0) return; var recordKey:IQualifiedKey; var beginRadians:Number; var spanRadians:Number; var midRadians:Number; var xScreenRadius:Number; var yScreenRadius:Number; var coordinate:Point = new Point(); for (var i:int ; i < _filteredData.keys.length ; i++) { if (_labelColumn.containsKey(_filteredData.keys[i] as IQualifiedKey) == false) return; recordKey = _filteredData.keys[i] as IQualifiedKey; beginRadians = _beginRadians.getValueFromKey(recordKey, Number) as Number; spanRadians = _spanRadians.getValueFromKey(recordKey, Number) as Number; midRadians = beginRadians + (spanRadians / 2); coordinate.x = Math.cos(midRadians); coordinate.y = Math.sin(midRadians); dataBounds.projectPointTo(coordinate, screenBounds); coordinate.x += Math.cos(midRadians) * 10; coordinate.y -= Math.sin(midRadians) * 10; var labelText:BitmapText = new BitmapText(); labelText.text = (" " + _labelColumn.getValueFromKey((_filteredData.keys[i] as IQualifiedKey)) + " "); if (midRadians < (Math.PI / 2) || midRadians > ((3 * Math.PI) / 2)) { labelText.horizontalAlign = BitmapText.HORIZONTAL_ALIGN_LEFT; labelText.verticalAlign = BitmapText.VERTICAL_ALIGN_CENTER; } else if (midRadians == ((3 * Math.PI) / 2)) { labelText.horizontalAlign = BitmapText.HORIZONTAL_ALIGN_CENTER; } else if (midRadians == (Math.PI / 2)) { labelText.horizontalAlign = BitmapText.HORIZONTAL_ALIGN_CENTER ; labelText.verticalAlign = BitmapText.VERTICAL_ALIGN_BOTTOM ; } else { labelText.horizontalAlign = BitmapText.HORIZONTAL_ALIGN_RIGHT; labelText.verticalAlign = BitmapText.VERTICAL_ALIGN_CENTER; } labelText.textFormat.color=Weave.properties.axisFontColor.value; labelText.textFormat.size=Weave.properties.axisFontSize.value; labelText.textFormat.underline=Weave.properties.axisFontUnderline.value; labelText.x = coordinate.x; labelText.y = coordinate.y; labelText.draw(destination); } } /** * This gets the data bounds of the bin that a record key falls into. */ override public function getDataBoundsFromRecordKey(recordKey:IQualifiedKey):Array { var beginRadians:Number = _beginRadians.getValueFromKey(recordKey, Number); var spanRadians:Number = _spanRadians.getValueFromKey(recordKey, Number); var bounds:IBounds2D = getReusableBounds(); WedgePlotter.getWedgeBounds(bounds, beginRadians, spanRadians); return [bounds]; } /** * This function returns a Bounds2D object set to the data bounds associated with the background. * @param outputDataBounds A Bounds2D object to store the result in. */ override public function getBackgroundDataBounds():IBounds2D { return getReusableBounds(-1, -1, 1, 1); } } }
/* 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.visualization.plotters { import flash.display.BitmapData; import flash.display.Graphics; import flash.display.Shape; import flash.geom.Point; import mx.controls.Alert; import weave.Weave; import weave.api.data.IAttributeColumn; import weave.api.data.IQualifiedKey; import weave.api.linkSessionState; import weave.api.primitives.IBounds2D; import weave.data.AttributeColumns.DynamicColumn; import weave.data.AttributeColumns.EquationColumn; import weave.data.AttributeColumns.FilteredColumn; import weave.data.AttributeColumns.SortedColumn; import weave.primitives.Bounds2D; import weave.utils.BitmapText; import weave.utils.ColumnUtils; import weave.visualization.plotters.styles.DynamicFillStyle; import weave.visualization.plotters.styles.DynamicLineStyle; import weave.visualization.plotters.styles.SolidFillStyle; import weave.visualization.plotters.styles.SolidLineStyle; /** * PieChartPlotter * * @author adufilie */ public class PieChartPlotter extends AbstractPlotter { public function PieChartPlotter() { init(); } private var _beginRadians:EquationColumn; private var _spanRadians:EquationColumn; private var _filteredData:FilteredColumn; private var _labelColumn:DynamicColumn = new DynamicColumn(); public function get data():DynamicColumn { return _filteredData.internalDynamicColumn; } public function get label():DynamicColumn {return _labelColumn;} public const lineStyle:DynamicLineStyle = new DynamicLineStyle(SolidLineStyle); public const fillStyle:DynamicFillStyle = new DynamicFillStyle(SolidFillStyle); private function init():void { var fill:SolidFillStyle = fillStyle.internalObject as SolidFillStyle; fill.color.internalDynamicColumn.globalName = Weave.DEFAULT_COLOR_COLUMN; _beginRadians = new EquationColumn(); _beginRadians.equation.value = "0.5 * PI + getRunningTotal(spanRadians) - getNumber(spanRadians)"; _spanRadians = _beginRadians.requestVariable("spanRadians", EquationColumn, true); _spanRadians.equation.value = "getNumber(sortedData) / getSum(sortedData) * 2 * PI"; var sortedData:SortedColumn = _spanRadians.requestVariable("sortedData", SortedColumn, true); _filteredData = sortedData.internalDynamicColumn.requestLocalObject(FilteredColumn, true); linkSessionState(keySet.keyFilter, _filteredData.filter); registerSpatialProperties(data); registerNonSpatialProperties(fillStyle, lineStyle, label); setKeySource(_filteredData); } override protected function addRecordGraphicsToTempShape(recordKey:IQualifiedKey, dataBounds:IBounds2D, screenBounds:IBounds2D, tempShape:Shape):void { // project data coordinates to screen coordinates and draw graphics var beginRadians:Number = _beginRadians.getValueFromKey(recordKey, Number); var spanRadians:Number = _spanRadians.getValueFromKey(recordKey, Number); var graphics:Graphics = tempShape.graphics; // begin line & fill lineStyle.beginLineStyle(recordKey, graphics); fillStyle.beginFillStyle(recordKey, graphics); // move to center point WedgePlotter.drawProjectedWedge(graphics, dataBounds, screenBounds, beginRadians, spanRadians); // end fill graphics.endFill(); } override public function drawBackground(dataBounds:IBounds2D, screenBounds:IBounds2D, destination:BitmapData):void { if (_labelColumn.keys.length == 0) return; var recordKey:IQualifiedKey; var beginRadians:Number; var spanRadians:Number; var midRadians:Number; var xScreenRadius:Number; var yScreenRadius:Number; var coordinate:Point = new Point(); for (var i:int ; i < _filteredData.keys.length ; i++) { if (_labelColumn.containsKey(_filteredData.keys[i] as IQualifiedKey) == false) return; recordKey = _filteredData.keys[i] as IQualifiedKey; beginRadians = _beginRadians.getValueFromKey(recordKey, Number) as Number; spanRadians = _spanRadians.getValueFromKey(recordKey, Number) as Number; midRadians = beginRadians + (spanRadians / 2); coordinate.x = Math.cos(midRadians); coordinate.y = Math.sin(midRadians); dataBounds.projectPointTo(coordinate, screenBounds); coordinate.x += Math.cos(midRadians) * 10 * screenBounds.getXDirection(); coordinate.y += Math.sin(midRadians) * 10 * screenBounds.getYDirection(); var labelText:BitmapText = new BitmapText(); labelText.text = (" " + _labelColumn.getValueFromKey((_filteredData.keys[i] as IQualifiedKey)) + " "); if (midRadians < (Math.PI / 2) || midRadians > ((3 * Math.PI) / 2)) { labelText.horizontalAlign = BitmapText.HORIZONTAL_ALIGN_LEFT; labelText.verticalAlign = BitmapText.VERTICAL_ALIGN_CENTER; } else if (midRadians == ((3 * Math.PI) / 2)) { labelText.horizontalAlign = BitmapText.HORIZONTAL_ALIGN_CENTER; } else if (midRadians == (Math.PI / 2)) { labelText.horizontalAlign = BitmapText.HORIZONTAL_ALIGN_CENTER ; labelText.verticalAlign = BitmapText.VERTICAL_ALIGN_BOTTOM ; } else { labelText.horizontalAlign = BitmapText.HORIZONTAL_ALIGN_RIGHT; labelText.verticalAlign = BitmapText.VERTICAL_ALIGN_CENTER; } labelText.textFormat.color=Weave.properties.axisFontColor.value; labelText.textFormat.size=Weave.properties.axisFontSize.value; labelText.textFormat.underline=Weave.properties.axisFontUnderline.value; labelText.x = coordinate.x; labelText.y = coordinate.y; labelText.draw(destination); } } /** * This gets the data bounds of the bin that a record key falls into. */ override public function getDataBoundsFromRecordKey(recordKey:IQualifiedKey):Array { var beginRadians:Number = _beginRadians.getValueFromKey(recordKey, Number); var spanRadians:Number = _spanRadians.getValueFromKey(recordKey, Number); var bounds:IBounds2D = getReusableBounds(); WedgePlotter.getWedgeBounds(bounds, beginRadians, spanRadians); return [bounds]; } /** * This function returns a Bounds2D object set to the data bounds associated with the background. * @param outputDataBounds A Bounds2D object to store the result in. */ override public function getBackgroundDataBounds():IBounds2D { return getReusableBounds(-1, -1, 1, 1); } } }
Modify coordinate for pie chart label
Modify coordinate for pie chart label
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
dfb705934b8244bd6d48e3d428361bd5b72ec0fb
src/goplayer/ConfigurationParser.as
src/goplayer/ConfigurationParser.as
package goplayer { public class ConfigurationParser { public static const DEFAULT_STREAMIO_API_URL : String = "http://staging.streamio.com/api" public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf" public static const DEFAULT_TRACKER_ID : String = "global" public static const VALID_PARAMETERS : Array = [ "streamio:api", "tracker", "skin", "video", "bitrate", "enablertmp", "autoplay", "loop", "skin:showchrome", "skin:showtitle" ] private const result : Configuration = new Configuration private var parameters : Object private var originalParameterNames : Object public function ConfigurationParser (parameters : Object, originalParameterNames : Object) { this.parameters = parameters this.originalParameterNames = originalParameterNames } public function execute() : void { result.apiURL = getString("streamio:api", DEFAULT_STREAMIO_API_URL) result.trackerID = getString("tracker", DEFAULT_TRACKER_ID) result.skinURL = getString("skin", DEFAULT_SKIN_URL) result.movieID = getString("video", null) result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST) result.enableRTMP = getBoolean("enablertmp", true) result.enableAutoplay = getBoolean("autoplay", false) result.enableLooping = getBoolean("loop", false) result.enableChrome = getBoolean("skin:showchrome", true) result.enableTitle = getBoolean("skin:showtitle", true) } public static function parse(parameters : Object) : Configuration { const normalizedParameters : Object = {} const originalParameterNames : Object = {} for (var name : String in parameters) if (VALID_PARAMETERS.indexOf(normalize(name)) == -1) reportUnknownParameter(name) else normalizedParameters[normalize(name)] = parameters[name], originalParameterNames[normalize(name)] = name const parser : ConfigurationParser = new ConfigurationParser (normalizedParameters, originalParameterNames) parser.execute() return parser.result } private static function normalize(name : String) : String { return name.toLowerCase().replace(/[^a-z:]/g, "") } private static function reportUnknownParameter(name : String) : void { debug("Error: Unknown parameter: " + name) } // ----------------------------------------------------- private function getString(name : String, fallback : String) : String { return name in parameters ? parameters[name] : fallback } private function getBoolean (name : String, fallback : Boolean) : Boolean { if (name in parameters) return $getBoolean(name, parameters[name], fallback) else return fallback } private function $getBoolean (name : String, value : String, fallback : Boolean) : Boolean { try { return $$getBoolean(value) } catch (error : Error) { reportInvalidParameter(name, value, ["true", "false"]) return fallback } throw new Error } private function $$getBoolean(value : String) : Boolean { if (value == "true") return true else if (value == "false") return false else throw new Error } // ----------------------------------------------------- private function getBitratePolicy (name : String, fallback : BitratePolicy) : BitratePolicy { if (name in parameters) return $getBitratePolicy(name, parameters[name], fallback) else return fallback } private function $getBitratePolicy (name : String, value : String, fallback : BitratePolicy) : BitratePolicy { try { return $$getBitratePolicy(value) } catch (error : Error) { reportInvalidParameter(name, value, BITRATE_POLICY_VALUES) return fallback } throw new Error } private const BITRATE_POLICY_VALUES : Array = ["<number>kbps", "min", "max", "best"] private function $$getBitratePolicy(value : String) : BitratePolicy { if (value == "max") return BitratePolicy.MAX else if (value == "min") return BitratePolicy.MIN else if (value == "best") return BitratePolicy.BEST else if (Bitrate.parse(value)) return BitratePolicy.specific(Bitrate.parse(value)) else throw new Error } // ----------------------------------------------------- private function reportInvalidParameter (name : String, value : String, validValues : Array) : void { debug("Error: Invalid parameter: " + "“" + originalParameterNames[name] + "=" + value + "”; " + getInvalidParameterHint(validValues) + ".") } private function getInvalidParameterHint(values : Array) : String { return $getInvalidParameterHint(getQuotedValues(values)) } private function $getInvalidParameterHint(values : Array) : String { return "please use " + "either " + values.slice(0, -1).join(", ") + " " + "or " + values[values.length - 1] } private function getQuotedValues(values : Array) : Array { var result : Array = [] for each (var value : String in values) result.push("“" + value + "”") return result } } }
package goplayer { public class ConfigurationParser { public static const DEFAULT_STREAMIO_API_URL : String = "http://staging.streamio.com/api" public static const DEFAULT_SKIN_URL : String = "goplayer-skin.swf" public static const DEFAULT_STREAMIO_TRACKER_ID : String = "global" public static const VALID_PARAMETERS : Array = [ "streamio:api", "streamio:tracker", "skin", "video", "bitrate", "enablertmp", "autoplay", "loop", "skin:showchrome", "skin:showtitle" ] private const result : Configuration = new Configuration private var parameters : Object private var originalParameterNames : Object public function ConfigurationParser (parameters : Object, originalParameterNames : Object) { this.parameters = parameters this.originalParameterNames = originalParameterNames } public function execute() : void { result.apiURL = getString ("streamio:api", DEFAULT_STREAMIO_API_URL) result.trackerID = getString ("streamio:tracker", DEFAULT_STREAMIO_TRACKER_ID) result.skinURL = getString("skin", DEFAULT_SKIN_URL) result.movieID = getString("video", null) result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST) result.enableRTMP = getBoolean("enablertmp", true) result.enableAutoplay = getBoolean("autoplay", false) result.enableLooping = getBoolean("loop", false) result.enableChrome = getBoolean("skin:showchrome", true) result.enableTitle = getBoolean("skin:showtitle", true) } public static function parse(parameters : Object) : Configuration { const normalizedParameters : Object = {} const originalParameterNames : Object = {} for (var name : String in parameters) if (VALID_PARAMETERS.indexOf(normalize(name)) == -1) reportUnknownParameter(name) else normalizedParameters[normalize(name)] = parameters[name], originalParameterNames[normalize(name)] = name const parser : ConfigurationParser = new ConfigurationParser (normalizedParameters, originalParameterNames) parser.execute() return parser.result } private static function normalize(name : String) : String { return name.toLowerCase().replace(/[^a-z:]/g, "") } private static function reportUnknownParameter(name : String) : void { debug("Error: Unknown parameter: " + name) } // ----------------------------------------------------- private function getString(name : String, fallback : String) : String { return name in parameters ? parameters[name] : fallback } private function getBoolean (name : String, fallback : Boolean) : Boolean { if (name in parameters) return $getBoolean(name, parameters[name], fallback) else return fallback } private function $getBoolean (name : String, value : String, fallback : Boolean) : Boolean { try { return $$getBoolean(value) } catch (error : Error) { reportInvalidParameter(name, value, ["true", "false"]) return fallback } throw new Error } private function $$getBoolean(value : String) : Boolean { if (value == "true") return true else if (value == "false") return false else throw new Error } // ----------------------------------------------------- private function getBitratePolicy (name : String, fallback : BitratePolicy) : BitratePolicy { if (name in parameters) return $getBitratePolicy(name, parameters[name], fallback) else return fallback } private function $getBitratePolicy (name : String, value : String, fallback : BitratePolicy) : BitratePolicy { try { return $$getBitratePolicy(value) } catch (error : Error) { reportInvalidParameter(name, value, BITRATE_POLICY_VALUES) return fallback } throw new Error } private const BITRATE_POLICY_VALUES : Array = ["<number>kbps", "min", "max", "best"] private function $$getBitratePolicy(value : String) : BitratePolicy { if (value == "max") return BitratePolicy.MAX else if (value == "min") return BitratePolicy.MIN else if (value == "best") return BitratePolicy.BEST else if (Bitrate.parse(value)) return BitratePolicy.specific(Bitrate.parse(value)) else throw new Error } // ----------------------------------------------------- private function reportInvalidParameter (name : String, value : String, validValues : Array) : void { debug("Error: Invalid parameter: " + "“" + originalParameterNames[name] + "=" + value + "”; " + getInvalidParameterHint(validValues) + ".") } private function getInvalidParameterHint(values : Array) : String { return $getInvalidParameterHint(getQuotedValues(values)) } private function $getInvalidParameterHint(values : Array) : String { return "please use " + "either " + values.slice(0, -1).join(", ") + " " + "or " + values[values.length - 1] } private function getQuotedValues(values : Array) : Array { var result : Array = [] for each (var value : String in values) result.push("“" + value + "”") return result } } }
Rename `tracker' parameter to `streamio:tracker'.
Rename `tracker' parameter to `streamio:tracker'.
ActionScript
mit
dbrock/goplayer,dbrock/goplayer
491657c4a4cf21adb84c64c5d4db5964c01d1d1e
src/org/mangui/hls/HLS.as
src/org/mangui/hls/HLS.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.model.AudioTrack; import flash.display.Stage; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.URLStream; import flash.events.EventDispatcher; import flash.events.Event; import org.mangui.hls.model.Level; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.loader.ManifestLoader; import org.mangui.hls.controller.AudioTrackController; import org.mangui.hls.loader.FragmentLoader; import org.mangui.hls.stream.HLSNetStream; import org.hola.WorkerUtils; import org.hola.HSettings; import flash.external.ExternalInterface; import org.hola.ZExternalInterface; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that manages the streaming process. **/ public class HLS extends EventDispatcher { public var _fragmentLoader : FragmentLoader; private var _manifestLoader : ManifestLoader; private var _audioTrackController : AudioTrackController; /** HLS NetStream **/ private var _hlsNetStream : HLSNetStream; /** HLS URLStream **/ private var _hlsURLStream : Class; private var _client : Object = {}; private var _stage : Stage; private var _url:String; private static var hola_api_inited:Boolean; private static var g_curr_id:Number = 0; private static var g_curr_hls:HLS; private static function hola_version() : Object { return { flashls_version: '0.3.5', patch_version: '1.0.12', have_worker: CONFIG::HAVE_WORKER }; } private static function hola_hls_get_video_url() : String { return g_curr_hls._url; } private static function hola_hls_get_position() : Number { return g_curr_hls.position; } private static function hola_hls_get_duration() : Number { return g_curr_hls.duration; } private static function hola_hls_get_buffer_sec() : Number { return g_curr_hls.bufferLength; } private static function hola_hls_call(method:String, args:Array):Object{ return g_curr_hls[method].apply(g_curr_hls, args); } private static function hola_hls_get_state() : String { return g_curr_hls.playbackState; } private static function hola_hls_get_levels() : Object { return g_curr_hls.levels } private static function hola_hls_get_level() : Number { return g_curr_hls.level } /** Create and connect all components. **/ public function HLS() { HSettings.init(); WorkerUtils.start_worker(); if (!hola_api_inited && ZExternalInterface.avail()) { ExternalInterface.call('console.log', 'HLS hola_api_inited'); hola_api_inited = true; ExternalInterface.addCallback("hola_hls_call", HLS.hola_hls_call); ExternalInterface.addCallback("hola_version", HLS.hola_version); ExternalInterface.addCallback("hola_hls_get_video_url", HLS.hola_hls_get_video_url); ExternalInterface.addCallback("hola_hls_get_position", HLS.hola_hls_get_position); ExternalInterface.addCallback("hola_hls_get_duration", HLS.hola_hls_get_duration); ExternalInterface.addCallback("hola_hls_get_buffer_sec", HLS.hola_hls_get_buffer_sec); ExternalInterface.addCallback("hola_hls_get_state", HLS.hola_hls_get_state); ExternalInterface.addCallback("hola_hls_get_levels", HLS.hola_hls_get_levels); ExternalInterface.addCallback("hola_hls_get_level", HLS.hola_hls_get_level); } g_curr_id++; g_curr_hls = this; if (ZExternalInterface.avail()) { ExternalInterface.call('console.log', 'HLS new ', g_curr_id); ExternalInterface.call('window.postMessage', {id: 'flashls.hlsNew', hls_id: g_curr_id}, '*'); } var connection : NetConnection = new NetConnection(); connection.connect(null); _manifestLoader = new ManifestLoader(this); _audioTrackController = new AudioTrackController(this); _hlsURLStream = URLStream as Class; // default loader _fragmentLoader = new FragmentLoader(this, _audioTrackController); _hlsNetStream = new HLSNetStream(connection, this, _fragmentLoader); add_event(HLSEvent.MANIFEST_LOADING); add_event(HLSEvent.MANIFEST_PARSED); add_event(HLSEvent.MANIFEST_LOADED); add_event(HLSEvent.LEVEL_LOADING); add_event(HLSEvent.LEVEL_LOADED); add_event(HLSEvent.LEVEL_SWITCH); add_event(HLSEvent.LEVEL_ENDLIST); add_event(HLSEvent.FRAGMENT_LOADING); add_event(HLSEvent.FRAGMENT_LOADED); add_event(HLSEvent.FRAGMENT_PLAYING); add_event(HLSEvent.AUDIO_TRACKS_LIST_CHANGE); add_event(HLSEvent.AUDIO_TRACK_CHANGE); add_event(HLSEvent.TAGS_LOADED); add_event(HLSEvent.LAST_VOD_FRAGMENT_LOADED); add_event(HLSEvent.ERROR); add_event(HLSEvent.MEDIA_TIME); add_event(HLSEvent.PLAYBACK_STATE); add_event(HLSEvent.SEEK_STATE); add_event(HLSEvent.PLAYBACK_COMPLETE); add_event(HLSEvent.PLAYLIST_DURATION_UPDATED); add_event(HLSEvent.ID3_UPDATED); }; private function add_event(name:String):void{ this.addEventListener(name, event_handler_func('flashls.'+name)); } private function event_handler_func(name:String):Function{ return function(event:HLSEvent):void{ if (!ZExternalInterface.avail()) return; ExternalInterface.call('window.postMessage', {id: name, hls_id: g_curr_id, url: event.url, level: event.level, duration: event.duration, levels: event.levels, error: event.error, loadMetrics: event.loadMetrics, playMetrics: event.playMetrics, mediatime: event.mediatime, state: event.state, audioTrack: event.audioTrack}, '*'); } } /** Forward internal errors. **/ override public function dispatchEvent(event : Event) : Boolean { if (event.type == HLSEvent.ERROR) { CONFIG::LOGGING { Log.error((event as HLSEvent).error); } _hlsNetStream.close(); } return super.dispatchEvent(event); }; public function dispose() : void { if (ZExternalInterface.avail()) { ExternalInterface.call('window.postMessage', {id: 'flashls.hlsDispose', hls_id: g_curr_id}, '*'); } _fragmentLoader.dispose(); _manifestLoader.dispose(); _audioTrackController.dispose(); _hlsNetStream.dispose_(); _fragmentLoader = null; _manifestLoader = null; _audioTrackController = null; _hlsNetStream = null; _client = null; _stage = null; _hlsNetStream = null; } /** Return the quality level used when starting a fresh playback **/ public function get startlevel() : int { return _manifestLoader.startlevel; }; /** Return the quality level used after a seek operation **/ public function get seeklevel() : int { return _manifestLoader.seeklevel; }; /** Return the quality level of the currently played fragment **/ public function get playbacklevel() : int { return _hlsNetStream.playbackLevel; }; /** Return the quality level of last loaded fragment **/ public function get level() : int { return _fragmentLoader.level; }; /* set quality level for next loaded fragment (-1 for automatic level selection) */ public function set level(level : int) : void { _fragmentLoader.level = level; }; /* check if we are in automatic level selection mode */ public function get autolevel() : Boolean { return _fragmentLoader.autolevel; }; /** Return a Vector of quality level **/ public function get levels() : Vector.<Level> { return _manifestLoader.levels; }; /** Return the current playback position. **/ public function get position() : Number { return _hlsNetStream.position; }; public function get video_url() : String { return _url; }; public function get duration() : Number { return _hlsNetStream.duration; }; /** Return the current playback state. **/ public function get playbackState() : String { return _hlsNetStream.playbackState; }; /** Return the current seek state. **/ public function get seekState() : String { return _hlsNetStream.seekState; }; /** Return the type of stream (VOD/LIVE). **/ public function get type() : String { return _manifestLoader.type; }; /** Load and parse a new HLS URL **/ public function load(url : String) : void { _hlsNetStream.close(); _url = url; _manifestLoader.load(url); }; /** return HLS NetStream **/ public function get stream() : NetStream { return _hlsNetStream; } public function get client() : Object { return _client; } public function set client(value : Object) : void { _client = value; } /** get current Buffer Length **/ public function get bufferLength() : Number { return _hlsNetStream.bufferLength; }; /** get audio tracks list**/ public function get audioTracks() : Vector.<AudioTrack> { return _audioTrackController.audioTracks; }; /** get alternate audio tracks list from playlist **/ public function get altAudioTracks() : Vector.<AltAudioTrack> { return _manifestLoader.altAudioTracks; }; /** get index of the selected audio track (index in audio track lists) **/ public function get audioTrack() : int { return _audioTrackController.audioTrack; }; /** select an audio track, based on its index in audio track lists**/ public function set audioTrack(val : int) : void { _audioTrackController.audioTrack = val; } /* set stage */ public function set stage(stage : Stage) : void { _stage = stage; } /* get stage */ public function get stage() : Stage { return _stage; } /* set URL stream loader */ public function set URLstream(urlstream : Class) : void { _hlsURLStream = urlstream; } /* retrieve URL stream loader */ public function get URLstream() : Class { return _hlsURLStream; } }; }
/* 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.model.AudioTrack; import flash.display.Stage; import flash.net.NetConnection; import flash.net.NetStream; import flash.net.URLStream; import flash.events.EventDispatcher; import flash.events.Event; import org.mangui.hls.model.Level; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.loader.ManifestLoader; import org.mangui.hls.controller.AudioTrackController; import org.mangui.hls.loader.FragmentLoader; import org.mangui.hls.stream.HLSNetStream; import org.hola.WorkerUtils; import org.hola.HSettings; import org.hola.FlashFetchBin; import flash.external.ExternalInterface; import org.hola.ZExternalInterface; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that manages the streaming process. **/ public class HLS extends EventDispatcher { public var _fragmentLoader : FragmentLoader; private var _manifestLoader : ManifestLoader; private var _audioTrackController : AudioTrackController; /** HLS NetStream **/ private var _hlsNetStream : HLSNetStream; /** HLS URLStream **/ private var _hlsURLStream : Class; private var _client : Object = {}; private var _stage : Stage; private var _url:String; private static var hola_api_inited:Boolean; private static var g_curr_id:Number = 0; private static var g_curr_hls:HLS; private static function hola_version() : Object { return { flashls_version: '0.3.5', patch_version: '1.0.12', have_worker: CONFIG::HAVE_WORKER }; } private static function hola_hls_get_video_url() : String { return g_curr_hls._url; } private static function hola_hls_get_position() : Number { return g_curr_hls.position; } private static function hola_hls_get_duration() : Number { return g_curr_hls.duration; } private static function hola_hls_get_buffer_sec() : Number { return g_curr_hls.bufferLength; } private static function hola_hls_call(method:String, args:Array):Object{ return g_curr_hls[method].apply(g_curr_hls, args); } private static function hola_hls_get_state() : String { return g_curr_hls.playbackState; } private static function hola_hls_get_levels() : Object { return g_curr_hls.levels } private static function hola_hls_get_level() : Number { return g_curr_hls.level } /** Create and connect all components. **/ public function HLS() { HSettings.init(); WorkerUtils.start_worker(); if (!hola_api_inited && ZExternalInterface.avail()) { ExternalInterface.call('console.log', 'HLS hola_api_inited'); hola_api_inited = true; ExternalInterface.addCallback("hola_hls_call", HLS.hola_hls_call); ExternalInterface.addCallback("hola_version", HLS.hola_version); ExternalInterface.addCallback("hola_hls_get_video_url", HLS.hola_hls_get_video_url); ExternalInterface.addCallback("hola_hls_get_position", HLS.hola_hls_get_position); ExternalInterface.addCallback("hola_hls_get_duration", HLS.hola_hls_get_duration); ExternalInterface.addCallback("hola_hls_get_buffer_sec", HLS.hola_hls_get_buffer_sec); ExternalInterface.addCallback("hola_hls_get_state", HLS.hola_hls_get_state); ExternalInterface.addCallback("hola_hls_get_levels", HLS.hola_hls_get_levels); ExternalInterface.addCallback("hola_hls_get_level", HLS.hola_hls_get_level); FlashFetchBin.init(); } g_curr_id++; g_curr_hls = this; if (ZExternalInterface.avail()) { ExternalInterface.call('console.log', 'HLS new ', g_curr_id); ExternalInterface.call('window.postMessage', {id: 'flashls.hlsNew', hls_id: g_curr_id}, '*'); } var connection : NetConnection = new NetConnection(); connection.connect(null); _manifestLoader = new ManifestLoader(this); _audioTrackController = new AudioTrackController(this); _hlsURLStream = URLStream as Class; // default loader _fragmentLoader = new FragmentLoader(this, _audioTrackController); _hlsNetStream = new HLSNetStream(connection, this, _fragmentLoader); add_event(HLSEvent.MANIFEST_LOADING); add_event(HLSEvent.MANIFEST_PARSED); add_event(HLSEvent.MANIFEST_LOADED); add_event(HLSEvent.LEVEL_LOADING); add_event(HLSEvent.LEVEL_LOADED); add_event(HLSEvent.LEVEL_SWITCH); add_event(HLSEvent.LEVEL_ENDLIST); add_event(HLSEvent.FRAGMENT_LOADING); add_event(HLSEvent.FRAGMENT_LOADED); add_event(HLSEvent.FRAGMENT_PLAYING); add_event(HLSEvent.AUDIO_TRACKS_LIST_CHANGE); add_event(HLSEvent.AUDIO_TRACK_CHANGE); add_event(HLSEvent.TAGS_LOADED); add_event(HLSEvent.LAST_VOD_FRAGMENT_LOADED); add_event(HLSEvent.ERROR); add_event(HLSEvent.MEDIA_TIME); add_event(HLSEvent.PLAYBACK_STATE); add_event(HLSEvent.SEEK_STATE); add_event(HLSEvent.PLAYBACK_COMPLETE); add_event(HLSEvent.PLAYLIST_DURATION_UPDATED); add_event(HLSEvent.ID3_UPDATED); }; private function add_event(name:String):void{ this.addEventListener(name, event_handler_func('flashls.'+name)); } private function event_handler_func(name:String):Function{ return function(event:HLSEvent):void{ if (!ZExternalInterface.avail()) return; ExternalInterface.call('window.postMessage', {id: name, hls_id: g_curr_id, url: event.url, level: event.level, duration: event.duration, levels: event.levels, error: event.error, loadMetrics: event.loadMetrics, playMetrics: event.playMetrics, mediatime: event.mediatime, state: event.state, audioTrack: event.audioTrack}, '*'); } } /** Forward internal errors. **/ override public function dispatchEvent(event : Event) : Boolean { if (event.type == HLSEvent.ERROR) { CONFIG::LOGGING { Log.error((event as HLSEvent).error); } _hlsNetStream.close(); } return super.dispatchEvent(event); }; public function dispose() : void { if (ZExternalInterface.avail()) { ExternalInterface.call('window.postMessage', {id: 'flashls.hlsDispose', hls_id: g_curr_id}, '*'); } _fragmentLoader.dispose(); _manifestLoader.dispose(); _audioTrackController.dispose(); _hlsNetStream.dispose_(); _fragmentLoader = null; _manifestLoader = null; _audioTrackController = null; _hlsNetStream = null; _client = null; _stage = null; _hlsNetStream = null; } /** Return the quality level used when starting a fresh playback **/ public function get startlevel() : int { return _manifestLoader.startlevel; }; /** Return the quality level used after a seek operation **/ public function get seeklevel() : int { return _manifestLoader.seeklevel; }; /** Return the quality level of the currently played fragment **/ public function get playbacklevel() : int { return _hlsNetStream.playbackLevel; }; /** Return the quality level of last loaded fragment **/ public function get level() : int { return _fragmentLoader.level; }; /* set quality level for next loaded fragment (-1 for automatic level selection) */ public function set level(level : int) : void { _fragmentLoader.level = level; }; /* check if we are in automatic level selection mode */ public function get autolevel() : Boolean { return _fragmentLoader.autolevel; }; /** Return a Vector of quality level **/ public function get levels() : Vector.<Level> { return _manifestLoader.levels; }; /** Return the current playback position. **/ public function get position() : Number { return _hlsNetStream.position; }; public function get video_url() : String { return _url; }; public function get duration() : Number { return _hlsNetStream.duration; }; /** Return the current playback state. **/ public function get playbackState() : String { return _hlsNetStream.playbackState; }; /** Return the current seek state. **/ public function get seekState() : String { return _hlsNetStream.seekState; }; /** Return the type of stream (VOD/LIVE). **/ public function get type() : String { return _manifestLoader.type; }; /** Load and parse a new HLS URL **/ public function load(url : String) : void { _hlsNetStream.close(); _url = url; _manifestLoader.load(url); }; /** return HLS NetStream **/ public function get stream() : NetStream { return _hlsNetStream; } public function get client() : Object { return _client; } public function set client(value : Object) : void { _client = value; } /** get current Buffer Length **/ public function get bufferLength() : Number { return _hlsNetStream.bufferLength; }; /** get audio tracks list**/ public function get audioTracks() : Vector.<AudioTrack> { return _audioTrackController.audioTracks; }; /** get alternate audio tracks list from playlist **/ public function get altAudioTracks() : Vector.<AltAudioTrack> { return _manifestLoader.altAudioTracks; }; /** get index of the selected audio track (index in audio track lists) **/ public function get audioTrack() : int { return _audioTrackController.audioTrack; }; /** select an audio track, based on its index in audio track lists**/ public function set audioTrack(val : int) : void { _audioTrackController.audioTrack = val; } /* set stage */ public function set stage(stage : Stage) : void { _stage = stage; } /* get stage */ public function get stage() : Stage { return _stage; } /* set URL stream loader */ public function set URLstream(urlstream : Class) : void { _hlsURLStream = urlstream; } /* retrieve URL stream loader */ public function get URLstream() : Class { return _hlsURLStream; } }; }
fix calling FlashFetchBin.init
fix calling FlashFetchBin.init
ActionScript
mpl-2.0
hola/flashls,hola/flashls
052417dfb804495d28d1d802c875c337e37d8ddf
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.PropertyUtil; 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 function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } 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 ); } } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { failIfTypeIsNotCloneable(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:*, deep:int, type:Type = null):* { if(!type) { type = Type.forInstance(source); } const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); const clonedInstance:* = new (type.clazz)(); for each(var field:Field in fieldsToClone) { PropertyUtil.cloneProperty(source, clonedInstance, field.name); } return clonedInstance; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); failIfTypeIsNotCloneable(type); const deep:int = 2; return doClone(source, deep, type); } } }
package dolly { import dolly.core.dolly_internal; import dolly.core.errors.CloningError; import dolly.core.metadata.MetadataName; import dolly.utils.PropertyUtil; 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 function isTypeCloneable(type:Type):Boolean { return type.hasMetadata(MetadataName.CLONEABLE); } 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 ); } } dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> { failIfTypeIsNotCloneable(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:*, deep:int, clonedObjectsMap:Dictionary = null, type:Type = null):* { if (!clonedObjectsMap) { clonedObjectsMap = new Dictionary(); } if (!type) { type = Type.forInstance(source); } const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type); const clonedInstance:* = new (type.clazz)(); for each(var field:Field in fieldsToClone) { PropertyUtil.cloneProperty(source, clonedInstance, field.name); } return clonedInstance; } public static function clone(source:*):* { const type:Type = Type.forInstance(source); failIfTypeIsNotCloneable(type); const deep:int = 2; return doClone(source, deep, null, type); } } }
Add parameter "clonedObjects" in Cloner.doClone() method.
Add parameter "clonedObjects" in Cloner.doClone() method.
ActionScript
mit
Yarovoy/dolly
bea9ed4b95ccde037256e8a940ac2495a9deb6cc
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.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 isAccessorCopyable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean { return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() && (skipMetadataChecking || accessor.hasMetadata(MetadataName.COPYABLE)); } dolly_internal static function findCopyableFieldsForType(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 (isAccessorCopyable(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 (!variable.isStatic && variable.hasMetadata(MetadataName.COPYABLE)) { result.push(variable); } } else if (metadataContainer is Accessor) { accessor = metadataContainer as Accessor; if (isAccessorCopyable(accessor, false)) { result.push(accessor); } } } } 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 { dolly_internal static function findCopyableFieldsForType(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; } 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; } } }
Remove private static method Copier.isAccessorCopyable().
Remove private static method Copier.isAccessorCopyable().
ActionScript
mit
Yarovoy/dolly
1dee769a29648581b6f278230dd00ed653f89a9a
src/aerys/minko/scene/node/Scene.as
src/aerys/minko/scene/node/Scene.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.Effect; import aerys.minko.render.Viewport; import aerys.minko.scene.controller.scene.RenderingController; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.loader.AssetsLibrary; import flash.display.BitmapData; import flash.utils.Dictionary; import flash.utils.getTimer; /** * Scene objects are the root of any 3D scene. * * @author Jean-Marc Le Roux * */ public final class Scene extends Group { use namespace minko_scene; minko_scene var _camera : AbstractCamera; private var _renderingCtrl : RenderingController; private var _properties : DataProvider; private var _bindings : DataBindings; private var _numTriangles : uint; private var _enterFrame : Signal; private var _renderingBegin : Signal; private var _renderingEnd : Signal; private var _exitFrame : Signal; private var _assets : AssetsLibrary; public function get assets():AssetsLibrary { return _assets; } public function get activeCamera() : AbstractCamera { return _camera; } public function get numPasses() : uint { return _renderingCtrl.numPasses; } public function get numEnabledPasses() : uint { return _renderingCtrl.numEnabledPasses; } public function get numTriangles() : uint { return _numTriangles; } public function get postProcessingEffect() : Effect { return _renderingCtrl.postProcessingEffect; } public function set postProcessingEffect(value : Effect) : void { _renderingCtrl.postProcessingEffect = value; } public function get postProcessingProperties() : DataProvider { return _renderingCtrl.postProcessingProperties; } public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get bindings() : DataBindings { return _bindings; } /** * The signal executed when the viewport is about to start rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who starts rendering the frame</li> * </ul> * @return * */ public function get enterFrame() : Signal { return _enterFrame; } /** * The signal executed when the viewport is done rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who just finished rendering the frame</li> * </ul> * @return * */ public function get exitFrame() : Signal { return _exitFrame; } public function get renderingBegin() : Signal { return _renderingBegin; } public function get renderingEnd() : Signal { return _renderingEnd; } public function Scene(...children) { super(children); } override protected function initialize() : void { _bindings = new DataBindings(this); _assets = new AssetsLibrary(); this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE); super.initialize(); } override protected function initializeSignals() : void { super.initializeSignals(); _enterFrame = new Signal('Scene.enterFrame'); _renderingBegin = new Signal('Scene.renderingBegin'); _renderingEnd = new Signal('Scene.renderingEnd'); _exitFrame = new Signal('Scene.exitFrame'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); added.add(addedHandler); } override protected function initializeContollers() : void { _renderingCtrl = new RenderingController(); addController(_renderingCtrl); super.initializeContollers(); } public function render(viewport : Viewport, destination : BitmapData = null) : void { _enterFrame.execute(this, viewport, destination, getTimer()); if (viewport.ready && viewport.visible) { _renderingBegin.execute(this, viewport, destination, getTimer()); _numTriangles = _renderingCtrl.render(viewport, destination); _renderingEnd.execute(this, viewport, destination, getTimer()); } _exitFrame.execute(this, viewport, destination, getTimer()); } private function addedHandler(child : ISceneNode, parent : Group) : void { throw new Error(); } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.render.Effect; import aerys.minko.render.Viewport; import aerys.minko.scene.controller.scene.RenderingController; import aerys.minko.scene.node.camera.AbstractCamera; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.DataProvider; import aerys.minko.type.enum.DataProviderUsage; import aerys.minko.type.loader.AssetsLibrary; import flash.display.BitmapData; import flash.utils.Dictionary; import flash.utils.getTimer; /** * Scene objects are the root of any 3D scene. * * @author Jean-Marc Le Roux * */ public final class Scene extends Group { use namespace minko_scene; minko_scene var _camera : AbstractCamera; private var _renderingCtrl : RenderingController; private var _properties : DataProvider; private var _bindings : DataBindings; private var _numTriangles : uint; private var _enterFrame : Signal; private var _renderingBegin : Signal; private var _renderingEnd : Signal; private var _exitFrame : Signal; private var _assets : AssetsLibrary; public function get assets() : AssetsLibrary { return _assets; } public function get activeCamera() : AbstractCamera { return _camera; } public function get numPasses() : uint { return _renderingCtrl.numPasses; } public function get numEnabledPasses() : uint { return _renderingCtrl.numEnabledPasses; } public function get numTriangles() : uint { return _numTriangles; } public function get postProcessingEffect() : Effect { return _renderingCtrl.postProcessingEffect; } public function set postProcessingEffect(value : Effect) : void { _renderingCtrl.postProcessingEffect = value; } public function get postProcessingProperties() : DataProvider { return _renderingCtrl.postProcessingProperties; } public function get properties() : DataProvider { return _properties; } public function set properties(value : DataProvider) : void { if (_properties != value) { if (_properties) _bindings.removeProvider(_properties); _properties = value; if (value) _bindings.addProvider(value); } } public function get bindings() : DataBindings { return _bindings; } /** * The signal executed when the viewport is about to start rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who starts rendering the frame</li> * </ul> * @return * */ public function get enterFrame() : Signal { return _enterFrame; } /** * The signal executed when the viewport is done rendering a frame. * Callback functions for this signal should accept the following arguments: * <ul> * <li>viewport : Viewport, the viewport who just finished rendering the frame</li> * </ul> * @return * */ public function get exitFrame() : Signal { return _exitFrame; } public function get renderingBegin() : Signal { return _renderingBegin; } public function get renderingEnd() : Signal { return _renderingEnd; } public function Scene(...children) { super(children); } override protected function initialize() : void { _bindings = new DataBindings(this); _assets = new AssetsLibrary(); this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE); super.initialize(); } override protected function initializeSignals() : void { super.initializeSignals(); _enterFrame = new Signal('Scene.enterFrame'); _renderingBegin = new Signal('Scene.renderingBegin'); _renderingEnd = new Signal('Scene.renderingEnd'); _exitFrame = new Signal('Scene.exitFrame'); } override protected function initializeSignalHandlers() : void { super.initializeSignalHandlers(); added.add(addedHandler); } override protected function initializeContollers() : void { _renderingCtrl = new RenderingController(); addController(_renderingCtrl); super.initializeContollers(); } public function render(viewport : Viewport, destination : BitmapData = null) : void { _enterFrame.execute(this, viewport, destination, getTimer()); if (viewport.ready && viewport.visible) { _renderingBegin.execute(this, viewport, destination, getTimer()); _numTriangles = _renderingCtrl.render(viewport, destination); _renderingEnd.execute(this, viewport, destination, getTimer()); } _exitFrame.execute(this, viewport, destination, getTimer()); } private function addedHandler(child : ISceneNode, parent : Group) : void { throw new Error(); } } }
fix coding style
fix coding style
ActionScript
mit
aerys/minko-as3
d2ae9782beeea874be4ce92ee7edbd126b79f198
src/aerys/minko/render/shader/part/phong/attenuation/MatrixShadowMapAttenuationShaderPart.as
src/aerys/minko/render/shader/part/phong/attenuation/MatrixShadowMapAttenuationShaderPart.as
package aerys.minko.render.shader.part.phong.attenuation { import aerys.minko.render.material.phong.PhongProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.part.phong.LightAwareShaderPart; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerMipMapping; import aerys.minko.type.enum.SamplerWrapping; import aerys.minko.type.enum.ShadowMappingQuality; /** * Fixme, bias should be:Total bias is m*SLOPESCALE + DEPTHBIAS * Where m = max( | ∂z/∂x | , | ∂z/∂y | ) * ftp://download.nvidia.com/developer/presentations/2004/GPU_Jackpot/Shadow_Mapping.pdf * * @author Romain Gilliotte */ public class MatrixShadowMapAttenuationShaderPart extends LightAwareShaderPart implements IAttenuationShaderPart { public function MatrixShadowMapAttenuationShaderPart(main : Shader) { super(main); } public function getAttenuation(lightId : uint) : SFloat { var lightType : uint = getLightConstant(lightId, 'type'); var screenPos : SFloat = interpolate(localToScreen(fsLocalPosition)); // retrieve shadow bias var shadowBias : SFloat; if (meshBindings.propertyExists(PhongProperties.SHADOW_BIAS)) shadowBias = meshBindings.getParameter(PhongProperties.SHADOW_BIAS, 1); else shadowBias = getLightParameter(lightId, PhongProperties.SHADOW_BIAS, 1); // retrieve depthmap and projection matrix var worldToUV : SFloat = getLightParameter(lightId, 'worldToUV', 16); var depthMap : SFloat = getLightTextureParameter( lightId, 'shadowMap', SamplerFiltering.LINEAR, SamplerMipMapping.DISABLE, SamplerWrapping.CLAMP ); // read expected depth from shadow map, and compute current depth var uv : SFloat; uv = multiply4x4(vsWorldPosition, worldToUV); uv = interpolate(uv); var currentDepth : SFloat = uv.z; currentDepth = min(subtract(1, shadowBias), currentDepth); uv = divide(uv, uv.w); var outsideMap : SFloat = notEqual( 0, dotProduct4(notEqual(uv, saturate(uv)), notEqual(uv, saturate(uv))) ); var precomputedDepth : SFloat = unpack(sampleTexture(depthMap, uv.xyyy)); var curDepthSubBias : SFloat = subtract(currentDepth, shadowBias); var noShadows : SFloat = lessEqual(curDepthSubBias, precomputedDepth); var quality : uint = getLightConstant(lightId, 'shadowQuality'); if (quality != ShadowMappingQuality.HARD) { var invertSize : SFloat = divide( getLightParameter(lightId, 'shadowSpread', 1), getLightParameter(lightId, 'shadowMapSize', 1) ); var uvs : Vector.<SFloat> = new <SFloat>[]; var uvDelta : SFloat; if (quality > ShadowMappingQuality.LOW) { uvDelta = multiply(float3(-1, 0, 1), invertSize); uvs.push( add(uv.xyxy, uvDelta.xxxy), // (-1, -1), (-1, 0) add(uv.xyxy, uvDelta.xzyx), // (-1, 1), ( 0, -1) add(uv.xyxy, uvDelta.yzzx), // ( 0, 1), ( 1, -1) add(uv.xyxy, uvDelta.zyzz) // ( 1, 0), ( 1, 1) ); } if (quality > ShadowMappingQuality.MEDIUM) { uvDelta = multiply(float3(-2, 0, 2), invertSize); uvs.push( add(uv.xyxy, uvDelta.xyyx), // (-2, 0), (0, -2) add(uv.xyxy, uvDelta.yzzy) // ( 0, 2), (2, 0) ); } if (quality > ShadowMappingQuality.HARD) { uvDelta = multiply(float4(-2, -1, 1, 2), invertSize); uvs.push( add(uv.xyxy, uvDelta.xzyw), // (-2, 1), (-1, 2) add(uv.xyxy, uvDelta.zwwz), // ( 1, 2), ( 2, 1) add(uv.xyxy, uvDelta.wyzx), // ( 2, -1), ( 1, -2) add(uv.xyxy, uvDelta.xyyx) // (-2, -1), (-1, -2) ); } var numSamples : uint = uvs.length; for (var sampleId : uint = 0; sampleId < numSamples; sampleId += 2) { precomputedDepth = float4( unpack(sampleTexture(depthMap, uvs[sampleId].xy)), unpack(sampleTexture(depthMap, uvs[sampleId].zw)), unpack(sampleTexture(depthMap, uvs[sampleId + 1].xy)), unpack(sampleTexture(depthMap, uvs[sampleId + 1].zw)) ); var localNoShadows : SFloat = lessEqual(curDepthSubBias, precomputedDepth); noShadows.incrementBy(dotProduct4(localNoShadows, float4(1, 1, 1, 1))); } noShadows.scaleBy(1 / (2 * numSamples + 1)); } return noShadows; } } }
package aerys.minko.render.shader.part.phong.attenuation { import aerys.minko.render.material.phong.PhongProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.part.phong.LightAwareShaderPart; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerMipMapping; import aerys.minko.type.enum.SamplerWrapping; import aerys.minko.type.enum.ShadowMappingQuality; /** * Fixme, bias should be:Total bias is m*SLOPESCALE + DEPTHBIAS * Where m = max( | ∂z/∂x | , | ∂z/∂y | ) * ftp://download.nvidia.com/developer/presentations/2004/GPU_Jackpot/Shadow_Mapping.pdf * * @author Romain Gilliotte */ public class MatrixShadowMapAttenuationShaderPart extends LightAwareShaderPart implements IAttenuationShaderPart { public function MatrixShadowMapAttenuationShaderPart(main : Shader) { super(main); } public function getAttenuation(lightId : uint) : SFloat { var lightType : uint = getLightConstant(lightId, 'type'); var screenPos : SFloat = interpolate(localToScreen(fsLocalPosition)); // retrieve shadow bias var shadowBias : SFloat; if (meshBindings.propertyExists(PhongProperties.SHADOW_BIAS)) shadowBias = meshBindings.getParameter(PhongProperties.SHADOW_BIAS, 1); else shadowBias = getLightParameter(lightId, PhongProperties.SHADOW_BIAS, 1); // retrieve depthmap and projection matrix var worldToUV : SFloat = getLightParameter(lightId, 'worldToUV', 16); var depthMap : SFloat = getLightTextureParameter( lightId, 'shadowMap', SamplerFiltering.NEAREST, SamplerMipMapping.DISABLE, SamplerWrapping.CLAMP ); // read expected depth from shadow map, and compute current depth var uv : SFloat; uv = multiply4x4(vsWorldPosition, worldToUV); uv = interpolate(uv); var currentDepth : SFloat = uv.z; currentDepth = min(subtract(1, shadowBias), currentDepth); uv = divide(uv, uv.w); var outsideMap : SFloat = notEqual( 0, dotProduct4(notEqual(uv, saturate(uv)), notEqual(uv, saturate(uv))) ); var precomputedDepth : SFloat = unpack(sampleTexture(depthMap, uv.xyyy)); var curDepthSubBias : SFloat = subtract(currentDepth, shadowBias); var noShadows : SFloat = lessEqual(curDepthSubBias, precomputedDepth); var quality : uint = getLightConstant(lightId, 'shadowQuality'); if (quality != ShadowMappingQuality.HARD) { var invertSize : SFloat = divide( getLightParameter(lightId, 'shadowSpread', 1), getLightParameter(lightId, 'shadowMapSize', 1) ); var uvs : Vector.<SFloat> = new <SFloat>[]; var uvDelta : SFloat; if (quality > ShadowMappingQuality.LOW) { uvDelta = multiply(float3(-1, 0, 1), invertSize); uvs.push( add(uv.xyxy, uvDelta.xxxy), // (-1, -1), (-1, 0) add(uv.xyxy, uvDelta.xzyx), // (-1, 1), ( 0, -1) add(uv.xyxy, uvDelta.yzzx), // ( 0, 1), ( 1, -1) add(uv.xyxy, uvDelta.zyzz) // ( 1, 0), ( 1, 1) ); } if (quality > ShadowMappingQuality.MEDIUM) { uvDelta = multiply(float3(-2, 0, 2), invertSize); uvs.push( add(uv.xyxy, uvDelta.xyyx), // (-2, 0), (0, -2) add(uv.xyxy, uvDelta.yzzy) // ( 0, 2), (2, 0) ); } if (quality > ShadowMappingQuality.HARD) { uvDelta = multiply(float4(-2, -1, 1, 2), invertSize); uvs.push( add(uv.xyxy, uvDelta.xzyw), // (-2, 1), (-1, 2) add(uv.xyxy, uvDelta.zwwz), // ( 1, 2), ( 2, 1) add(uv.xyxy, uvDelta.wyzx), // ( 2, -1), ( 1, -2) add(uv.xyxy, uvDelta.xyyx) // (-2, -1), (-1, -2) ); } var numSamples : uint = uvs.length; for (var sampleId : uint = 0; sampleId < numSamples; sampleId += 2) { precomputedDepth = float4( unpack(sampleTexture(depthMap, uvs[sampleId].xy)), unpack(sampleTexture(depthMap, uvs[sampleId].zw)), unpack(sampleTexture(depthMap, uvs[sampleId + 1].xy)), unpack(sampleTexture(depthMap, uvs[sampleId + 1].zw)) ); var localNoShadows : SFloat = lessEqual(curDepthSubBias, precomputedDepth); noShadows.incrementBy(dotProduct4(localNoShadows, float4(1, 1, 1, 1))); } noShadows.scaleBy(1 / (2 * numSamples + 1)); } return noShadows; } } }
use SamplerFiltering.NEAREST for shadow map sampling
use SamplerFiltering.NEAREST for shadow map sampling
ActionScript
mit
aerys/minko-as3
daeabbe99cf3dacfa29a823254cb609010ab5996
src/com/esri/builder/model/PortalModel.as
src/com/esri/builder/model/PortalModel.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.model { import com.esri.ags.portal.Portal; import com.esri.builder.supportClasses.URLUtil; import flash.events.Event; import flash.events.EventDispatcher; import mx.utils.StringUtil; public class PortalModel extends EventDispatcher { //-------------------------------------------------------------------------- // // Constants // //-------------------------------------------------------------------------- public static const DEFAULT_PORTAL_URL:String = "https://www.arcgis.com"; private static var instance:PortalModel; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- public static function getInstance():PortalModel { if (!instance) { instance = new PortalModel(new SingletonEnforcer()); } return instance; } public function cleanUpPortalURL(url:String):String { var cleanURL:String = url; cleanURL = StringUtil.trim(cleanURL); cleanURL = replacePreviousDefaultPortalURL(cleanURL); cleanURL = cleanURL.replace(/\/sharing\/content\/items\/?$/i, ''); cleanURL = cleanURL.charAt(cleanURL.length - 1) == "/" ? cleanURL : cleanURL + "/"; cleanURL = URLUtil.encode(cleanURL); return cleanURL; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- public function PortalModel(singletonEnforcer:SingletonEnforcer) { if (!singletonEnforcer) { throw new Error("Class should not be instantiated - use getInstance()"); } } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // portal //---------------------------------- [Bindable] public var portal:Portal = new Portal(); //---------------------------------- // portalURL //---------------------------------- /** * Stripped value of the _userDefinedPortalURL * (without "/sharing/content/items") */ private var _portalURL:String; [Bindable("userDefinedPortalURLChanged")] public function get portalURL():String { return _portalURL; } public function set portalURL(value:String):void { if (_userDefinedPortalURL != value) { _userDefinedPortalURL = cleanUpPortalURL(value); _portalURL = _userDefinedPortalURL; dispatchEvent(new Event("userDefinedPortalURLChanged")); } } private function replacePreviousDefaultPortalURL(url:String):String { const previousDefaultPortalURL:String = "http://www.arcgis.com/"; return url.replace(previousDefaultPortalURL, DEFAULT_PORTAL_URL); } //---------------------------------- // userDefinedPortalURL //---------------------------------- /** * The ArcGIS Portal URL set by the user */ private var _userDefinedPortalURL:String; [Bindable(event="userDefinedPortalURLChanged")] public function get userDefinedPortalURL():String { return _userDefinedPortalURL; } } } class SingletonEnforcer { }
//////////////////////////////////////////////////////////////////////////////// // 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.model { import com.esri.ags.portal.Portal; import com.esri.builder.supportClasses.URLUtil; import flash.events.Event; import flash.events.EventDispatcher; import mx.utils.StringUtil; public class PortalModel extends EventDispatcher { //-------------------------------------------------------------------------- // // Constants // //-------------------------------------------------------------------------- public static const DEFAULT_PORTAL_URL:String = "https://www.arcgis.com/"; private static var instance:PortalModel; //-------------------------------------------------------------------------- // // Class methods // //-------------------------------------------------------------------------- public static function getInstance():PortalModel { if (!instance) { instance = new PortalModel(new SingletonEnforcer()); } return instance; } public function cleanUpPortalURL(url:String):String { var cleanURL:String = url; cleanURL = StringUtil.trim(cleanURL); cleanURL = replacePreviousDefaultPortalURL(cleanURL); cleanURL = cleanURL.replace(/\/sharing\/content\/items\/?$/i, ''); cleanURL = cleanURL.charAt(cleanURL.length - 1) == "/" ? cleanURL : cleanURL + "/"; cleanURL = URLUtil.encode(cleanURL); return cleanURL; } //-------------------------------------------------------------------------- // // Constructor // //-------------------------------------------------------------------------- public function PortalModel(singletonEnforcer:SingletonEnforcer) { if (!singletonEnforcer) { throw new Error("Class should not be instantiated - use getInstance()"); } } //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- //---------------------------------- // portal //---------------------------------- [Bindable] public var portal:Portal = new Portal(); //---------------------------------- // portalURL //---------------------------------- /** * Stripped value of the _userDefinedPortalURL * (without "/sharing/content/items") */ private var _portalURL:String; [Bindable("userDefinedPortalURLChanged")] public function get portalURL():String { return _portalURL; } public function set portalURL(value:String):void { if (_userDefinedPortalURL != value) { _userDefinedPortalURL = cleanUpPortalURL(value); _portalURL = _userDefinedPortalURL; dispatchEvent(new Event("userDefinedPortalURLChanged")); } } private function replacePreviousDefaultPortalURL(url:String):String { const previousDefaultPortalURL:String = "http://www.arcgis.com/"; return url.replace(previousDefaultPortalURL, DEFAULT_PORTAL_URL); } //---------------------------------- // userDefinedPortalURL //---------------------------------- /** * The ArcGIS Portal URL set by the user */ private var _userDefinedPortalURL:String; [Bindable(event="userDefinedPortalURLChanged")] public function get userDefinedPortalURL():String { return _userDefinedPortalURL; } } } class SingletonEnforcer { }
Update default Portal URL with trailing forward slash.
Update default Portal URL with trailing forward slash.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
7499c3ace4a48e0a2400061ff4d92d257a81135f
actionscript/src/com/freshplanet/ane/AirInAppPurchase/InAppPurchase.as
actionscript/src/com/freshplanet/ane/AirInAppPurchase/InAppPurchase.as
////////////////////////////////////////////////////////////////////////////////////// // // Copyright 2012 Freshplanet (http://freshplanet.com | [email protected]) // // 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.freshplanet.ane.AirInAppPurchase { import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class InAppPurchase extends EventDispatcher { private static var _instance:InAppPurchase; private var extCtx:*; public function InAppPurchase() { if (!_instance) { if (this.isInAppPurchaseSupported) { extCtx = ExtensionContext.createExtensionContext("com.freshplanet.AirInAppPurchase", null); if (extCtx != null) { extCtx.addEventListener(StatusEvent.STATUS, onStatus); } else { trace('[InAppPurchase] extCtx is null.'); } } _instance = this; } else { throw Error( 'This is a singleton, use getInstance, do not call the constructor directly'); } } public static function getInstance():InAppPurchase { return _instance != null ? _instance : new InAppPurchase(); } public function init(googlePlayKey:String, debug:Boolean = false):void { if (this.isInAppPurchaseSupported) { trace("[InAppPurchase] init library"); extCtx.call("initLib", googlePlayKey, debug); } } public function makePurchase(productId:String ):void { if (this.isInAppPurchaseSupported) { trace("[InAppPurchase] purchasing", productId); extCtx.call("makePurchase", productId); } else { this.dispatchEvent(new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported")); } } // receipt is for android device. public function removePurchaseFromQueue(productId:String, receipt:String):void { if (this.isInAppPurchaseSupported) { trace("[InAppPurchase] removing product from queue", productId, receipt); extCtx.call("removePurchaseFromQueue", productId, receipt); if (Capabilities.manufacturer.indexOf("iOS") > -1) { _iosPendingPurchases = _iosPendingPurchases.filter(function(jsonPurchase:String, index:int, purchases:Vector.<Object>):Boolean { try { var purchase:Object = JSON.parse(jsonPurchase); return JSON.stringify(purchase.receipt) != receipt; } catch(error:Error) { trace("[InAppPurchase] Couldn't parse purchase: " + jsonPurchase); } return false; }); } } } public function getProductsInfo(productsId:Array):void { if (this.isInAppPurchaseSupported) { trace("[InAppPurchase] get Products Info"); extCtx.call("getProductsInfo", productsId); } else { this.dispatchEvent( new InAppPurchaseEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR) ); } } public function userCanMakeAPurchase():void { if (this.isInAppPurchaseSupported) { trace("[InAppPurchase] check user can make a purchase"); extCtx.call("userCanMakeAPurchase"); } else { this.dispatchEvent(new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_DISABLED)); } } public function userCanMakeASubscription():void { if (Capabilities.manufacturer.indexOf('Android') > -1) { trace("[InAppPurchase] check user can make a purchase"); extCtx.call("userCanMakeASubscription"); } else { this.dispatchEvent(new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_DISABLED)); } } public function makeSubscription(productId:String):void { if (Capabilities.manufacturer.indexOf('Android') > -1) { trace("[InAppPurchase] check user can make a subscription"); extCtx.call("makeSubscription", productId); } else { this.dispatchEvent(new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported")); } } public function restoreTransactions():void { if (Capabilities.manufacturer.indexOf('Android') > -1) { extCtx.call("restoreTransaction"); } else if (Capabilities.manufacturer.indexOf("iOS") > -1) { var jsonPurchases:String = "[" + _iosPendingPurchases.join(",") + "]"; var jsonData:String = "{ \"purchases\": " + jsonPurchases + "}"; dispatchEvent(new InAppPurchaseEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, jsonData)); } } public function stop():void { if (Capabilities.manufacturer.indexOf('Android') > -1) { trace("[InAppPurchase] stop library"); extCtx.call("stopLib"); } } public function get isInAppPurchaseSupported():Boolean { var value:Boolean = Capabilities.manufacturer.indexOf('iOS') > -1 || Capabilities.manufacturer.indexOf('Android') > -1; trace(value ? '[InAppPurchase] in app purchase is supported ' : '[InAppPurchase] in app purchase is not supported '); return value; } private var _iosPendingPurchases:Vector.<Object> = new Vector.<Object>(); private function onStatus(event:StatusEvent):void { trace(event); var e:InAppPurchaseEvent; switch(event.code) { case "INIT_SUCCESSFULL": e = new InAppPurchaseEvent(InAppPurchaseEvent.INIT_SUCCESSFULL); break; case "INIT_ERROR": e = new InAppPurchaseEvent(InAppPurchaseEvent.INIT_ERROR, event.level); break; case "PRODUCT_INFO_RECEIVED": e = new InAppPurchaseEvent(InAppPurchaseEvent.PRODUCT_INFO_RECEIVED, event.level); break; case "PURCHASE_SUCCESSFUL": if (Capabilities.manufacturer.indexOf("iOS") > -1) { _iosPendingPurchases.push(event.level); } e = new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_SUCCESSFULL, event.level); break; case "PURCHASE_ERROR": e = new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_ERROR, event.level); break; case "PURCHASE_ENABLED": e = new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_ENABLED, event.level); break; case "PURCHASE_DISABLED": e = new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_DISABLED, event.level); break; case "PRODUCT_INFO_ERROR": e = new InAppPurchaseEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR); break; case "SUBSCRIPTION_ENABLED": e = new InAppPurchaseEvent(InAppPurchaseEvent.SUBSCRIPTION_ENABLED); break; case "SUBSCRIPTION_DISABLED": e = new InAppPurchaseEvent(InAppPurchaseEvent.SUBSCRIPTION_DISABLED); break; case "RESTORE_INFO_RECEIVED": e = new InAppPurchaseEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, event.level); break; default: } if (e) { this.dispatchEvent(e); } } } }
////////////////////////////////////////////////////////////////////////////////////// // // Copyright 2012 Freshplanet (http://freshplanet.com | [email protected]) // // 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.freshplanet.ane.AirInAppPurchase { import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class InAppPurchase extends EventDispatcher { private static var _instance:InAppPurchase; private var extCtx:*; public function InAppPurchase() { if (!_instance) { if (this.isInAppPurchaseSupported) { extCtx = ExtensionContext.createExtensionContext("com.freshplanet.AirInAppPurchase", null); if (extCtx != null) { extCtx.addEventListener(StatusEvent.STATUS, onStatus); } else { trace('[InAppPurchase] extCtx is null.'); } } _instance = this; } else { throw Error( 'This is a singleton, use getInstance, do not call the constructor directly'); } } public static function getInstance():InAppPurchase { return _instance != null ? _instance : new InAppPurchase(); } public function init(googlePlayKey:String, debug:Boolean = false):void { if (this.isInAppPurchaseSupported) { trace("[InAppPurchase] init library"); extCtx.call("initLib", googlePlayKey, debug); } } public function makePurchase(productId:String ):void { if (this.isInAppPurchaseSupported) { trace("[InAppPurchase] purchasing", productId); extCtx.call("makePurchase", productId); } else { this.dispatchEvent(new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported")); } } // receipt is for android device. public function removePurchaseFromQueue(productId:String, receipt:String):void { if (this.isInAppPurchaseSupported) { trace("[InAppPurchase] removing product from queue", productId, receipt); extCtx.call("removePurchaseFromQueue", productId, receipt); if (Capabilities.manufacturer.indexOf("iOS") > -1) { _iosPendingPurchases = _iosPendingPurchases.filter(function(jsonPurchase:String, index:int, purchases:Vector.<Object>):Boolean { try { var purchase:Object = JSON.parse(jsonPurchase); return JSON.stringify(purchase.receipt) != receipt; } catch(error:Error) { trace("[InAppPurchase] Couldn't parse purchase: " + jsonPurchase); } return false; }); } } } public function getProductsInfo(productsId:Array):void { if (this.isInAppPurchaseSupported) { trace("[InAppPurchase] get Products Info"); extCtx.call("getProductsInfo", productsId); } else { this.dispatchEvent( new InAppPurchaseEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR) ); } } public function userCanMakeAPurchase():void { if (this.isInAppPurchaseSupported) { trace("[InAppPurchase] check user can make a purchase"); extCtx.call("userCanMakeAPurchase"); } else { this.dispatchEvent(new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_DISABLED)); } } public function userCanMakeASubscription():void { if (Capabilities.manufacturer.indexOf('Android') > -1) { trace("[InAppPurchase] check user can make a purchase"); extCtx.call("userCanMakeASubscription"); } else { this.dispatchEvent(new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_DISABLED)); } } public function makeSubscription(productId:String):void { if (Capabilities.manufacturer.indexOf('Android') > -1) { trace("[InAppPurchase] check user can make a subscription"); extCtx.call("makeSubscription", productId); } else { this.dispatchEvent(new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_ERROR, "InAppPurchase not supported")); } } public function restoreTransactions():void { if (Capabilities.manufacturer.indexOf('Android') > -1) { extCtx.call("restoreTransaction"); } else if (Capabilities.manufacturer.indexOf("iOS") > -1) { extCtx.call("restoreTransaction"); //This restore purchases in memory not from appstore //var jsonPurchases:String = "[" + _iosPendingPurchases.join(",") + "]"; //var jsonData:String = "{ \"purchases\": " + jsonPurchases + "}"; //dispatchEvent(new InAppPurchaseEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, jsonData)); } } public function stop():void { if (Capabilities.manufacturer.indexOf('Android') > -1) { trace("[InAppPurchase] stop library"); extCtx.call("stopLib"); } } public function get isInAppPurchaseSupported():Boolean { var value:Boolean = Capabilities.manufacturer.indexOf('iOS') > -1 || Capabilities.manufacturer.indexOf('Android') > -1; trace(value ? '[InAppPurchase] in app purchase is supported ' : '[InAppPurchase] in app purchase is not supported '); return value; } private var _iosPendingPurchases:Vector.<Object> = new Vector.<Object>(); private function onStatus(event:StatusEvent):void { trace(event); var e:InAppPurchaseEvent; switch(event.code) { case "INIT_SUCCESSFULL": e = new InAppPurchaseEvent(InAppPurchaseEvent.INIT_SUCCESSFULL); break; case "INIT_ERROR": e = new InAppPurchaseEvent(InAppPurchaseEvent.INIT_ERROR, event.level); break; case "PRODUCT_INFO_RECEIVED": e = new InAppPurchaseEvent(InAppPurchaseEvent.PRODUCT_INFO_RECEIVED, event.level); break; case "PURCHASE_SUCCESSFUL": if (Capabilities.manufacturer.indexOf("iOS") > -1) { _iosPendingPurchases.push(event.level); } e = new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_SUCCESSFULL, event.level); break; case "PURCHASE_ERROR": e = new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_ERROR, event.level); break; case "PURCHASE_ENABLED": e = new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_ENABLED, event.level); break; case "PURCHASE_DISABLED": e = new InAppPurchaseEvent(InAppPurchaseEvent.PURCHASE_DISABLED, event.level); break; case "PRODUCT_INFO_ERROR": e = new InAppPurchaseEvent(InAppPurchaseEvent.PRODUCT_INFO_ERROR); break; case "SUBSCRIPTION_ENABLED": e = new InAppPurchaseEvent(InAppPurchaseEvent.SUBSCRIPTION_ENABLED); break; case "SUBSCRIPTION_DISABLED": e = new InAppPurchaseEvent(InAppPurchaseEvent.SUBSCRIPTION_DISABLED); break; case "RESTORE_INFO_RECEIVED": e = new InAppPurchaseEvent(InAppPurchaseEvent.RESTORE_INFO_RECEIVED, event.level); break; default: } if (e) { this.dispatchEvent(e); } } } }
Update InAppPurchase.as
Update InAppPurchase.as Restore from appstore not from memory
ActionScript
apache-2.0
Fluocode/ANE-In-App-Purchase,Fluocode/ANE-In-App-Purchase
9b48440b7c66d1f45e7c73806470288bc6a22c6b
src/aerys/minko/scene/node/camera/Camera.as
src/aerys/minko/scene/node/camera/Camera.as
package aerys.minko.scene.node.camera { import aerys.minko.ns.minko_scene; 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; import aerys.minko.type.math.Vector4; import flash.geom.Point; use namespace minko_scene; public class Camera extends AbstractCamera { public static const DEFAULT_FOV : Number = Math.PI * .25; private static const TMP_VECTOR4 : Vector4 = new Vector4(); public function get fieldOfView() : Number { return _cameraData.fieldOfView; } public function set fieldOfView(value : Number) : void { _cameraData.fieldOfView = value; } public function Camera(fieldOfView : Number = DEFAULT_FOV, zNear : Number = AbstractCamera.DEFAULT_ZNEAR, zFar : Number = AbstractCamera.DEFAULT_ZFAR) { super(zNear, zFar); _cameraData.fieldOfView = fieldOfView; } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Camera = new Camera(fieldOfView, zNear, zFar); clone.transform.copyFrom(this.transform); return clone as AbstractSceneNode; } override public function unproject(x : Number, y : Number, out : Ray = null) : Ray { if (!(root is Scene)) throw new Error('Camera must be in the scene to unproject vectors.'); out ||= new Ray(); var sceneBindings : DataBindings = (root as Scene).bindings; var zNear : Number = _cameraData.zNear; var zFar : Number = _cameraData.zFar; var fovDiv2 : Number = _cameraData.fieldOfView * 0.5; var width : Number = sceneBindings.getProperty('viewportWidth'); var height : Number = sceneBindings.getProperty('viewportHeight'); var xPercent : Number = 2.0 * (x / width - 0.5); var yPercent : Number = 2.0 * (y / height - 0.5); var dx : Number = Math.tan(fovDiv2) * xPercent * (width / height); var dy : Number = -Math.tan(fovDiv2) * yPercent; out.origin.set(dx * zNear, dy * zNear, zNear); out.direction.set(dx * zNear, dy * zNear, zNear).normalize(); localToWorld(out.origin, out.origin); localToWorld(out.direction, out.direction, true); return out; } override public function project(localToWorld : Matrix4x4, output : Point = null) : Point { output ||= new Point(); var sceneBindings : DataBindings = (root as Scene).bindings; var width : Number = sceneBindings.getProperty('viewportWidth'); var height : Number = sceneBindings.getProperty('viewportHeight'); var translation : Vector4 = localToWorld.getTranslation(); var screenPosition : Vector4 = _cameraData.worldToScreen.projectVector( translation, TMP_VECTOR4 ); output.x = width * ((screenPosition.x + 1.0) * .5); output.y = height * ((1.0 - ((screenPosition.y + 1.0) * .5))); return output; } } }
package aerys.minko.scene.node.camera { import aerys.minko.ns.minko_scene; 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; import aerys.minko.type.math.Vector4; import flash.geom.Point; use namespace minko_scene; public class Camera extends AbstractCamera { public static const DEFAULT_FOV : Number = Math.PI * .25; private static const TMP_VECTOR4 : Vector4 = new Vector4(); public function get fieldOfView() : Number { return _cameraData.fieldOfView; } public function set fieldOfView(value : Number) : void { _cameraData.fieldOfView = value; } public function Camera(fieldOfView : Number = DEFAULT_FOV, zNear : Number = AbstractCamera.DEFAULT_ZNEAR, zFar : Number = AbstractCamera.DEFAULT_ZFAR) { super(zNear, zFar); _cameraData.fieldOfView = fieldOfView; } override minko_scene function cloneNode() : AbstractSceneNode { var clone : Camera = new Camera(fieldOfView, zNear, zFar); clone.transform.copyFrom(this.transform); return clone as AbstractSceneNode; } override public function unproject(x : Number, y : Number, out : Ray = null) : Ray { if (!(root is Scene)) throw new Error('Camera must be in the scene to unproject vectors.'); out ||= new Ray(); var sceneBindings : DataBindings = (root as Scene).bindings; var zNear : Number = _cameraData.zNear; var zFar : Number = _cameraData.zFar; var fovDiv2 : Number = _cameraData.fieldOfView * 0.5; var width : Number = sceneBindings.propertyExists('viewportWidth') ? sceneBindings.getProperty('viewportWidth') : 0.; var height : Number = sceneBindings.propertyExists('viewportHeight') ? sceneBindings.getProperty('viewportHeight') : 0.; var xPercent : Number = 2.0 * (x / width - 0.5); var yPercent : Number = 2.0 * (y / height - 0.5); var dx : Number = Math.tan(fovDiv2) * xPercent * (width / height); var dy : Number = -Math.tan(fovDiv2) * yPercent; out.origin.set(dx * zNear, dy * zNear, zNear); out.direction.set(dx * zNear, dy * zNear, zNear).normalize(); localToWorld(out.origin, out.origin); localToWorld(out.direction, out.direction, true); return out; } override public function project(localToWorld : Matrix4x4, output : Point = null) : Point { output ||= new Point(); var sceneBindings : DataBindings = (root as Scene).bindings; var width : Number = sceneBindings.getProperty('viewportWidth'); var height : Number = sceneBindings.getProperty('viewportHeight'); var translation : Vector4 = localToWorld.getTranslation(); var screenPosition : Vector4 = _cameraData.worldToScreen.projectVector( translation, TMP_VECTOR4 ); output.x = width * ((screenPosition.x + 1.0) * .5); output.y = height * ((1.0 - ((screenPosition.y + 1.0) * .5))); return output; } } }
use 0 as default value when viewportWidth/viewportHeight is not defined in the scene bindings
use 0 as default value when viewportWidth/viewportHeight is not defined in the scene bindings
ActionScript
mit
aerys/minko-as3
4cebaac301f89a38b4685dbca9897a81d5c6567a
WeaveData/src/weave/data/BinningDefinitions/CategoryBinningDefinition.as
WeaveData/src/weave/data/BinningDefinitions/CategoryBinningDefinition.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.BinningDefinitions { import mx.utils.ObjectUtil; import weave.api.data.IAttributeColumn; import weave.api.data.IQualifiedKey; import weave.data.BinClassifiers.SingleValueClassifier; import weave.utils.AsyncSort; /** * Creates a separate bin for every string value in a column. * * @author adufilie */ public class CategoryBinningDefinition extends AbstractBinningDefinition { public function CategoryBinningDefinition() { overrideBinNames.lock(); // no bin names allowed } /** * This function sorts string values by their corresponding numeric values stored in _sortMap. */ private function _sortFunc(str1:String, str2:String):int { return ObjectUtil.numericCompare(_sortMap[str1], _sortMap[str2]) || ObjectUtil.stringCompare(str1, str2); } private var _sortMap:Object; // used by _sortFunc /** * derive an explicit definition. */ override public function generateBinClassifiersForColumn(column:IAttributeColumn):void { // clear any existing bin classifiers output.removeAllObjects(); // get all string values in the a column _sortMap = {}; var strArray:Array = new Array(column.keys.length); // alloc max length var i:int = 0; var str:String; for each (var key:IQualifiedKey in column.keys) { str = column.getValueFromKey(key, String) as String; if (str && !_sortMap.hasOwnProperty(str)) { strArray[int(i++)] = str; _sortMap[str] = column.getValueFromKey(key, Number); } } strArray.length = i; // truncate AsyncSort.sortImmediately(strArray, _sortFunc); // sort strings by corresponding numeric values var n:int = strArray.length; for (i = 0; i < n; i++) { //first get name from overrideBinNames str = strArray[i] as String; //TODO: look up replacement name once we store original + modified names together rather than a simple Array of replacement names. var svc:SingleValueClassifier = output.requestObject(str, SingleValueClassifier, false); svc.value = strArray[i]; } // trigger callbacks now because we're done updating the output asyncResultCallbacks.triggerCallbacks(); } } }
/* 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.BinningDefinitions { import mx.utils.ObjectUtil; import weave.api.WeaveAPI; import weave.api.data.IAttributeColumn; import weave.api.data.IQualifiedKey; import weave.core.SessionManager; import weave.data.BinClassifiers.SingleValueClassifier; import weave.utils.AsyncSort; /** * Creates a separate bin for every string value in a column. * * @author adufilie */ public class CategoryBinningDefinition extends AbstractBinningDefinition { public function CategoryBinningDefinition() { overrideBinNames.lock(); // no bin names allowed (WeaveAPI.SessionManager as SessionManager).unregisterLinkableChild(this, overrideBinNames); } /** * This function sorts string values by their corresponding numeric values stored in _sortMap. */ private function _sortFunc(str1:String, str2:String):int { return ObjectUtil.numericCompare(_sortMap[str1], _sortMap[str2]) || ObjectUtil.stringCompare(str1, str2); } private var _sortMap:Object; // used by _sortFunc /** * derive an explicit definition. */ override public function generateBinClassifiersForColumn(column:IAttributeColumn):void { // clear any existing bin classifiers output.removeAllObjects(); // get all string values in the a column _sortMap = {}; var strArray:Array = new Array(column.keys.length); // alloc max length var i:int = 0; var str:String; for each (var key:IQualifiedKey in column.keys) { str = column.getValueFromKey(key, String) as String; if (str && !_sortMap.hasOwnProperty(str)) { strArray[int(i++)] = str; _sortMap[str] = column.getValueFromKey(key, Number); } } strArray.length = i; // truncate AsyncSort.sortImmediately(strArray, _sortFunc); // sort strings by corresponding numeric values var n:int = strArray.length; for (i = 0; i < n; i++) { //first get name from overrideBinNames str = strArray[i] as String; //TODO: look up replacement name once we store original + modified names together rather than a simple Array of replacement names. var svc:SingleValueClassifier = output.requestObject(str, SingleValueClassifier, false); svc.value = strArray[i]; } // trigger callbacks now because we're done updating the output asyncResultCallbacks.triggerCallbacks(); } } }
hide unused variable
hide unused variable Change-Id: I8f5219585e79a177734200d196167153c566b751
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
1dc22ceba5acfb615ba2327c6baac155b8a48038
src/main/actionscript/com/dotfold/dotvimstat/model/UserInfoEntity.as
src/main/actionscript/com/dotfold/dotvimstat/model/UserInfoEntity.as
package com.dotfold.dotvimstat.model { /** * * @author jamesmcnamee * */ public class UserInfoEntity extends BaseEntity { public function UserInfoEntity() { super(); } public var displayName:String; public var created_on:String; public var is_staff:Boolean; public var is_plus:Boolean; public var is_pro:Boolean; public var location:String; public var url:String; public var bio:String; public var profile_url:String; public var videos_url:String; public var total_videos_uploaded:int; public var total_videos_appears_in:int; public var total_videos_liked:int; public var total_contacts:int; public var total_albums:int; public var total_channels:int; public var portrait_small:String; public var portrait_medium:String; public var portrait_large:String; public var portrait_huge:String; } }
package com.dotfold.dotvimstat.model { import com.dotfold.dotvimstat.model.image.EntityImage; import com.dotfold.dotvimstat.model.image.EntityImageCollection; /** * * @author jamesmcnamee * */ public class UserInfoEntity extends BaseEntity { public function UserInfoEntity() { super(); } public var display_name:String; public var created_on:String; public var is_staff:Boolean; public var is_plus:Boolean; public var is_pro:Boolean; public var location:String; public var url:String; public var bio:String; public var profile_url:String; public var videos_url:String; public var total_videos_uploaded:int; public var total_videos_appears_in:int; public var total_videos_liked:int; public var total_contacts:int; public var total_albums:int; public var total_channels:int; private var _portrait_small:String public function get portrait_small():String { return _portrait_small; } public function set portrait_small(value:String):void { _portrait_small = value; var image:EntityImage = new EntityImage(); image.url = value; image.size = 'small'; images.addItem(image); } private var _portrait_medium:String public function get portrait_medium():String { return _portrait_medium; } public function set portrait_medium(value:String):void { _portrait_medium = value; var image:EntityImage = new EntityImage(); image.url = value; image.size = 'medium'; images.addItem(image); } private var _portrait_large:String public function get portrait_large():String { return _portrait_large; } public function set portrait_large(value:String):void { _portrait_large = value; var image:EntityImage = new EntityImage(); image.url = value; image.size = 'large'; images.addItem(image); } private var _portrait_huge:String public function get portrait_huge():String { return _portrait_huge; } public function set portrait_huge(value:String):void { _portrait_huge = value; var image:EntityImage = new EntityImage(); image.url = value; image.size = 'huge'; images.addItem(image); } public var images:EntityImageCollection = new EntityImageCollection(); } }
add UserInfoEntity
[feat] add UserInfoEntity
ActionScript
mit
dotfold/dotvimstat
65e0f8015e467ae8e6dab24c2d40ac4324673329
src/as/com/threerings/flex/CommandMenu.as
src/as/com/threerings/flex/CommandMenu.as
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // 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.flex { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.IEventDispatcher; import flash.geom.Point; import flash.geom.Rectangle; import mx.controls.Menu; import mx.controls.listClasses.BaseListData; import mx.controls.listClasses.IListItemRenderer; import mx.controls.menuClasses.IMenuItemRenderer; import mx.controls.menuClasses.MenuListData; import mx.core.mx_internal; import mx.core.Application; import mx.core.ClassFactory; import mx.core.IFlexDisplayObject; import mx.core.ScrollPolicy; import mx.events.MenuEvent; import mx.managers.PopUpManager; import mx.utils.ObjectUtil; import flexlib.controls.ScrollableArrowMenu; import com.threerings.util.CommandEvent; import com.threerings.flex.PopUpUtil; import com.threerings.flex.menuClasses.CommandMenuItemRenderer; import com.threerings.flex.menuClasses.CommandListData; use namespace mx_internal; /** * A pretty standard menu that can submit CommandEvents if menu items have "command" and possibly * "arg" properties. Commands are submitted to controllers for processing. Alternatively, you may * specify "callback" properties that specify a function closure to call, with the "arg" property * containing either a single arg or an array of args. * * Another property now supported is "iconObject", which is an already-instantiated * IFlexDisplayObject to use as the icon. This will only be applied if the "icon" property * (which specifies a Class) is not used. * * Example dataProvider array: * [ { label: "Go home", icon: homeIconClass, * command: Controller.GO_HOME, arg: homeId }, * { type: "separator"}, { label: "Crazytown", callback: setCrazy, arg: [ true, false ] }, * { label: "Other places", children: subMenuArray } * ]; * * See "Defining menu structure and data" in the Flex manual for the full list. */ public class CommandMenu extends Menu { /** * Factory method to create a command menu. * * @param items an array of menu items. * @param dispatcher an override event dispatcher to use for command events, rather than * our parent. */ public static function createMenu ( items :Array, dispatcher :IEventDispatcher = null) :CommandMenu { var menu :CommandMenu = new CommandMenu(); menu.owner = DisplayObjectContainer(Application.application); menu.tabEnabled = false; menu.showRoot = true; menu.setDispatcher(dispatcher); Menu.popUpMenu(menu, null, items); // does not actually pop up, but needed. return menu; } public function CommandMenu () { super(); itemRenderer = new ClassFactory(CommandMenuItemRenderer); verticalScrollPolicy = ScrollPolicy.OFF; addEventListener(MenuEvent.ITEM_CLICK, itemClicked); } /** * Configures the event dispatcher to be used when dispatching this menu's command events. * Normally they will be dispatched on our parent (usually the SystemManager or something). */ public function setDispatcher (dispatcher :IEventDispatcher) :void { _dispatcher = dispatcher; } /** * Actually pop up the menu. This can be used instead of show(). */ public function popUp ( trigger :DisplayObject, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; var r :Rectangle = trigger.getBounds(trigger.stage); show(_lefting ? r.left : r.right, _upping ? r.top : r.bottom); } /** * Shows the menu at the specified mouse coordinates. */ public function popUpAt ( mx :int, my :int, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(mx, my); } /** * Shows the menu at the current mouse location. */ public function popUpAtMouse (popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(); // our show, with no args, pops at the mouse } /** * Just like our superclass's show(), except that when invoked with no args, causes the menu to * show at the current mouse location instead of the top-left corner of the application. * Also, we ensure that the resulting menu is in-bounds. */ override public function show (xShow :Object = null, yShow :Object = null) :void { if (xShow == null) { xShow = DisplayObject(Application.application).mouseX; } if (yShow == null) { yShow = DisplayObject(Application.application).mouseY; } super.show(xShow, yShow); // reposition now that we know our size if (_lefting) { y = x - getExplicitOrMeasuredWidth(); } if (_upping) { y = y - getExplicitOrMeasuredHeight(); } PopUpUtil.fit(this); } /** * Callback for MenuEvent.ITEM_CLICK. */ protected function itemClicked (event :MenuEvent) :void { var arg :Object = getItemProp(event.item, "arg"); var cmdOrFn :Object = getItemProp(event.item, "command"); if (cmdOrFn == null) { cmdOrFn = getItemProp(event.item, "callback"); } if (cmdOrFn != null) { event.stopImmediatePropagation(); CommandEvent.dispatch(_dispatcher == null ? mx_internal::parentDisplayObject : _dispatcher, cmdOrFn, arg); } // else: no warning. There may be non-command menu items mixed in. } // from ScrollableArrowMenu.. override mx_internal function openSubMenu (row :IListItemRenderer) :void { supposedToLoseFocus = true; var r :Menu = getRootMenu(); var menu :CommandMenu; // check to see if the menu exists, if not create it if (!IMenuItemRenderer(row).menu) { // the only differences between this method and the original method in mx.controls.Menu // are these few lines. menu = new CommandMenu(); menu.maxHeight = this.maxHeight; menu.verticalScrollPolicy = this.verticalScrollPolicy; menu.variableRowHeight = this.variableRowHeight; menu.parentMenu = this; menu.owner = this; menu.showRoot = showRoot; menu.dataDescriptor = r.dataDescriptor; menu.styleName = r; menu.labelField = r.labelField; menu.labelFunction = r.labelFunction; menu.iconField = r.iconField; menu.iconFunction = r.iconFunction; menu.itemRenderer = r.itemRenderer; menu.rowHeight = r.rowHeight; menu.scaleY = r.scaleY; menu.scaleX = r.scaleX; // if there's data and it has children then add the items if (row.data && _dataDescriptor.isBranch(row.data) && _dataDescriptor.hasChildren(row.data)) { menu.dataProvider = _dataDescriptor.getChildren(row.data); } menu.sourceMenuBar = sourceMenuBar; menu.sourceMenuBarItem = sourceMenuBarItem; IMenuItemRenderer(row).menu = menu; PopUpManager.addPopUp(menu, r, false); } super.openSubMenu(row); // if we're lefting, upping or fitting make sure our submenu does so as well var submenu :Menu = IMenuItemRenderer(row).menu; var lefting :Boolean = _lefting; var upping :Boolean = _upping; var fitting :Rectangle = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); if (submenu.x + submenu.getExplicitOrMeasuredWidth() > fitting.right) { lefting = true; } if (submenu.y + submenu.getExplicitOrMeasuredHeight() > fitting.bottom) { upping = true; } if (lefting) { submenu.x -= submenu.getExplicitOrMeasuredWidth(); } if (upping) { var displayObj :DisplayObject = DisplayObject(row); var rowLoc :Point = displayObj.localToGlobal(new Point(row.x, row.y)); submenu.y = rowLoc.y - submenu.getExplicitOrMeasuredHeight() + displayObj.height; } // if we've poped out of the boundaries, just snap it to the lower right corner, or upper // if upping, left if lefting if (submenu.x < fitting.left) { submenu.x = lefting ? 0 : Math.max( fitting.right - submenu.getExplicitOrMeasuredWidth(), fitting.left); } if (submenu.y < fitting.top) { submenu.y = upping ? 0 : Math.max( fitting.bottom - submenu.getExplicitOrMeasuredHeight(), fitting.top); } } // from List override protected function makeListData (data :Object, uid :String, rowNum :int) :BaseListData { // Oh, FFS. // We need to set up these "maxMeasuredIconWidth" fields on the MenuListData, but our // superclass has made those variables private. // We can get the values out of another MenuListData, so we just always call super() // to create one of those, and if we need to make a CommandListData, we construct one // from the fields in the MenuListData. var menuListData :MenuListData = super.makeListData(data, uid, rowNum) as MenuListData; var iconObject :IFlexDisplayObject = getItemProp(data, "iconObject") as IFlexDisplayObject; if (iconObject != null) { var cmdListData :CommandListData = new CommandListData(menuListData.label, menuListData.icon, iconObject, labelField, uid, this, rowNum); cmdListData.maxMeasuredIconWidth = menuListData.maxMeasuredIconWidth; cmdListData.maxMeasuredTypeIconWidth = menuListData.maxMeasuredTypeIconWidth; cmdListData.maxMeasuredBranchIconWidth = menuListData.maxMeasuredBranchIconWidth; cmdListData.useTwoColumns = menuListData.useTwoColumns; return cmdListData; } return menuListData; } /** * Get the specified property for the specified item, if any. Somewhat similar to bits in the * DefaultDataDescriptor. */ protected function getItemProp (item :Object, prop :String) :Object { try { if (item is XML) { return String((item as XML).attribute(prop)); } else if (prop in item) { return item[prop]; } } catch (e :Error) { // alas; fall through } return null; } protected var _dispatcher :IEventDispatcher; protected var _lefting :Boolean = false; protected var _upping :Boolean = false; } }
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // 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.flex { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.IEventDispatcher; import flash.geom.Point; import flash.geom.Rectangle; import mx.controls.Menu; import mx.controls.listClasses.BaseListData; import mx.controls.listClasses.IListItemRenderer; import mx.controls.menuClasses.IMenuItemRenderer; import mx.controls.menuClasses.MenuListData; import mx.core.mx_internal; import mx.core.Application; import mx.core.ClassFactory; import mx.core.IFlexDisplayObject; import mx.core.ScrollPolicy; import mx.events.MenuEvent; import mx.managers.PopUpManager; import mx.utils.ObjectUtil; import flexlib.controls.ScrollableArrowMenu; import com.threerings.util.CommandEvent; import com.threerings.flex.PopUpUtil; import com.threerings.flex.menuClasses.CommandMenuItemRenderer; import com.threerings.flex.menuClasses.CommandListData; use namespace mx_internal; /** * A pretty standard menu that can submit CommandEvents if menu items have "command" and possibly * "arg" properties. Commands are submitted to controllers for processing. Alternatively, you may * specify "callback" properties that specify a function closure to call, with the "arg" property * containing either a single arg or an array of args. * * Another property now supported is "iconObject", which is an already-instantiated * IFlexDisplayObject to use as the icon. This will only be applied if the "icon" property * (which specifies a Class) is not used. * * Example dataProvider array: * [ { label: "Go home", icon: homeIconClass, * command: Controller.GO_HOME, arg: homeId }, * { type: "separator"}, { label: "Crazytown", callback: setCrazy, arg: [ true, false ] }, * { label: "Other places", children: subMenuArray } * ]; * * See "Defining menu structure and data" in the Flex manual for the full list. */ public class CommandMenu extends Menu { /** * Factory method to create a command menu. * * @param items an array of menu items. * @param dispatcher an override event dispatcher to use for command events, rather than * our parent. */ public static function createMenu ( items :Array, dispatcher :IEventDispatcher = null) :CommandMenu { var menu :CommandMenu = new CommandMenu(); menu.owner = DisplayObjectContainer(Application.application); menu.tabEnabled = false; menu.showRoot = true; menu.setDispatcher(dispatcher); Menu.popUpMenu(menu, null, items); // does not actually pop up, but needed. return menu; } public function CommandMenu () { super(); itemRenderer = new ClassFactory(CommandMenuItemRenderer); verticalScrollPolicy = ScrollPolicy.OFF; addEventListener(MenuEvent.ITEM_CLICK, itemClicked); } /** * Configures the event dispatcher to be used when dispatching this menu's command events. * Normally they will be dispatched on our parent (usually the SystemManager or something). */ public function setDispatcher (dispatcher :IEventDispatcher) :void { _dispatcher = dispatcher; } /** * Sets a Rectangle (in stage coords) that the menu will attempt to keep submenus positioned * within. If a submenu is too large to fit, it will position it in the lower right corner * of this Rectangle (or top if popping upwards, or left if popping leftwards). This * value defaults to the stage bounds. */ public function setBounds (fitting :Rectangle) :void { _fitting = fitting; } /** * Actually pop up the menu. This can be used instead of show(). */ public function popUp ( trigger :DisplayObject, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; var r :Rectangle = trigger.getBounds(trigger.stage); show(_lefting ? r.left : r.right, _upping ? r.top : r.bottom); } /** * Shows the menu at the specified mouse coordinates. */ public function popUpAt ( mx :int, my :int, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(mx, my); } /** * Shows the menu at the current mouse location. */ public function popUpAtMouse (popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(); // our show, with no args, pops at the mouse } /** * Just like our superclass's show(), except that when invoked with no args, causes the menu to * show at the current mouse location instead of the top-left corner of the application. * Also, we ensure that the resulting menu is in-bounds. */ override public function show (xShow :Object = null, yShow :Object = null) :void { if (xShow == null) { xShow = DisplayObject(Application.application).mouseX; } if (yShow == null) { yShow = DisplayObject(Application.application).mouseY; } super.show(xShow, yShow); // reposition now that we know our size if (_lefting) { y = x - getExplicitOrMeasuredWidth(); } if (_upping) { y = y - getExplicitOrMeasuredHeight(); } PopUpUtil.fit(this); } /** * Callback for MenuEvent.ITEM_CLICK. */ protected function itemClicked (event :MenuEvent) :void { var arg :Object = getItemProp(event.item, "arg"); var cmdOrFn :Object = getItemProp(event.item, "command"); if (cmdOrFn == null) { cmdOrFn = getItemProp(event.item, "callback"); } if (cmdOrFn != null) { event.stopImmediatePropagation(); CommandEvent.dispatch(_dispatcher == null ? mx_internal::parentDisplayObject : _dispatcher, cmdOrFn, arg); } // else: no warning. There may be non-command menu items mixed in. } // from ScrollableArrowMenu.. override mx_internal function openSubMenu (row :IListItemRenderer) :void { supposedToLoseFocus = true; var r :Menu = getRootMenu(); var menu :CommandMenu; // check to see if the menu exists, if not create it if (!IMenuItemRenderer(row).menu) { // the only differences between this method and the original method in mx.controls.Menu // are these few lines. menu = new CommandMenu(); menu.maxHeight = this.maxHeight; menu.verticalScrollPolicy = this.verticalScrollPolicy; menu.variableRowHeight = this.variableRowHeight; menu.parentMenu = this; menu.owner = this; menu.showRoot = showRoot; menu.dataDescriptor = r.dataDescriptor; menu.styleName = r; menu.labelField = r.labelField; menu.labelFunction = r.labelFunction; menu.iconField = r.iconField; menu.iconFunction = r.iconFunction; menu.itemRenderer = r.itemRenderer; menu.rowHeight = r.rowHeight; menu.scaleY = r.scaleY; menu.scaleX = r.scaleX; // if there's data and it has children then add the items if (row.data && _dataDescriptor.isBranch(row.data) && _dataDescriptor.hasChildren(row.data)) { menu.dataProvider = _dataDescriptor.getChildren(row.data); } menu.sourceMenuBar = sourceMenuBar; menu.sourceMenuBarItem = sourceMenuBarItem; IMenuItemRenderer(row).menu = menu; PopUpManager.addPopUp(menu, r, false); } super.openSubMenu(row); // if we're lefting, upping or fitting make sure our submenu does so as well var submenu :Menu = IMenuItemRenderer(row).menu; var lefting :Boolean = _lefting; var upping :Boolean = _upping; var fitting :Rectangle = _fitting != null ? _fitting : new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); if (submenu.x + submenu.getExplicitOrMeasuredWidth() > fitting.right) { lefting = true; } if (submenu.y + submenu.getExplicitOrMeasuredHeight() > fitting.bottom) { upping = true; } if (lefting) { submenu.x -= submenu.getExplicitOrMeasuredWidth(); } if (upping) { var displayObj :DisplayObject = DisplayObject(row); var rowLoc :Point = displayObj.localToGlobal(new Point(row.x, row.y)); submenu.y = rowLoc.y - submenu.getExplicitOrMeasuredHeight() + displayObj.height; } // if we've poped out of the boundaries, just snap it to the lower right corner, or upper // if upping, left if lefting if (submenu.x < fitting.left) { submenu.x = lefting ? fitting.left : Math.max( fitting.right - submenu.getExplicitOrMeasuredWidth(), fitting.left); } if (submenu.y < fitting.top) { submenu.y = upping ? fitting.top : Math.max( fitting.bottom - submenu.getExplicitOrMeasuredHeight(), fitting.top); } } // from List override protected function makeListData (data :Object, uid :String, rowNum :int) :BaseListData { // Oh, FFS. // We need to set up these "maxMeasuredIconWidth" fields on the MenuListData, but our // superclass has made those variables private. // We can get the values out of another MenuListData, so we just always call super() // to create one of those, and if we need to make a CommandListData, we construct one // from the fields in the MenuListData. var menuListData :MenuListData = super.makeListData(data, uid, rowNum) as MenuListData; var iconObject :IFlexDisplayObject = getItemProp(data, "iconObject") as IFlexDisplayObject; if (iconObject != null) { var cmdListData :CommandListData = new CommandListData(menuListData.label, menuListData.icon, iconObject, labelField, uid, this, rowNum); cmdListData.maxMeasuredIconWidth = menuListData.maxMeasuredIconWidth; cmdListData.maxMeasuredTypeIconWidth = menuListData.maxMeasuredTypeIconWidth; cmdListData.maxMeasuredBranchIconWidth = menuListData.maxMeasuredBranchIconWidth; cmdListData.useTwoColumns = menuListData.useTwoColumns; return cmdListData; } return menuListData; } /** * Get the specified property for the specified item, if any. Somewhat similar to bits in the * DefaultDataDescriptor. */ protected function getItemProp (item :Object, prop :String) :Object { try { if (item is XML) { return String((item as XML).attribute(prop)); } else if (prop in item) { return item[prop]; } } catch (e :Error) { // alas; fall through } return null; } protected var _dispatcher :IEventDispatcher; protected var _lefting :Boolean = false; protected var _upping :Boolean = false; protected var _fitting :Rectangle = null; } }
Allow the creator to specify their own bounds if they don't want submenus to be constrained by the stage.
Allow the creator to specify their own bounds if they don't want submenus to be constrained by the stage. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@519 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
f33cbb1c41529a35bc545a9260e9cb95eee37846
src/aerys/minko/render/shader/compiler/graph/nodes/vertex/Instruction.as
src/aerys/minko/render/shader/compiler/graph/nodes/vertex/Instruction.as
package aerys.minko.render.shader.compiler.graph.nodes.vertex { import aerys.minko.render.shader.compiler.CRC32; import aerys.minko.render.shader.compiler.InstructionFlag; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.compiler.register.Components; import flash.utils.Dictionary; /** * @private * @author Romain Gilliotte */ public class Instruction extends AbstractNode { public static const MOV : uint = 0x00; public static const ADD : uint = 0x01; public static const SUB : uint = 0x02; public static const MUL : uint = 0x03; public static const DIV : uint = 0x04; public static const RCP : uint = 0x05; public static const MIN : uint = 0x06; public static const MAX : uint = 0x07; public static const FRC : uint = 0x08; public static const SQT : uint = 0x09; public static const RSQ : uint = 0x0a; public static const POW : uint = 0x0b; public static const LOG : uint = 0x0c; public static const EXP : uint = 0x0d; public static const NRM : uint = 0x0e; public static const SIN : uint = 0x0f; public static const COS : uint = 0x10; public static const CRS : uint = 0x11; public static const DP3 : uint = 0x12; public static const DP4 : uint = 0x13; public static const ABS : uint = 0x14; public static const NEG : uint = 0x15; public static const SAT : uint = 0x16; public static const M33 : uint = 0x17; public static const M44 : uint = 0x18; public static const M34 : uint = 0x19; public static const KIL : uint = 0x27; public static const TEX : uint = 0x28; public static const SGE : uint = 0x29; public static const SLT : uint = 0x2a; public static const SEQ : uint = 0x2c; public static const SNE : uint = 0x2d; public static const MUL_MAT33 : uint = 0x100; public static const MUL_MAT44 : uint = 0x101; public static const NAME : Dictionary = new Dictionary(); { NAME[MOV] = 'mov'; NAME[ADD] = 'add'; NAME[SUB] = 'sub'; NAME[MUL] = 'mul'; NAME[DIV] = 'div'; NAME[RCP] = 'rcp'; NAME[MIN] = 'min'; NAME[MAX] = 'max'; NAME[FRC] = 'frc'; NAME[SQT] = 'sqt'; NAME[RSQ] = 'rsq'; NAME[POW] = 'pow'; NAME[LOG] = 'log'; NAME[EXP] = 'exp'; NAME[NRM] = 'nrm'; NAME[SIN] = 'sin'; NAME[COS] = 'cos'; NAME[CRS] = 'crs'; NAME[DP3] = 'dp3'; NAME[DP4] = 'dp4'; NAME[ABS] = 'abs'; NAME[NEG] = 'neg'; NAME[SAT] = 'sat'; NAME[M33] = 'm33'; NAME[M44] = 'm44'; NAME[M34] = 'm34'; NAME[TEX] = 'tex'; NAME[KIL] = 'kil'; NAME[SGE] = 'sge'; NAME[SLT] = 'slt'; NAME[SEQ] = 'seq'; NAME[SNE] = 'sne'; NAME[MUL_MAT33] = 'mulMat33'; NAME[MUL_MAT44] = 'mulMat44'; } private static const FLAGS : Dictionary = new Dictionary(); { FLAGS[MOV] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[ADD] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE | InstructionFlag.LINEAR; FLAGS[SUB] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.LINEAR; FLAGS[MUL] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE | InstructionFlag.LINEAR; FLAGS[DIV] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.LINEAR; FLAGS[RCP] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[MIN] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[MAX] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[FRC] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[SQT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[RSQ] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[POW] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[LOG] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[EXP] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[NRM] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SINGLE; FLAGS[SIN] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[COS] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[CRS] = InstructionFlag.AVAILABLE_ALL; FLAGS[DP3] = InstructionFlag.AVAILABLE_ALL; FLAGS[DP4] = InstructionFlag.AVAILABLE_ALL; FLAGS[ABS] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[NEG] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[SAT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[M33] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[M44] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[M34] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[KIL] = InstructionFlag.AVAILABLE_FS | InstructionFlag.SINGLE; FLAGS[TEX] = InstructionFlag.AVAILABLE_FS; FLAGS[SGE] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[SLT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[SEQ] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[SNE] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[MUL_MAT33] = InstructionFlag.AVAILABLE_CPU | InstructionFlag.ASSOCIATIVE; FLAGS[MUL_MAT44] = InstructionFlag.AVAILABLE_CPU | InstructionFlag.ASSOCIATIVE; } private var _id : uint; public function get id() : uint { return _id; } public function get name() : String { return NAME[_id]; } public function get argument1() : AbstractNode { return getArgumentAt(0); } public function get argument2() : AbstractNode { return getArgumentAt(1); } public function get component1() : uint { return getComponentAt(0); } public function get component2() : uint { return getComponentAt(1); } public function set argument1(v : AbstractNode) : void { setArgumentAt(0, v); } public function set argument2(v : AbstractNode) : void { setArgumentAt(1, v); } public function set component1(v : uint) : void { setComponentAt(0, v); } public function set component2(v : uint) : void { setComponentAt(1, v); } public function get isAssociative() : Boolean { return (FLAGS[_id] & InstructionFlag.ASSOCIATIVE) != 0; } public function get isComponentWise() : Boolean { return (FLAGS[_id] & InstructionFlag.COMPONENT_WISE) != 0; } public function get isSingle() : Boolean { return (FLAGS[_id] & InstructionFlag.SINGLE) != 0; } public function get isLinear() : Boolean { return (FLAGS[_id] & InstructionFlag.LINEAR) != 0; } public function isCommutative() : Boolean { return (FLAGS[_id] & InstructionFlag.COMMUTATIVE) != 0; } public function Instruction(id : uint, argument1 : AbstractNode, argument2 : AbstractNode = null) { _id = id; var component1 : uint = id == MUL_MAT33 || id == MUL_MAT44 ? Components.createContinuous(0, 0, 4, 4) : Components.createContinuous(0, 0, argument1.size, argument1.size) var arguments : Vector.<AbstractNode> = new <AbstractNode>[argument1]; var components : Vector.<uint> = new <uint>[component1]; if (!isSingle) { var component2 : uint; if ((FLAGS[id] & InstructionFlag.SPECIAL_MATRIX) != 0) component2 = Components.createContinuous(0, 0, 4, 4); else if (id != TEX && id != MUL_MAT33 && id != MUL_MAT44) component2 = Components.createContinuous(0, 0, argument2.size, argument2.size); arguments.push(argument2); components.push(component2); } arguments.fixed = components.fixed = true; super(arguments, components); } override protected function computeHash() : uint { // commutative operations invert the arguments when computing the hash if arg1.crc > arg2.crc // that way, mul(a, b).hash == mul(b, a).hash var hashLeft : String = argument1.hash.toString(16) + '_' + component1.toString(16); if ((FLAGS[_id] & InstructionFlag.SINGLE) != 0) return CRC32.computeForString(hashLeft); else { var hashRight : String = argument2.hash.toString(16) + '_' + component2.toString(16); if ((FLAGS[_id] & InstructionFlag.COMMUTATIVE) != 0 && argument1.hash > argument2.hash) return CRC32.computeForString(hashRight + hashLeft); else return CRC32.computeForString(hashLeft + hashRight); } } override protected function computeSize() : uint { switch (_id) { case DP3: case DP4: return 1; case M33: case M34: case NRM: case CRS: return 3; case TEX: case M44: return 4; default: var nodeSize : uint; nodeSize = Components.getMaxWriteOffset(component1) - Components.getMinWriteOffset(component1) + 1; if (nodeSize > 4) throw new Error(); if (!isSingle) nodeSize = Math.max(nodeSize, Components.getMaxWriteOffset(component2) - Components.getMinWriteOffset(component2) + 1 ); if (nodeSize < 1) throw new Error(); if (nodeSize > 4) throw new Error(); return nodeSize; } } override public function toString() : String { return name; } override public function clone() : AbstractNode { var clone : Instruction; if (isSingle) { clone = new Instruction(_id, argument1); clone.component1 = component1; } else { clone = new Instruction(_id, argument1, argument2); clone.component1 = component1; clone.component2 = component2; } return clone; } } }
package aerys.minko.render.shader.compiler.graph.nodes.vertex { import aerys.minko.render.shader.compiler.CRC32; import aerys.minko.render.shader.compiler.InstructionFlag; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.compiler.register.Components; import flash.utils.Dictionary; /** * @private * @author Romain Gilliotte */ public class Instruction extends AbstractNode { public static const MOV : uint = 0x00; public static const ADD : uint = 0x01; public static const SUB : uint = 0x02; public static const MUL : uint = 0x03; public static const DIV : uint = 0x04; public static const RCP : uint = 0x05; public static const MIN : uint = 0x06; public static const MAX : uint = 0x07; public static const FRC : uint = 0x08; public static const SQT : uint = 0x09; public static const RSQ : uint = 0x0a; public static const POW : uint = 0x0b; public static const LOG : uint = 0x0c; public static const EXP : uint = 0x0d; public static const NRM : uint = 0x0e; public static const SIN : uint = 0x0f; public static const COS : uint = 0x10; public static const CRS : uint = 0x11; public static const DP3 : uint = 0x12; public static const DP4 : uint = 0x13; public static const ABS : uint = 0x14; public static const NEG : uint = 0x15; public static const SAT : uint = 0x16; public static const M33 : uint = 0x17; public static const M44 : uint = 0x18; public static const M34 : uint = 0x19; public static const KIL : uint = 0x27; public static const TEX : uint = 0x28; public static const SGE : uint = 0x29; public static const SLT : uint = 0x2a; public static const SEQ : uint = 0x2c; public static const SNE : uint = 0x2d; public static const MUL_MAT33 : uint = 0x100; public static const MUL_MAT44 : uint = 0x101; public static const NAME : Dictionary = new Dictionary(); { NAME[MOV] = 'mov'; NAME[ADD] = 'add'; NAME[SUB] = 'sub'; NAME[MUL] = 'mul'; NAME[DIV] = 'div'; NAME[RCP] = 'rcp'; NAME[MIN] = 'min'; NAME[MAX] = 'max'; NAME[FRC] = 'frc'; NAME[SQT] = 'sqt'; NAME[RSQ] = 'rsq'; NAME[POW] = 'pow'; NAME[LOG] = 'log'; NAME[EXP] = 'exp'; NAME[NRM] = 'nrm'; NAME[SIN] = 'sin'; NAME[COS] = 'cos'; NAME[CRS] = 'crs'; NAME[DP3] = 'dp3'; NAME[DP4] = 'dp4'; NAME[ABS] = 'abs'; NAME[NEG] = 'neg'; NAME[SAT] = 'sat'; NAME[M33] = 'm33'; NAME[M44] = 'm44'; NAME[M34] = 'm34'; NAME[TEX] = 'tex'; NAME[KIL] = 'kil'; NAME[SGE] = 'sge'; NAME[SLT] = 'slt'; NAME[SEQ] = 'seq'; NAME[SNE] = 'sne'; NAME[MUL_MAT33] = 'mulMat33'; NAME[MUL_MAT44] = 'mulMat44'; } private static const FLAGS : Dictionary = new Dictionary(); { FLAGS[MOV] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[ADD] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE | InstructionFlag.LINEAR; FLAGS[SUB] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.LINEAR; FLAGS[MUL] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE | InstructionFlag.LINEAR; FLAGS[DIV] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.LINEAR; FLAGS[RCP] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[MIN] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[MAX] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[FRC] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[SQT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[RSQ] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[POW] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[LOG] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[EXP] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[NRM] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SINGLE; FLAGS[SIN] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[COS] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[CRS] = InstructionFlag.AVAILABLE_ALL; FLAGS[DP3] = InstructionFlag.AVAILABLE_ALL; FLAGS[DP4] = InstructionFlag.AVAILABLE_ALL; FLAGS[ABS] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[NEG] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE | InstructionFlag.LINEAR; FLAGS[SAT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.SINGLE; FLAGS[M33] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[M44] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[M34] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.SPECIAL_MATRIX | InstructionFlag.LINEAR; FLAGS[KIL] = InstructionFlag.AVAILABLE_FS | InstructionFlag.SINGLE; FLAGS[TEX] = InstructionFlag.AVAILABLE_FS; FLAGS[SGE] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[SLT] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE; FLAGS[SEQ] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[SNE] = InstructionFlag.AVAILABLE_ALL | InstructionFlag.COMPONENT_WISE | InstructionFlag.COMMUTATIVE; FLAGS[MUL_MAT33] = InstructionFlag.AVAILABLE_CPU | InstructionFlag.ASSOCIATIVE; FLAGS[MUL_MAT44] = InstructionFlag.AVAILABLE_CPU | InstructionFlag.ASSOCIATIVE; } private var _id : uint; public function get id() : uint { return _id; } public function get name() : String { return NAME[_id]; } public function get argument1() : AbstractNode { return getArgumentAt(0); } public function get argument2() : AbstractNode { return getArgumentAt(1); } public function get component1() : uint { return getComponentAt(0); } public function get component2() : uint { return getComponentAt(1); } public function set argument1(v : AbstractNode) : void { setArgumentAt(0, v); } public function set argument2(v : AbstractNode) : void { setArgumentAt(1, v); } public function set component1(v : uint) : void { setComponentAt(0, v); } public function set component2(v : uint) : void { setComponentAt(1, v); } public function get isAssociative() : Boolean { return (FLAGS[_id] & InstructionFlag.ASSOCIATIVE) != 0; } public function get isComponentWise() : Boolean { return (FLAGS[_id] & InstructionFlag.COMPONENT_WISE) != 0; } public function get isSingle() : Boolean { return (FLAGS[_id] & InstructionFlag.SINGLE) != 0; } public function get isLinear() : Boolean { return (FLAGS[_id] & InstructionFlag.LINEAR) != 0; } public function isCommutative() : Boolean { return (FLAGS[_id] & InstructionFlag.COMMUTATIVE) != 0; } public function Instruction(id : uint, argument1 : AbstractNode, argument2 : AbstractNode = null) { _id = id; var component1 : uint = id == MUL_MAT33 || id == MUL_MAT44 ? Components.createContinuous(0, 0, 4, 4) : Components.createContinuous(0, 0, argument1.size, argument1.size) var arguments : Vector.<AbstractNode> = new <AbstractNode>[argument1]; var components : Vector.<uint> = new <uint>[component1]; if (!isSingle) { var component2 : uint; if ((FLAGS[id] & InstructionFlag.SPECIAL_MATRIX) != 0) component2 = Components.createContinuous(0, 0, 4, 4); else if (id != TEX && id != MUL_MAT33 && id != MUL_MAT44) component2 = Components.createContinuous(0, 0, argument2.size, argument2.size); arguments.push(argument2); components.push(component2); } arguments.fixed = components.fixed = true; super(arguments, components); } override protected function computeHash() : uint { // commutative operations invert the arguments when computing the hash if arg1.crc > arg2.crc // that way, mul(a, b).hash == mul(b, a).hash var hashLeft : String = id.toFixed(16) + '_' + argument1.hash.toString(16) + '_' + component1.toString(16); if ((FLAGS[_id] & InstructionFlag.SINGLE) != 0) return CRC32.computeForString(hashLeft); else { var hashRight : String = argument2.hash.toString(16) + '_' + component2.toString(16); if ((FLAGS[_id] & InstructionFlag.COMMUTATIVE) != 0 && argument1.hash > argument2.hash) return CRC32.computeForString(hashRight + hashLeft); else return CRC32.computeForString(hashLeft + hashRight); } } override protected function computeSize() : uint { switch (_id) { case DP3: case DP4: return 1; case M33: case M34: case NRM: case CRS: return 3; case TEX: case M44: return 4; default: var nodeSize : uint; nodeSize = Components.getMaxWriteOffset(component1) - Components.getMinWriteOffset(component1) + 1; if (nodeSize > 4) throw new Error(); if (!isSingle) nodeSize = Math.max(nodeSize, Components.getMaxWriteOffset(component2) - Components.getMinWriteOffset(component2) + 1 ); if (nodeSize < 1) throw new Error(); if (nodeSize > 4) throw new Error(); return nodeSize; } } override public function toString() : String { return name; } override public function clone() : AbstractNode { var clone : Instruction; if (isSingle) { clone = new Instruction(_id, argument1); clone.component1 = component1; } else { clone = new Instruction(_id, argument1, argument2); clone.component1 = component1; clone.component2 = component2; } return clone; } } }
fix Instruction.computeHash() to prefix the string hash with the instruction id and avoid instructions with the same arguments being mixed up
fix Instruction.computeHash() to prefix the string hash with the instruction id and avoid instructions with the same arguments being mixed up
ActionScript
mit
aerys/minko-as3
67a10a51840e612a962b0520755375fd6558865c
plugins/wvPlugin/src/wvPluginCode.as
plugins/wvPlugin/src/wvPluginCode.as
package { import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.LayoutProxy; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.plugin.IPlugin; import com.kaltura.kdpfl.plugin.KPluginEvent; import com.kaltura.kdpfl.plugin.WVPluginInfo; import flash.display.Sprite; import org.osmf.events.MediaFactoryEvent; import org.osmf.media.DefaultMediaFactory; import org.osmf.media.PluginInfoResource; import org.puremvc.as3.interfaces.IFacade; public class wvPluginCode extends Sprite implements IPlugin { protected var _flashvars : Object; protected var _localMediaFactory : DefaultMediaFactory; public function wvPluginCode() { trace('Widevine plugin v2'); super(); } public function initializePlugin(facade:IFacade):void { _flashvars = (facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars; _localMediaFactory = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.mediaFactory; var wvpinfo: WVPluginInfo = new WVPluginInfo(); var lp:LayoutProxy = (facade.retrieveProxy(LayoutProxy.NAME) as LayoutProxy); for each( var i:Object in lp.components) { if(i.hasOwnProperty("className") && i.className == "KMediaPlayer" ) { trace(i.ui.width,i.ui.height ); WVPluginInfo.mediaWidth = i.ui.width; WVPluginInfo.mediaHeight = i.ui.height; break; } } //overriding media width/height if flashvar available /* if (_flashvars.widevinemediawidth) WVPluginInfo.mediaWidth = Number(_flashvars.widevinemediawidth); if (_flashvars.widevinemediaheight) WVPluginInfo.mediaHeight = Number(_flashvars.widevinemediaheight);*/ _localMediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD, onOSMFPluginLoaded); _localMediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD_ERROR, onOSMFPluginLoadError); _localMediaFactory.loadPlugin(new PluginInfoResource(wvpinfo) ); var wvm:WvMediator = new WvMediator(wvpinfo); facade.registerMediator(wvm); } /** * Listener for the LOAD_COMPLETE event. * @param e - MediaFactoryEvent * */ protected function onOSMFPluginLoaded (e : MediaFactoryEvent) : void { dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_COMPLETE) ); } /** * Listener for the LOAD_ERROR event. * @param e - MediaFactoryEvent * */ protected function onOSMFPluginLoadError (e : MediaFactoryEvent) : void { dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_FAILED) ); } public function setSkin(styleName:String, setSkinSize:Boolean=false):void { } } }
package { import com.kaltura.kdpfl.model.ConfigProxy; import com.kaltura.kdpfl.model.LayoutProxy; import com.kaltura.kdpfl.model.MediaProxy; import com.kaltura.kdpfl.plugin.IPlugin; import com.kaltura.kdpfl.plugin.KPluginEvent; import com.kaltura.kdpfl.plugin.WVPluginInfo; import flash.display.Sprite; import org.osmf.events.MediaFactoryEvent; import org.osmf.media.DefaultMediaFactory; import org.osmf.media.PluginInfoResource; import org.puremvc.as3.interfaces.IFacade; public dynamic class wvPluginCode extends Sprite implements IPlugin { protected var _flashvars : Object; protected var _localMediaFactory : DefaultMediaFactory; public function wvPluginCode() { trace('Widevine plugin v2'); super(); } public function initializePlugin(facade:IFacade):void { _flashvars = (facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars; _localMediaFactory = (facade.retrieveProxy(MediaProxy.NAME) as MediaProxy).vo.mediaFactory; var wvpinfo: WVPluginInfo = new WVPluginInfo(); var lp:LayoutProxy = (facade.retrieveProxy(LayoutProxy.NAME) as LayoutProxy); for each( var i:Object in lp.components) { if(i.hasOwnProperty("className") && i.className == "KMediaPlayer" ) { trace(i.ui.width,i.ui.height ); WVPluginInfo.mediaWidth = i.ui.width; WVPluginInfo.mediaHeight = i.ui.height; break; } } //overriding media width/height if flashvar available /* if (_flashvars.widevinemediawidth) WVPluginInfo.mediaWidth = Number(_flashvars.widevinemediawidth); if (_flashvars.widevinemediaheight) WVPluginInfo.mediaHeight = Number(_flashvars.widevinemediaheight);*/ _localMediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD, onOSMFPluginLoaded); _localMediaFactory.addEventListener(MediaFactoryEvent.PLUGIN_LOAD_ERROR, onOSMFPluginLoadError); _localMediaFactory.loadPlugin(new PluginInfoResource(wvpinfo) ); var wvm:WvMediator = new WvMediator(wvpinfo); facade.registerMediator(wvm); } /** * Listener for the LOAD_COMPLETE event. * @param e - MediaFactoryEvent * */ protected function onOSMFPluginLoaded (e : MediaFactoryEvent) : void { dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_COMPLETE) ); } /** * Listener for the LOAD_ERROR event. * @param e - MediaFactoryEvent * */ protected function onOSMFPluginLoadError (e : MediaFactoryEvent) : void { dispatchEvent( new KPluginEvent (KPluginEvent.KPLUGIN_INIT_FAILED) ); } public function setSkin(styleName:String, setSkinSize:Boolean=false):void { } } }
make widevine plugin a dynamic class: this way we can access properties dynamically via kdp.evaluate
make widevine plugin a dynamic class: this way we can access properties dynamically via kdp.evaluate
ActionScript
agpl-3.0
kaltura/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,shvyrev/kdp
913c4da7fe237f88033fd53066f0e57e0046d16f
src/main/as/flump/export/Exporter.as
src/main/as/flump/export/Exporter.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.desktop.NativeApplication; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.net.SharedObject; import com.adobe.crypto.MD5; import deng.fzip.FZip; import deng.fzip.FZipFile; import executor.Executor; import executor.Future; import flump.bytesToXML; import flump.export.Ternary; import flump.xfl.ParseError; import flump.xfl.XflAnimation; import flump.xfl.XflLibrary; import spark.components.DataGrid; import spark.components.List; import spark.components.Window; import spark.events.GridSelectionEvent; import starling.core.Starling; import com.threerings.util.DelayUtil; import com.threerings.util.F; import com.threerings.util.Log; import com.threerings.util.StringUtil; public class Exporter { public static const NA :NativeApplication = NativeApplication.nativeApplication; protected static const IMPORT_ROOT :String = "IMPORT_ROOT"; public function Exporter (win :ExporterWindow) { _win = win; _errors = _win.errors; _libraries = _win.libraries; _libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _libraries.selectedIndices); _win.export.enabled = _libraries.selectedIndices.length > 0; _win.preview.enabled = _libraries.selectedIndices.length == 1; }); _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _libraries.selectedItems) { exportFlashDocument(status); } }); _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { var previewWindow :PreviewWindow = new PreviewWindow(); previewWindow.started = F.callback(DelayUtil.delayFrame, function (..._) :void { var preview :Preview = Preview(Starling.current.stage.getChildAt(0)); var lib :XflLibrary = _libraries.selectedItem.lib; // TODO - animation selector in Preview }); previewWindow.open(); }); _importChooser = new DirChooser(_settings, "IMPORT_ROOT", _win.importRoot, _win.browseImport); _importChooser.changed.add(setImport); setImport(new File(_importChooser.dir)); _exportChooser = new DirChooser(_settings, "EXPORT_ROOT", _win.exportRoot, _win.browseExport); } protected function setImport (root :File) :void { _libraries.dataProvider.removeAll(); _rootLen = root.nativePath.length + 1; if (_docFinder != null) _docFinder.shutdownNow(); _docFinder = new Executor(2); findFlashDocuments(root, _docFinder); } protected function findFlashDocuments (base :File, exec :Executor) :void { Files.list(base, exec).succeeded.add(function (files :Array) :void { if (exec.isShutdown) return; for each (var file :File in files) { if (StringUtil.endsWith(file.nativePath, ".xfl")) { addFlashDocument(file.parent); return; } } for each (file in files) { if (file.isDirectory) findFlashDocuments(file, exec); else if (StringUtil.endsWith(file.nativePath, ".fla")) addFlashDocument(file); } }); } protected function addFlashDocument (file :File) :void { const status :DocStatus = new DocStatus(file, _rootLen, Ternary.UNKOWN, Ternary.UNKOWN, null); _libraries.dataProvider.addItem(status); loadFlashDocument(status); } protected function exportFlashDocument (status :DocStatus) :void { const exportDir :File = new File(_exportChooser.dir); PngPublisher.dumpTextures(exportDir, status.lib); BetwixtPublisher.export(status.lib, status.file, exportDir); status.updateModified(Ternary.FALSE); } protected function loadFlashDocument (status :DocStatus) :void { if (StringUtil.endsWith(status.file.nativePath, ".xfl")) status.file = status.file.parent; if (status.file.isDirectory) { const name :String = status.file.nativePath.substring(_rootLen); const load :Future = new XflLoader().load(name, status.file); load.succeeded.add(function (lib :XflLibrary) :void { const exportDir :File = new File(_exportChooser.dir); const isMod :Boolean = BetwixtPublisher.modified(lib, exportDir); status.lib = lib; status.updateModified(Ternary.of(isMod)); for each (var err :ParseError in lib.getErrors()) { _errors.dataProvider.addItem(err); trace(err); } status.updateValid(Ternary.of(lib.valid)); if (status.path == "shapes") { try { exportFlashDocument(status); } catch (e :Error) { log.warning("Blew up", e); } finally { NA.exit(0); } } }); } else loadFla(status.file); } protected function loadFla (file :File) :void { log.info("Loading fla", "path", file.nativePath); Files.load(file).succeeded.add(function (file :File) :void { const zip :FZip = new FZip(); zip.loadBytes(file.data); const files :Array = []; for (var ii :int = 0; ii < zip.getFileCount(); ii++) files.push(zip.getFileAt(ii)); const xmls :Array = F.filter(files, function (fz :FZipFile) :Boolean { return StringUtil.endsWith(fz.filename, ".xml"); }); const anims :Array = F.filter(xmls, function (fz :FZipFile) :Boolean { return StringUtil.startsWith(fz.filename, "LIBRARY/Animations/"); }); const textures :Array = F.filter(xmls, function (fz :FZipFile) :Boolean { return StringUtil.startsWith(fz.filename, "LIBRARY/Textures/"); }); function toFn (fz :FZipFile) :String { return fz.filename }; log.info("Loaded", "bytes", file.data.length, "anims", F.map(anims, toFn), "textures", F.map(textures, toFn)); for each (var fz :FZipFile in anims) { new XflAnimation(fz.filename, bytesToXML(fz.content), MD5.hashBytes(fz.content)); } NA.exit(0); }); } protected var _rootLen :int; protected var _docFinder :Executor; protected var _win :ExporterWindow; protected var _libraries :DataGrid; protected var _errors :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter"); private static const log :Log = Log.getLog(Exporter); } } import flash.events.EventDispatcher; import flash.filesystem.File; import flump.export.Ternary; import flump.xfl.XflLibrary; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; class DocStatus extends EventDispatcher implements IPropertyChangeNotifier { public var path :String; public var modified :String; public var valid :String = QUESTION; public var file :File; public var lib :XflLibrary; public function DocStatus (file :File, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) { this.file = file; this.lib = lib; path = file.nativePath.substring(rootLen); _uid = path; updateModified(modified); updateValid(valid); } public function updateValid (newValid :Ternary) :void { changeField("valid", function (..._) :void { if (newValid == Ternary.TRUE) valid = CHECK; else if (newValid == Ternary.FALSE) valid = FROWN; else valid = QUESTION; }); } public function updateModified (newModified :Ternary) :void { changeField("modified", function (..._) :void { if (newModified == Ternary.TRUE) modified = CHECK; else if (newModified == Ternary.FALSE) modified = " "; else modified = QUESTION; }); } protected function changeField(fieldName :String, modifier :Function) :void { const oldValue :Object = this[fieldName]; modifier(); const newValue :Object = this[fieldName]; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue)); } public function get uid () :String { return _uid; } public function set uid (uid :String) :void { _uid = uid; } protected var _uid :String; protected static const QUESTION :String = "?"; protected static const FROWN :String = "☹"; protected static const CHECK :String = "✓"; }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.desktop.NativeApplication; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.net.SharedObject; import com.adobe.crypto.MD5; import deng.fzip.FZip; import deng.fzip.FZipFile; import executor.Executor; import executor.Future; import flump.bytesToXML; import flump.export.Ternary; import flump.xfl.ParseError; import flump.xfl.XflAnimation; import flump.xfl.XflLibrary; import spark.components.DataGrid; import spark.components.List; import spark.components.Window; import spark.events.GridSelectionEvent; import starling.core.Starling; import com.threerings.util.DelayUtil; import com.threerings.util.F; import com.threerings.util.Log; import com.threerings.util.StringUtil; public class Exporter { public static const NA :NativeApplication = NativeApplication.nativeApplication; protected static const IMPORT_ROOT :String = "IMPORT_ROOT"; public function Exporter (win :ExporterWindow) { _win = win; _errors = _win.errors; _libraries = _win.libraries; _libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _libraries.selectedIndices); _win.export.enabled = _libraries.selectedIndices.length > 0; _win.preview.enabled = _libraries.selectedIndices.length == 1; }); _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _libraries.selectedItems) { exportFlashDocument(status); } }); _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { var previewWindow :PreviewWindow = new PreviewWindow(); previewWindow.started = F.callback(DelayUtil.delayFrame, function (..._) :void { var preview :Preview = Preview(Starling.current.stage.getChildAt(0)); var lib :XflLibrary = _libraries.selectedItem.lib; // TODO - animation selector in Preview }); previewWindow.open(); }); _importChooser = new DirChooser(_settings, "IMPORT_ROOT", _win.importRoot, _win.browseImport); _importChooser.changed.add(setImport); setImport(new File(_importChooser.dir)); _exportChooser = new DirChooser(_settings, "EXPORT_ROOT", _win.exportRoot, _win.browseExport); } protected function setImport (root :File) :void { _libraries.dataProvider.removeAll(); _rootLen = root.nativePath.length + 1; if (_docFinder != null) _docFinder.shutdownNow(); _docFinder = new Executor(2); findFlashDocuments(root, _docFinder); } protected function findFlashDocuments (base :File, exec :Executor) :void { Files.list(base, exec).succeeded.add(function (files :Array) :void { if (exec.isShutdown) return; for each (var file :File in files) { if (StringUtil.endsWith(file.nativePath, ".xfl")) { addFlashDocument(file.parent); return; } } for each (file in files) { if (file.isDirectory) findFlashDocuments(file, exec); else if (StringUtil.endsWith(file.nativePath, ".fla")) addFlashDocument(file); } }); } protected function addFlashDocument (file :File) :void { const status :DocStatus = new DocStatus(file, _rootLen, Ternary.UNKOWN, Ternary.UNKOWN, null); _libraries.dataProvider.addItem(status); loadFlashDocument(status); } protected function exportFlashDocument (status :DocStatus) :void { const exportDir :File = new File(_exportChooser.dir); BetwixtPublisher.publish(status.lib, status.file, exportDir); status.updateModified(Ternary.FALSE); } protected function loadFlashDocument (status :DocStatus) :void { if (StringUtil.endsWith(status.file.nativePath, ".xfl")) status.file = status.file.parent; if (status.file.isDirectory) { const name :String = status.file.nativePath.substring(_rootLen); const load :Future = new XflLoader().load(name, status.file); load.succeeded.add(function (lib :XflLibrary) :void { const exportDir :File = new File(_exportChooser.dir); const isMod :Boolean = BetwixtPublisher.modified(lib, exportDir); status.lib = lib; status.updateModified(Ternary.of(isMod)); for each (var err :ParseError in lib.getErrors()) { _errors.dataProvider.addItem(err); trace(err); } status.updateValid(Ternary.of(lib.valid)); if (status.path == "shapes") { try { exportFlashDocument(status); } catch (e :Error) { log.warning("Blew up", e); } finally { NA.exit(0); } } }); } else loadFla(status.file); } protected function loadFla (file :File) :void { log.info("Loading fla", "path", file.nativePath); Files.load(file).succeeded.add(function (file :File) :void { const zip :FZip = new FZip(); zip.loadBytes(file.data); const files :Array = []; for (var ii :int = 0; ii < zip.getFileCount(); ii++) files.push(zip.getFileAt(ii)); const xmls :Array = F.filter(files, function (fz :FZipFile) :Boolean { return StringUtil.endsWith(fz.filename, ".xml"); }); const anims :Array = F.filter(xmls, function (fz :FZipFile) :Boolean { return StringUtil.startsWith(fz.filename, "LIBRARY/Animations/"); }); const textures :Array = F.filter(xmls, function (fz :FZipFile) :Boolean { return StringUtil.startsWith(fz.filename, "LIBRARY/Textures/"); }); function toFn (fz :FZipFile) :String { return fz.filename }; log.info("Loaded", "bytes", file.data.length, "anims", F.map(anims, toFn), "textures", F.map(textures, toFn)); for each (var fz :FZipFile in anims) { new XflAnimation(fz.filename, bytesToXML(fz.content), MD5.hashBytes(fz.content)); } NA.exit(0); }); } protected var _rootLen :int; protected var _docFinder :Executor; protected var _win :ExporterWindow; protected var _libraries :DataGrid; protected var _errors :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter"); private static const log :Log = Log.getLog(Exporter); } } import flash.events.EventDispatcher; import flash.filesystem.File; import flump.export.Ternary; import flump.xfl.XflLibrary; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; class DocStatus extends EventDispatcher implements IPropertyChangeNotifier { public var path :String; public var modified :String; public var valid :String = QUESTION; public var file :File; public var lib :XflLibrary; public function DocStatus (file :File, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) { this.file = file; this.lib = lib; path = file.nativePath.substring(rootLen); _uid = path; updateModified(modified); updateValid(valid); } public function updateValid (newValid :Ternary) :void { changeField("valid", function (..._) :void { if (newValid == Ternary.TRUE) valid = CHECK; else if (newValid == Ternary.FALSE) valid = FROWN; else valid = QUESTION; }); } public function updateModified (newModified :Ternary) :void { changeField("modified", function (..._) :void { if (newModified == Ternary.TRUE) modified = CHECK; else if (newModified == Ternary.FALSE) modified = " "; else modified = QUESTION; }); } protected function changeField(fieldName :String, modifier :Function) :void { const oldValue :Object = this[fieldName]; modifier(); const newValue :Object = this[fieldName]; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue)); } public function get uid () :String { return _uid; } public function set uid (uid :String) :void { _uid = uid; } protected var _uid :String; protected static const QUESTION :String = "?"; protected static const FROWN :String = "☹"; protected static const CHECK :String = "✓"; }
Stop dumping the textures individually
Stop dumping the textures individually
ActionScript
mit
mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,tconkling/flump
9f6bef9addb2325a24ccbb0a69d5bb02c201e72a
src/aerys/minko/type/xpath/XPathEvaluator.as
src/aerys/minko/type/xpath/XPathEvaluator.as
package aerys.minko.type.xpath { import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.binding.DataBindings; import flash.utils.getQualifiedClassName; public final class XPathEvaluator { private var _path : String; private var _selection : Vector.<ISceneNode> = null; private var _modifier : String = null; private var _lexer : XPathLexer = null; public function get selection() : Vector.<ISceneNode> { return _selection; } public function XPathEvaluator(path : String, selection : Vector.<ISceneNode>, modifier : String = null) { _modifier = modifier; initialize(path, selection); } private function initialize(path : String, selection : Vector.<ISceneNode>) : void { _path = path; _lexer = new XPathLexer(_path); // update root var token : String = _lexer.getToken(); _selection = selection.slice(); if (token == "/") { selectRoots(); _lexer.nextToken(token); } // parse while ((token = _lexer.getToken()) != null) { switch (token) { case '//' : _lexer.nextToken(token); selectDescendants(); break ; case '/' : _lexer.nextToken(token); selectChildren(); break ; default : _lexer.nextToken(token); parseNodeType(token); break ; } } } private function selectChildren(typeName : String = null) : void { var selection : Vector.<ISceneNode> = _selection.slice(); if (typeName != null) typeName = typeName.toLowerCase(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node is Group) { var group : Group = node as Group; var numChildren : uint = group.numChildren; for (var i : uint = 0; i < numChildren; ++i) { var child : ISceneNode = group.getChildAt(i); var className : String = getQualifiedClassName(child) var childType : String = className.substr(className.lastIndexOf(':') + 1); if (typeName == null || childType.toLowerCase() == typeName) _selection.push(child); } } } } private function selectRoots() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) if (_selection.indexOf(node.root) < 0) _selection.push(node); } private function selectDescendants() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { _selection.push(node); if (node is Group) (node as Group).getDescendantsByType(ISceneNode, _selection); } } private function selectParents() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node.parent) _selection.push(node.parent); else _selection.push(node); } } private function parseNodeType(nodeType : String) : void { if (nodeType == '.') { // nothing } if (nodeType == '..') selectParents(); else if (nodeType == '*') selectChildren(); else selectChildren(nodeType); // apply predicates var token : String = _lexer.getToken(); while (token == '[') { _lexer.nextToken(token); parsePredicate(); token = _lexer.getToken(); } } private function parsePredicate() : void { var propertyName : String = _lexer.getToken(true); var isBinding : Boolean = propertyName == '@'; if (isBinding) propertyName = _lexer.getToken(true); var index : int = parseInt(propertyName); filterProperty(_lexer, propertyName, _selection); _lexer.checkNextToken(']'); } private function getValueObject(source : Object, chunks : Array) : Object { if (chunks) for each (var chunk : String in chunks) source = source[chunk]; return source; } private function removeFromSelection(index : uint) : void { var numNodes : uint = _selection.length - 1; _selection[index] = _selection[numNodes]; _selection.length = numNodes; } private function filterProperty(lexer : XPathLexer, propertyName : String, selection : Vector.<ISceneNode>) : void { var isBinding : Boolean = propertyName == '@'; var index : int = parseInt(propertyName); if (propertyName == 'hasController') filterOnController(lexer, selection); else if (propertyName == 'hasProperty') filterOnProperty(lexer, selection); else if (propertyName == 'position') filterOnPosition(lexer, selection); else if (propertyName == 'last') filterLast(lexer, selection); else if (propertyName == 'first') filterFirst(lexer, selection); else if (index.toString() == propertyName) { if (index < selection.length) { selection[0] = selection[index]; selection.length = 1; } else selection.length = 0; } else filterOnValue(lexer, selection, propertyName, isBinding); } private function filterOnValue(lexer : XPathLexer, selection : Vector.<ISceneNode>, propertyName : String, isBinding : Boolean = false) : void { var operator : String = lexer.getToken(true); var chunks : Array = [propertyName]; while (operator == '.') { chunks.push(lexer.getToken(true)); operator = lexer.getToken(true); } var value : Object = lexer.getValueToken(); var numNodes : uint = selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = selection[i]; var nodeValue : Object = null; if (isBinding && (node['bindings'] is DataBindings)) nodeValue = (node['bindings'] as DataBindings).getProperty(propertyName); else { try { nodeValue = getValueObject(node, chunks); if (!compare(operator, nodeValue, value)) removeFromSelection(i); } catch (e : Error) { removeFromSelection(i); } } } } private function filterLast(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void { lexer.checkNextToken('('); lexer.checkNextToken(')'); if (selection.length) { selection[0] = selection[uint(selection.length - 1)]; selection.length = 1; } } private function filterFirst(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void { lexer.checkNextToken('('); lexer.checkNextToken(')'); selection.length = 1; } private function filterOnController(lexer : XPathLexer, selection : Vector.<ISceneNode>) : Object { lexer.checkNextToken('('); var controllerName : String = lexer.getToken(true); lexer.checkNextToken(')'); var numNodes : uint = selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = selection[i]; var numControllers : uint = node.numControllers; var keepSceneNode : Boolean = false; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controllerType : String = getQualifiedClassName(node.getController(controllerId)); controllerType = controllerType.substr(controllerType.lastIndexOf(':') + 1); if (controllerType == controllerName) { keepSceneNode = true; break; } } if (!keepSceneNode) removeFromSelection(i); } return null; } private function filterOnPosition(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void { lexer.checkNextToken('('); lexer.checkNextToken(')'); var operator : String = lexer.getToken(true); var value : uint = uint(parseInt(lexer.getToken(true))); switch (operator) { case '>': ++value; case '>=': selection = selection.slice(value); break; case '<': --value; case '<=': selection = selection.slice(0, value); break; case '=': case '==': selection[0] = selection[value]; selection.length = 1; default: throw new Error('Unknown comparison operator \'' + operator + '\''); } } private function filterOnProperty(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void { lexer.checkNextToken('('); var chunks : Array = [lexer.getToken(true)]; var operator : String = lexer.getToken(true); while (operator == '.') { chunks.push(operator); operator = lexer.getToken(true); } if (operator != ')') lexer.throwParseError(')', operator); var numNodes : uint = selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { try { getValueObject(selection[i], chunks); } catch (e : Error) { removeFromSelection(i); } } } private function compare(operator : String, a : Object, b : Object) : Boolean { switch (operator) { case '>' : return a > b; case '>=' : return a >= b; case '<' : return a >= b; case '<=' : return a <= b; case '=' : case '==' : return a == b; case '~=' : var matches : Array = String(a).match(b); return matches && matches.length != 0; default: throw new Error('Unknown comparison operator \'' + operator + '\''); } } } }
package aerys.minko.type.xpath { import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.binding.DataBindings; import flash.utils.getQualifiedClassName; public final class XPathEvaluator { private var _path : String; private var _selection : Vector.<ISceneNode> = null; private var _modifier : String = null; private var _lexer : XPathLexer = null; public function get selection() : Vector.<ISceneNode> { return _selection; } public function XPathEvaluator(path : String, selection : Vector.<ISceneNode>, modifier : String = null) { _modifier = modifier; initialize(path, selection); } private function initialize(path : String, selection : Vector.<ISceneNode>) : void { _path = path; _lexer = new XPathLexer(_path); // update root var token : String = _lexer.getToken(); _selection = selection.slice(); if (token == "/") { selectRoots(); _lexer.nextToken(token); } // parse while ((token = _lexer.getToken()) != null) { switch (token) { case '//' : _lexer.nextToken(token); selectDescendants(); break ; case '/' : _lexer.nextToken(token); selectChildren(); break ; default : _lexer.nextToken(token); parseNodeType(token); break ; } } } private function selectChildren(typeName : String = null) : void { var selection : Vector.<ISceneNode> = _selection.slice(); if (typeName != null) typeName = typeName.toLowerCase(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node is Group) { var group : Group = node as Group; var numChildren : uint = group.numChildren; for (var i : uint = 0; i < numChildren; ++i) { var child : ISceneNode = group.getChildAt(i); var className : String = getQualifiedClassName(child) var childType : String = className.substr(className.lastIndexOf(':') + 1); if (typeName == null || childType.toLowerCase() == typeName) _selection.push(child); } } } } private function selectRoots() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) if (_selection.indexOf(node.root) < 0) _selection.push(node); } private function selectDescendants() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { _selection.push(node); if (node is Group) (node as Group).getDescendantsByType(ISceneNode, _selection); } } private function selectParents() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node.parent) _selection.push(node.parent); else _selection.push(node); } } private function parseNodeType(nodeType : String) : void { if (nodeType == '.') { // nothing } if (nodeType == '..') selectParents(); else if (nodeType == '*') selectChildren(); else selectChildren(nodeType); // apply predicates var token : String = _lexer.getToken(); while (token == '[') { _lexer.nextToken(token); parsePredicate(); token = _lexer.getToken(); } } private function parsePredicate() : void { var propertyName : String = _lexer.getToken(true); var isBinding : Boolean = propertyName == '@'; if (isBinding) propertyName = _lexer.getToken(true); var index : int = parseInt(propertyName); filterProperty(_lexer, propertyName, _selection); _lexer.checkNextToken(']'); } private function getValueObject(source : Object, chunks : Array) : Object { if (chunks) for each (var chunk : String in chunks) source = source[chunk]; return source; } private function removeFromSelection(index : uint) : void { var numNodes : uint = _selection.length - 1; _selection[index] = _selection[numNodes]; _selection.length = numNodes; } private function filterProperty(lexer : XPathLexer, propertyName : String, selection : Vector.<ISceneNode>) : void { var isBinding : Boolean = propertyName == '@'; var index : int = parseInt(propertyName); if (propertyName == 'hasController') filterOnController(lexer, selection); else if (propertyName == 'hasProperty') filterOnProperty(lexer, selection); else if (propertyName == 'position') filterOnPosition(lexer, selection); else if (propertyName == 'last') filterLast(lexer, selection); else if (propertyName == 'first') filterFirst(lexer, selection); else if (index.toString() == propertyName) { if (index < selection.length) { selection[0] = selection[index]; selection.length = 1; } else selection.length = 0; } else filterOnValue(lexer, selection, propertyName, isBinding); } private function filterOnValue(lexer : XPathLexer, selection : Vector.<ISceneNode>, propertyName : String, isBinding : Boolean = false) : void { var operator : String = lexer.getToken(true); var chunks : Array = [propertyName]; while (operator == '.') { chunks.push(lexer.getToken(true)); operator = lexer.getToken(true); } var value : Object = lexer.getValueToken(); var numNodes : uint = selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = selection[i]; var nodeValue : Object = null; if (isBinding && (node['bindings'] is DataBindings)) nodeValue = (node['bindings'] as DataBindings).getProperty(propertyName); else { try { nodeValue = getValueObject(node, chunks); if (!compare(operator, nodeValue, value)) removeFromSelection(i); } catch (e : Error) { removeFromSelection(i); } } } } private function filterLast(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void { lexer.checkNextToken('('); lexer.checkNextToken(')'); if (selection.length) { selection[0] = selection[uint(selection.length - 1)]; selection.length = 1; } } private function filterFirst(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void { lexer.checkNextToken('('); lexer.checkNextToken(')'); selection.length = 1; } private function filterOnController(lexer : XPathLexer, selection : Vector.<ISceneNode>) : Object { lexer.checkNextToken('('); var controllerName : String = lexer.getToken(true); lexer.checkNextToken(')'); var numNodes : uint = selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = selection[i]; var numControllers : uint = node.numControllers; var keepSceneNode : Boolean = false; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controllerType : String = getQualifiedClassName(node.getController(controllerId)); controllerType = controllerType.substr(controllerType.lastIndexOf(':') + 1); if (controllerType == controllerName) { keepSceneNode = true; break; } } if (!keepSceneNode) removeFromSelection(i); } return null; } private function filterOnPosition(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void { lexer.checkNextToken('('); lexer.checkNextToken(')'); var operator : String = lexer.getToken(true); var value : uint = uint(parseInt(lexer.getToken(true))); switch (operator) { case '>': ++value; case '>=': selection = selection.slice(value); break; case '<': --value; case '<=': selection = selection.slice(0, value); break; case '=': case '==': selection[0] = selection[value]; selection.length = 1; default: throw new Error('Unknown comparison operator \'' + operator + '\''); } } private function filterOnProperty(lexer : XPathLexer, selection : Vector.<ISceneNode>) : void { lexer.checkNextToken('('); var chunks : Array = [lexer.getToken(true)]; var operator : String = lexer.getToken(true); while (operator == '.') { //chunks.push(operator); chunks.push(lexer.getToken(true)); operator = lexer.getToken(true); } if (operator != ')') lexer.throwParseError(')', operator); var numNodes : uint = selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { try { if (getValueObject(selection[i], chunks) == null) removeFromSelection(i); } catch (e : Error) { removeFromSelection(i); } } } private function compare(operator : String, a : Object, b : Object) : Boolean { switch (operator) { case '>' : return a > b; case '>=' : return a >= b; case '<' : return a >= b; case '<=' : return a <= b; case '=' : case '==' : return a == b; case '~=' : var matches : Array = String(a).match(b); return matches && matches.length != 0; default: throw new Error('Unknown comparison operator \'' + operator + '\''); } } } }
Fix xpath for hasProperty command
Fix xpath for hasProperty command
ActionScript
mit
aerys/minko-as3
55092ca3356334544b95c70a144abac5413540fb
src/com/axis/httpclient/HTTPClient.as
src/com/axis/httpclient/HTTPClient.as
package com.axis.httpclient { import com.axis.ClientEvent; import com.axis.NetStreamClient; import com.axis.ErrorManager; import com.axis.IClient; import com.axis.Logger; import flash.utils.*; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.NetStatusEvent; import flash.media.Video; import flash.net.NetConnection; import flash.net.NetStream; public class HTTPClient extends NetStreamClient implements IClient { private var urlParsed:Object; private var nc:NetConnection; private static const FORCED_FPS:Number = 20; private static const UPDATE_VIRT_BUFFER_INTERVAL:Number = 1000 / FORCED_FPS; private var updateLoop:uint = 0; private var virtPause:Boolean = false; private var userPause:Boolean = false; private var frameByFrame:Boolean = false; private var virtBuffer:Number = 0; private var streamBuffer:Number = 0; public function HTTPClient(urlParsed:Object) { this.urlParsed = urlParsed; } public function start(options:Object):Boolean { Logger.log('HTTPClient: playing:', urlParsed.full); this.frameByFrame = Player.config.frameByFrame; nc = new NetConnection(); nc.connect(null); nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus); this.ns = new NetStream(nc); this.setupNetStream(); this.ns.play(urlParsed.full); this.ns.addEventListener(NetStatusEvent.NET_STATUS, this.onNetStreamStatus); this.updateLoop = setInterval(this.updateVirtualBuffer, UPDATE_VIRT_BUFFER_INTERVAL); return true; } public function stop():Boolean { clearInterval(this.updateLoop); this.ns.dispose(); this.nc.close(); this.currentState = 'stopped'; dispatchEvent(new ClientEvent(ClientEvent.STOPPED)); return true; } public function seek(position:Number):Boolean { this.ns.seek(position); return true; } public function pause():Boolean { if (this.currentState !== 'playing') { ErrorManager.dispatchError(800); return false; } this.userPause = true; this.ns.pause(); if (this.virtPause) { dispatchEvent(new ClientEvent(ClientEvent.PAUSED, { 'reason': 'user' })); } return true; } public function resume():Boolean { if (this.currentState !== 'paused') { ErrorManager.dispatchError(801); return false; } this.userPause = false; if (!this.virtPause) { this.ns.resume(); } else { this.currentState = 'playing'; dispatchEvent(new ClientEvent(ClientEvent.START_PLAY)); } return true; } public function setFrameByFrame(frameByFrame:Boolean):Boolean { this.frameByFrame = frameByFrame; return true; } override public function bufferedTime():Number { var c:Number = this.getCurrentTime(); return c >= 0 ? Math.max(this.virtBuffer - c, 0) : c; } public function playFrames(timestamp:Number):void { if (this.virtBuffer < timestamp) { this.virtBuffer = timestamp; } } public function setBuffer(seconds:Number):Boolean { this.ns.bufferTime = seconds; if (!this.userPause && !this.virtPause) { this.ns.pause(); this.ns.resume(); } return true; } private function updateVirtualBuffer():void { if (this.currentState == 'stopped') { return; } if (this.frameByFrame) { var buffer:Number = this.getCurrentTime() + super.bufferedTime(); var step:Number = 1000 / FORCED_FPS; while (this.streamBuffer < buffer) { this.streamBuffer = Math.min(this.streamBuffer + step, buffer) dispatchEvent(new ClientEvent(ClientEvent.FRAME, this.streamBuffer)); } if (!this.virtPause && this.virtBuffer <= this.getCurrentTime() && !streamEnded) { Logger.log('HTTPClient: pause caused by virtual buffer ran out', { currentTime: this.getCurrentTime(), virtualBuffer: this.virtBuffer, realBuffer: super.bufferedTime() }); this.virtPause = true; // Prevent NetStreamClient from triggering paused event this.currentState = 'paused'; this.ns.pause(); } else if (this.virtPause && this.virtBuffer - this.getCurrentTime() >= this.ns.bufferTime * 1000) { this.virtPause = false; if (!this.userPause) { this.ns.resume(); } } } else { this.virtBuffer = this.getCurrentTime() + super.bufferedTime(); } } private function onNetStreamStatus(event:NetStatusEvent):void { if ('NetStream.Play.Stop' === event.info.code) { clearInterval(this.updateLoop); } } private function onConnectionStatus(event:NetStatusEvent):void { Logger.log('HTTPClient: connection status:', event.info.code); if ('NetConnection.Connect.Closed' === event.info.code && this.currentState !== 'stopped') { clearInterval(this.updateLoop); this.currentState = 'stopped'; dispatchEvent(new ClientEvent(ClientEvent.STOPPED)); this.ns.dispose(); } } } }
package com.axis.httpclient { import com.axis.ClientEvent; import com.axis.NetStreamClient; import com.axis.ErrorManager; import com.axis.IClient; import com.axis.Logger; import flash.utils.*; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.NetStatusEvent; import flash.media.Video; import flash.net.NetConnection; import flash.net.NetStream; public class HTTPClient extends NetStreamClient implements IClient { private var urlParsed:Object; private var nc:NetConnection; private static const FORCED_FPS:Number = 30; private static const UPDATE_VIRT_BUFFER_INTERVAL:Number = 1000 / FORCED_FPS; private var updateLoop:uint = 0; private var virtPause:Boolean = false; private var userPause:Boolean = false; private var frameByFrame:Boolean = false; private var virtBuffer:Number = 0; private var streamBuffer:Number = 0; public function HTTPClient(urlParsed:Object) { this.urlParsed = urlParsed; } public function start(options:Object):Boolean { Logger.log('HTTPClient: playing:', urlParsed.full); this.frameByFrame = Player.config.frameByFrame; nc = new NetConnection(); nc.connect(null); nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus); this.ns = new NetStream(nc); this.setupNetStream(); this.ns.play(urlParsed.full); this.ns.addEventListener(NetStatusEvent.NET_STATUS, this.onNetStreamStatus); this.updateLoop = setInterval(this.updateVirtualBuffer, UPDATE_VIRT_BUFFER_INTERVAL); return true; } public function stop():Boolean { clearInterval(this.updateLoop); this.ns.dispose(); this.nc.close(); this.currentState = 'stopped'; dispatchEvent(new ClientEvent(ClientEvent.STOPPED)); return true; } public function seek(position:Number):Boolean { this.ns.seek(position); return true; } public function pause():Boolean { if (this.currentState !== 'playing') { ErrorManager.dispatchError(800); return false; } this.userPause = true; this.ns.pause(); if (this.virtPause) { dispatchEvent(new ClientEvent(ClientEvent.PAUSED, { 'reason': 'user' })); } return true; } public function resume():Boolean { if (this.currentState !== 'paused') { ErrorManager.dispatchError(801); return false; } this.userPause = false; if (!this.virtPause) { this.ns.resume(); } else { this.currentState = 'playing'; dispatchEvent(new ClientEvent(ClientEvent.START_PLAY)); } return true; } public function setFrameByFrame(frameByFrame:Boolean):Boolean { this.frameByFrame = frameByFrame; return true; } override public function bufferedTime():Number { var c:Number = this.getCurrentTime(); return c >= 0 ? Math.max(this.virtBuffer - c, 0) : c; } public function playFrames(timestamp:Number):void { if (this.virtBuffer < timestamp) { this.virtBuffer = timestamp; } } public function setBuffer(seconds:Number):Boolean { this.ns.bufferTime = seconds; if (!this.userPause && !this.virtPause) { this.ns.pause(); this.ns.resume(); } return true; } private function updateVirtualBuffer():void { if (this.currentState == 'stopped') { return; } if (this.frameByFrame) { var buffer:Number = this.getCurrentTime() + super.bufferedTime(); var step:Number = 1000 / FORCED_FPS; while (this.streamBuffer < buffer) { this.streamBuffer = Math.min(this.streamBuffer + step, buffer) dispatchEvent(new ClientEvent(ClientEvent.FRAME, this.streamBuffer)); } if (!this.virtPause && this.virtBuffer <= this.getCurrentTime() && !streamEnded) { Logger.log('HTTPClient: pause caused by virtual buffer ran out', { currentTime: this.getCurrentTime(), virtualBuffer: this.virtBuffer, realBuffer: super.bufferedTime() }); this.virtPause = true; // Prevent NetStreamClient from triggering paused event this.currentState = 'paused'; this.ns.pause(); } else if (this.virtPause && this.virtBuffer - this.getCurrentTime() >= this.ns.bufferTime * 1000) { this.virtPause = false; if (!this.userPause) { this.ns.resume(); } } } else { this.virtBuffer = this.getCurrentTime() + super.bufferedTime(); } } private function onNetStreamStatus(event:NetStatusEvent):void { if ('NetStream.Play.Stop' === event.info.code) { clearInterval(this.updateLoop); } } private function onConnectionStatus(event:NetStatusEvent):void { Logger.log('HTTPClient: connection status:', event.info.code); if ('NetConnection.Connect.Closed' === event.info.code && this.currentState !== 'stopped') { clearInterval(this.updateLoop); this.currentState = 'stopped'; dispatchEvent(new ClientEvent(ClientEvent.STOPPED)); this.ns.dispose(); } } } }
Increase virtual HTTP stream FPS to 30
Increase virtual HTTP stream FPS to 30 Affects granularity of frame by frame feature.
ActionScript
bsd-3-clause
gaetancollaud/locomote-video-player,AxisCommunications/locomote-video-player
1ca91fd9bac0c7842f09a648cb288f33e09a4588
src/com/esri/builder/controllers/supportClasses/LocalConnectionDelegate.as
src/com/esri/builder/controllers/supportClasses/LocalConnectionDelegate.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.controllers.supportClasses { import flash.events.StatusEvent; import flash.net.LocalConnection; import mx.logging.ILogger; import mx.logging.Log; public final class LocalConnectionDelegate { private static const LOG:ILogger = Log.getLogger('com.esri.builder.controllers.supportClasses.LocalConnectionDelegate'); private static const CNAME:String = '_flexViewer'; private var m_localConnection:LocalConnection; private function get localConnection():LocalConnection { if (m_localConnection === null) { if (Log.isDebug()) { LOG.debug("Acquiring local connection"); } m_localConnection = new LocalConnection(); m_localConnection.addEventListener(StatusEvent.STATUS, localConnection_statusHandler); } return m_localConnection; } private function localConnection_statusHandler(event:StatusEvent):void { if (event.level == "error") { if (Log.isDebug()) { LOG.debug("Call failed: {0}", event.toString()); } } } public function setTitles(title:String, subtitle:String):void { if (Log.isDebug()) { LOG.debug("Sending titles changes: title {0} - subtitle {1}", title, subtitle); } callViewerMethod('setTitles', title, subtitle); } private function callViewerMethod(methodName:String, ... values):void { try { //use Function#apply to avoid passing rest argument as Array localConnection.send.apply(null, [ CNAME, methodName ].concat(values)); } catch (error:Error) { if (Log.isDebug()) { LOG.debug("Call to Viewer method {0} failed: {1}", methodName, error); } } } public function setLogo(value:String):void { if (Log.isDebug()) { LOG.debug("Sending logo changes {0}", value); } callViewerMethod('setLogo', value); } public function setTextColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending text color changes {0}", value); } callViewerMethod('setTextColor', value); } public function setBackgroundColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending background color changes {0}", value); } callViewerMethod('setBackgroundColor', value); } public function setRolloverColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending rollover color changes {0}", value); } callViewerMethod('setRolloverColor', value); } public function setSelectionColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending selection color changes {0}", value); } callViewerMethod('setSelectionColor', value); } public function setTitleColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending title color changes {0}", value); } callViewerMethod('setTitleColor', value); } public function setLocale(localeChain:String):void { if (Log.isDebug()) { LOG.debug("Sending locale changes {0}", localeChain); } callViewerMethod('setLocale', localeChain); } public function setFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending font name changes {0}", value); } callViewerMethod('setFontName', value); } public function setAppTitleFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending app title font name changes {0}", value); } callViewerMethod('setAppTitleFontName', value); } public function setSubTitleFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending subtitle font name changes {0}", value); } callViewerMethod('setSubTitleFontName', value); } public function setAlpha(value:Number):void { if (Log.isDebug()) { LOG.debug("Sending alpha changes {0}", value); } callViewerMethod('setAlpha', value); } public function setPredefinedStyles(value:Object):void { if (Log.isDebug()) { LOG.debug("Sending predefined changes {0}", value); } callViewerMethod('setPredefinedStyles', value); } } }
//////////////////////////////////////////////////////////////////////////////// // 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.controllers.supportClasses { import com.esri.builder.supportClasses.LogUtil; import flash.events.StatusEvent; import flash.net.LocalConnection; import mx.logging.ILogger; import mx.logging.Log; public final class LocalConnectionDelegate { private static const LOG:ILogger = LogUtil.createLogger(LocalConnectionDelegate); private static const CONNECTION_NAME:String = '_flexViewer'; private var _localConnection:LocalConnection; private function get localConnection():LocalConnection { if (_localConnection === null) { if (Log.isDebug()) { LOG.debug("Acquiring local connection"); } _localConnection = new LocalConnection(); _localConnection.addEventListener(StatusEvent.STATUS, localConnection_statusHandler); } return _localConnection; } private function localConnection_statusHandler(event:StatusEvent):void { if (event.level == "error") { if (Log.isDebug()) { LOG.debug("Call failed: {0}", event.toString()); } } } public function setTitles(title:String, subtitle:String):void { if (Log.isDebug()) { LOG.debug("Sending titles changes: title {0} - subtitle {1}", title, subtitle); } callViewerMethod('setTitles', title, subtitle); } private function callViewerMethod(methodName:String, ... values):void { try { //use Function#apply to avoid passing rest argument as Array localConnection.send.apply(null, [ CONNECTION_NAME, methodName ].concat(values)); } catch (error:Error) { if (Log.isDebug()) { LOG.debug("Call to Viewer method {0} failed: {1}", methodName, error); } } } public function setLogo(value:String):void { if (Log.isDebug()) { LOG.debug("Sending logo changes {0}", value); } callViewerMethod('setLogo', value); } public function setTextColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending text color changes {0}", value); } callViewerMethod('setTextColor', value); } public function setBackgroundColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending background color changes {0}", value); } callViewerMethod('setBackgroundColor', value); } public function setRolloverColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending rollover color changes {0}", value); } callViewerMethod('setRolloverColor', value); } public function setSelectionColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending selection color changes {0}", value); } callViewerMethod('setSelectionColor', value); } public function setTitleColor(value:uint):void { if (Log.isDebug()) { LOG.debug("Sending title color changes {0}", value); } callViewerMethod('setTitleColor', value); } public function setLocale(localeChain:String):void { if (Log.isDebug()) { LOG.debug("Sending locale changes {0}", localeChain); } callViewerMethod('setLocale', localeChain); } public function setFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending font name changes {0}", value); } callViewerMethod('setFontName', value); } public function setAppTitleFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending app title font name changes {0}", value); } callViewerMethod('setAppTitleFontName', value); } public function setSubTitleFontName(value:String):void { if (Log.isDebug()) { LOG.debug("Sending subtitle font name changes {0}", value); } callViewerMethod('setSubTitleFontName', value); } public function setAlpha(value:Number):void { if (Log.isDebug()) { LOG.debug("Sending alpha changes {0}", value); } callViewerMethod('setAlpha', value); } public function setPredefinedStyles(value:Object):void { if (Log.isDebug()) { LOG.debug("Sending predefined changes {0}", value); } callViewerMethod('setPredefinedStyles', value); } } }
Clean up.
Clean up.
ActionScript
apache-2.0
Esri/arcgis-viewer-builder-flex
a5b7fd63a483b79adb51b7e4c1c7cbf9c6e2c817
src/aerys/minko/type/animation/Animation.as
src/aerys/minko/type/animation/Animation.as
package aerys.minko.type.animation { import aerys.minko.scene.node.IScene; import aerys.minko.scene.node.ITransformable; import aerys.minko.scene.node.group.Group; import aerys.minko.type.animation.timeline.ITimeline; import flash.utils.getTimer; import org.osmf.elements.DurationElement; public class Animation { private var _id : String; private var _beginTime : uint; private var _lastTime : uint; private var _playingOn : IScene; private var _timelines : Vector.<ITimeline>; private var _duration : uint; public function get id() : String { return _id; } public function Animation(id : String, timelines : Vector.<ITimeline>) { _id = id; _timelines = timelines; _lastTime = 0; _duration = 0; for each (var timeline : ITimeline in timelines) if (_duration < timeline.duration) _duration = timeline.duration; } public function tick() : void { var time : uint = (getTimer() - _beginTime) % _duration; transformNodes(time); } public function step() : void { var time : uint = (_lastTime + 2500 / 30) % _duration; transformNodes(time); } public function stepReverse() : void { var time : int = (_lastTime - 2500 / 30) % _duration; if (time < 0) time = time + _duration; transformNodes(time); } private function transformNodes(time : uint) : void { _lastTime = time; var timelinesCount : uint = _timelines.length; for (var i : uint = 0; i < timelinesCount; ++i) { var timeline : ITimeline = _timelines[i]; var timelineTarget : String = timeline.target; var target : ITransformable; if (_playingOn.name == timelineTarget) target = ITransformable(_playingOn); else if (_playingOn is Group) target = ITransformable(Group(_playingOn).getDescendantByName(timelineTarget)); if (!target) continue; timeline.updateAt(time, target); } } public function playOn(node : IScene) : void { _beginTime = getTimer(); _playingOn = node; _lastTime = 0; } public function stop() : void { _playingOn = null; } } }
package aerys.minko.type.animation { import aerys.minko.scene.node.IScene; import aerys.minko.scene.node.ITransformable; import aerys.minko.scene.node.group.Group; import aerys.minko.type.animation.timeline.ITimeline; import flash.utils.getTimer; import org.osmf.elements.DurationElement; public class Animation { private var _id : String; private var _beginTime : uint; private var _lastTime : uint; private var _playingOn : IScene; private var _timelines : Vector.<ITimeline>; private var _duration : uint; public function get id() : String { return _id; } public function Animation(id : String, timelines : Vector.<ITimeline>) { _id = id; _timelines = timelines; _lastTime = 0; _duration = 0; for each (var timeline : ITimeline in timelines) if (_duration < timeline.duration) _duration = timeline.duration; } public function tick() : void { var time : uint = (getTimer() - _beginTime) % _duration; transformNodes(time); } public function step(deltaTime : uint = 80) : void { var time : uint = (_lastTime + deltaTime) % _duration; transformNodes(time); } public function stepReverse(deltaTime : uint = 80) : void { var time : int = (_lastTime - deltaTime) % _duration; if (time < 0) time = time + _duration; transformNodes(time); } private function transformNodes(time : uint) : void { _lastTime = time; var timelinesCount : uint = _timelines.length; for (var i : uint = 0; i < timelinesCount; ++i) { var timeline : ITimeline = _timelines[i]; var timelineTarget : String = timeline.target; var target : ITransformable; if (_playingOn.name == timelineTarget) target = ITransformable(_playingOn); else if (_playingOn is Group) target = ITransformable(Group(_playingOn).getDescendantByName(timelineTarget)); if (!target) continue; timeline.updateAt(time, target); } } public function playOn(node : IScene) : void { _beginTime = getTimer(); _playingOn = node; _lastTime = 0; } public function stop() : void { _playingOn = null; } } }
Enable user to customise deltaTime when calling Animation::step and Animation::stepReverse
Enable user to customise deltaTime when calling Animation::step and Animation::stepReverse
ActionScript
mit
aerys/minko-as3
dcc59600647e91f05615ee4ddcb4c3c454de32dc
src/aerys/minko/scene/SceneIterator.as
src/aerys/minko/scene/SceneIterator.as
package aerys.minko.scene { import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.binding.DataBindings; import avmplus.getQualifiedClassName; import flash.utils.Dictionary; import flash.utils.Proxy; import flash.utils.describeType; import flash.utils.flash_proxy; import flash.utils.getQualifiedClassName; public dynamic class SceneIterator extends Proxy { private static const TYPE_CACHE : Dictionary = new Dictionary(true); private static const OPERATORS : Vector.<String> = new <String>[ "//", "/", "[", "]", "..", ".", "~=", "?=", "=", "@", "*" ]; private static const REGEX_TRIM : RegExp = /^\s+|\s+$/; private var _path : String = null; private var _selection : Vector.<ISceneNode> = null; private var _modifier : String = null; public function get length() : uint { return _selection.length; } public function SceneIterator(path : String, selection : Vector.<ISceneNode>, modifier : String = "") { super(); _modifier = modifier; initialize(path, selection); } public function toString() : String { return _selection.toString(); } override flash_proxy function setProperty(name : *, value : *):void { var propertyName : String = name; for each (var node : ISceneNode in _selection) getValueObject(node, _modifier)[propertyName] = value; } override flash_proxy function getProperty(name : *) : * { var index : int = parseInt(name); if (index == name) return index < _selection.length ? _selection[index] : null; else { throw new Error( 'Unable to get a property on a set of objects. ' + 'You must use the [] operator to fetch one of the objects.' ); } } override flash_proxy function nextNameIndex(index : int) : int { return index < _selection.length ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { return _selection[int(index - 1)]; } override flash_proxy function callProperty(name:*, ...parameters):* { var methodName : String = name; for each (var node : ISceneNode in _selection) { var method : Function = getValueObject(node, _modifier)[methodName]; method.apply(null, parameters); } return this; } private function initialize(path : String, selection : Vector.<ISceneNode>) : void { _path = path; // update root var token : String = getToken(); _selection = selection.slice(); if (token == "/") { selectRoots(); nextToken(token); } // parse while (token = getToken()) { switch (token) { case '//' : nextToken(token); selectDescendants(); break ; case '/' : nextToken(token); selectChildren(); break ; default : nextToken(token); parseNodeType(token); break ; } } } private function getToken(doNext : Boolean = false) : String { var token : String = null; if (!_path) return null; _path = _path.replace(/^\s+/, ''); var nextOpIndex : int = int.MAX_VALUE; for each (var op : String in OPERATORS) { var opIndex : int = _path.indexOf(op); if (opIndex > 0 && opIndex < nextOpIndex) nextOpIndex = opIndex; if (opIndex == 0) { token = op; break ; } } if (!token) token = _path.substring(0, nextOpIndex); if (doNext) nextToken(token); return token; } private function getValueToken() : Object { var value : Object = null; _path = _path.replace(/^\s+/, ''); if (_path.charAt(0) == "'") { var endOfStringIndex : int = _path.indexOf("'", 1); if (endOfStringIndex < 0) throw new Error("Unterminated string expression."); var stringValue : String = _path.substring(1, endOfStringIndex); _path = _path.substring(endOfStringIndex + 1); value = stringValue; } else { var token : String = getToken(true); if (token == "true") value = true; else if (token == "false") value = false; else if (token.indexOf("0x") == 0) value = parseInt(token, 16); } return value; } private function nextToken(token : String) : void { _path = _path.substring(_path.indexOf(token) + token.length); } private function selectChildren(typeName : String = null) : void { var selection : Vector.<ISceneNode> = _selection.slice(); if (typeName != null) typeName = typeName.toLowerCase(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node is Group) { var group : Group = node as Group; var numChildren : uint = group.numChildren; for (var i : uint = 0; i < numChildren; ++i) { var child : ISceneNode = group.getChildAt(i); var className : String = getQualifiedClassName(child) var childType : String = className.substr(className.lastIndexOf(':') + 1); if (typeName == null || childType.toLowerCase() == typeName) _selection.push(child); } } } } private function selectRoots() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) if (_selection.indexOf(node.root) < 0) _selection.push(node); } private function selectDescendants() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { _selection.push(node); if (node is Group) (node as Group).getDescendantsByType(ISceneNode, _selection); } } private function selectParents() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node.parent) _selection.push(node.parent); else _selection.push(node); } } private function parseNodeType(nodeType : String) : void { if (nodeType == '.') { // nothing } if (nodeType == '..') selectParents(); else if (nodeType == '*') selectChildren(); else selectChildren(nodeType); // apply predicates var token : String = getToken(); while (token == "[") { nextToken(token); parsePredicate(); token = getToken(); } } private function parsePredicate() : void { var propertyName : String = getToken(true); var isBinding : Boolean = propertyName == '@'; if (isBinding) propertyName = getToken(true); var index : int = parseInt(propertyName); if (index.toString() == propertyName) { if (index < _selection.length) { _selection[0] = _selection[index]; _selection.length = 1; } else _selection.length = 0; } else { var operator : String = getToken(true); var value : Object = getValueToken(); if (operator == "~=") filterOnRegExp(propertyName, String(value), isBinding); else if (operator == "?=") filterOnController(String(value)); else filterOnValue(propertyName, value, isBinding); } checkNextToken("]"); } private function filterOnRegExp(propertyName : String, regExpString : String, isBinding : Boolean) : void { var numNodes : int = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = _selection[i]; var nodeValue : String = null; if (isBinding && (node['bindings'] is DataBindings)) nodeValue = String((node['bindings'] as DataBindings).getProperty(propertyName)); else nodeValue = String(getValueObject(node, propertyName)); var matches : Array = nodeValue.match(regExpString); if (!matches || matches.length == 0) removeFromSelection(i); } } private function filterOnValue(propertyName : String, value : Object, isBinding : Boolean) : void { var numNodes : int = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = _selection[i]; var nodeValue : Object = null; if (isBinding && (node['bindings'] is DataBindings)) nodeValue = (node['bindings'] as DataBindings).getProperty(propertyName); else nodeValue = getValueObject(node, propertyName); if (nodeValue != value) removeFromSelection(i); } } private function filterOnController(controllerName : Object) : Object { var numNodes : int = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = _selection[i]; var numControllers : uint = node.numControllers; var keepSceneNode : Boolean = false; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controllerType : String = getQualifiedClassName(node.getController(controllerId)); controllerType = controllerType.substr(controllerType.lastIndexOf(':') + 1); if (controllerType == controllerName) { keepSceneNode = true; break; } } if (!keepSceneNode) removeFromSelection(i); } return null; } private function getValueObject(source : Object, modifier : String) : Object { if (modifier) { var tokens : Array = modifier.split("."); for each (var token : String in tokens) source = source[token]; } return source; } private function removeFromSelection(index : int) : void { var numNodes : int = _selection.length; --numNodes; _selection[index] = _selection[numNodes]; _selection.length = numNodes; } private function checkNextToken(expected : String) : void { var token : String = getToken(true); if (token != expected) throwParseError(expected, token); } private function throwParseError(expected : String, got : String) : void { throw new Error( "Parse error: expected '" + expected + "', got '" + got + "'." ); } } }
package aerys.minko.scene { import aerys.minko.scene.node.Group; import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.binding.DataBindings; import avmplus.getQualifiedClassName; import flash.utils.Dictionary; import flash.utils.Proxy; import flash.utils.describeType; import flash.utils.flash_proxy; import flash.utils.getQualifiedClassName; public dynamic class SceneIterator extends Proxy { private static const TYPE_CACHE : Dictionary = new Dictionary(true); private static const OPERATORS : Vector.<String> = new <String>[ "//", "/", "[", "]", "..", ".", "~=", "?=", "=", "@", "*", "(", ")" ]; private static const REGEX_TRIM : RegExp = /^\s+|\s+$/; private var _path : String = null; private var _selection : Vector.<ISceneNode> = null; private var _modifier : String = null; public function get length() : uint { return _selection.length; } public function SceneIterator(path : String, selection : Vector.<ISceneNode>, modifier : String = "") { super(); _modifier = modifier; initialize(path, selection); } public function toString() : String { return _selection.toString(); } override flash_proxy function setProperty(name : *, value : *):void { var propertyName : String = name; for each (var node : ISceneNode in _selection) getValueObject(node, _modifier)[propertyName] = value; } override flash_proxy function getProperty(name : *) : * { var index : int = parseInt(name); if (index == name) return index < _selection.length ? _selection[index] : null; else { throw new Error( 'Unable to get a property on a set of objects. ' + 'You must use the [] operator to fetch one of the objects.' ); } } override flash_proxy function nextNameIndex(index : int) : int { return index < _selection.length ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { return _selection[int(index - 1)]; } override flash_proxy function callProperty(name:*, ...parameters):* { var methodName : String = name; for each (var node : ISceneNode in _selection) { var method : Function = getValueObject(node, _modifier)[methodName]; method.apply(null, parameters); } return this; } private function initialize(path : String, selection : Vector.<ISceneNode>) : void { _path = path; // update root var token : String = getToken(); _selection = selection.slice(); if (token == "/") { selectRoots(); nextToken(token); } // parse while (token = getToken()) { switch (token) { case '//' : nextToken(token); selectDescendants(); break ; case '/' : nextToken(token); selectChildren(); break ; default : nextToken(token); parseNodeType(token); break ; } } } private function getToken(doNext : Boolean = false) : String { var token : String = null; if (!_path) return null; _path = _path.replace(/^\s+/, ''); var nextOpIndex : int = int.MAX_VALUE; for each (var op : String in OPERATORS) { var opIndex : int = _path.indexOf(op); if (opIndex > 0 && opIndex < nextOpIndex) nextOpIndex = opIndex; if (opIndex == 0) { token = op; break ; } } if (!token) token = _path.substring(0, nextOpIndex); if (doNext) nextToken(token); return token; } private function getValueToken() : Object { var value : Object = null; _path = _path.replace(/^\s+/, ''); if (_path.charAt(0) == "'") { var endOfStringIndex : int = _path.indexOf("'", 1); if (endOfStringIndex < 0) throw new Error("Unterminated string expression."); var stringValue : String = _path.substring(1, endOfStringIndex); _path = _path.substring(endOfStringIndex + 1); value = stringValue; } else { var token : String = getToken(true); if (token == "true") value = true; else if (token == "false") value = false; else if (token.indexOf("0x") == 0) value = parseInt(token, 16); } return value; } private function nextToken(token : String) : void { _path = _path.substring(_path.indexOf(token) + token.length); } private function selectChildren(typeName : String = null) : void { var selection : Vector.<ISceneNode> = _selection.slice(); if (typeName != null) typeName = typeName.toLowerCase(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node is Group) { var group : Group = node as Group; var numChildren : uint = group.numChildren; for (var i : uint = 0; i < numChildren; ++i) { var child : ISceneNode = group.getChildAt(i); var className : String = getQualifiedClassName(child) var childType : String = className.substr(className.lastIndexOf(':') + 1); if (typeName == null || childType.toLowerCase() == typeName) _selection.push(child); } } } } private function selectRoots() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) if (_selection.indexOf(node.root) < 0) _selection.push(node); } private function selectDescendants() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { _selection.push(node); if (node is Group) (node as Group).getDescendantsByType(ISceneNode, _selection); } } private function selectParents() : void { var selection : Vector.<ISceneNode> = _selection.slice(); _selection.length = 0; for each (var node : ISceneNode in selection) { if (node.parent) _selection.push(node.parent); else _selection.push(node); } } private function parseNodeType(nodeType : String) : void { if (nodeType == '.') { // nothing } if (nodeType == '..') selectParents(); else if (nodeType == '*') selectChildren(); else selectChildren(nodeType); // apply predicates var token : String = getToken(); while (token == "[") { nextToken(token); parsePredicate(); token = getToken(); } } private function parsePredicate() : void { var propertyName : String = getToken(true); var isBinding : Boolean = propertyName == '@'; if (isBinding) propertyName = getToken(true); var index : int = parseInt(propertyName); if (index.toString() == propertyName) { if (index < _selection.length) { _selection[0] = _selection[index]; _selection.length = 1; } else _selection.length = 0; } else if (propertyName == 'hasController') { checkNextToken('('); filterOnController(getToken(true)); checkNextToken(')'); } else { var operator : String = getToken(true); var value : Object = getValueToken(); if (operator == "~=") filterOnRegExp(propertyName, String(value), isBinding); else filterOnValue(propertyName, value, isBinding); } checkNextToken("]"); } private function filterOnRegExp(propertyName : String, regExpString : String, isBinding : Boolean) : void { var numNodes : int = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = _selection[i]; var nodeValue : String = null; if (isBinding && (node['bindings'] is DataBindings)) nodeValue = String((node['bindings'] as DataBindings).getProperty(propertyName)); else nodeValue = String(getValueObject(node, propertyName)); var matches : Array = nodeValue.match(regExpString); if (!matches || matches.length == 0) removeFromSelection(i); } } private function filterOnValue(propertyName : String, value : Object, isBinding : Boolean) : void { var numNodes : int = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = _selection[i]; var nodeValue : Object = null; if (isBinding && (node['bindings'] is DataBindings)) nodeValue = (node['bindings'] as DataBindings).getProperty(propertyName); else nodeValue = getValueObject(node, propertyName); if (nodeValue != value) removeFromSelection(i); } } private function filterOnController(controllerName : Object) : Object { var numNodes : int = _selection.length; for (var i : int = numNodes - 1; i >= 0; --i) { var node : ISceneNode = _selection[i]; var numControllers : uint = node.numControllers; var keepSceneNode : Boolean = false; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controllerType : String = getQualifiedClassName(node.getController(controllerId)); controllerType = controllerType.substr(controllerType.lastIndexOf(':') + 1); if (controllerType == controllerName) { keepSceneNode = true; break; } } if (!keepSceneNode) removeFromSelection(i); } return null; } private function getValueObject(source : Object, modifier : String) : Object { if (modifier) { var tokens : Array = modifier.split("."); for each (var token : String in tokens) source = source[token]; } return source; } private function removeFromSelection(index : int) : void { var numNodes : int = _selection.length; --numNodes; _selection[index] = _selection[numNodes]; _selection.length = numNodes; } private function checkNextToken(expected : String) : void { var token : String = getToken(true); if (token != expected) throwParseError(expected, token); } private function throwParseError(expected : String, got : String) : void { throw new Error( "Parse error: expected '" + expected + "', got '" + got + "'." ); } } }
add XPath special function 'hasController()' instead of weird ?= operator
add XPath special function 'hasController()' instead of weird ?= operator
ActionScript
mit
aerys/minko-as3
f14bc0fb01a151f9261726bf12b2f228958b3667
sdk-remote/src/tests/liburbi-check.as
sdk-remote/src/tests/liburbi-check.as
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*- AS_INIT()dnl URBI_PREPARE() set -e case $VERBOSE in x) set -x;; esac # Avoid zombies and preserve debugging information. cleanup () { exit_status=$? # In case we were caught by set -e, kill the children. children_kill children_harvest children_report children_sta=$(children_status remote) # Don't clean before calling children_status... test x$VERBOSE != x || children_clean case $exit_status:$children_sta in 0:0) ;; 0:*) # Maybe a children exited for SKIP etc. exit $children_sta;; *:*) # If liburbi-check failed, there is a big problem. error SOFTWARE "liburbi-check itself failed with $exit_status";; esac # rst_expect sets exit=false if it saw a failure. $exit } for signal in 1 2 13 15; do trap 'error $((128 + $signal)) \ "received signal $signal ($(kill -l $signal))"' $signal done trap cleanup 0 # Overriden to include the test name. stderr () { echo >&2 "$(basename $0): $me: $@" echo >&2 } # Sleep some time, but taking into account the fact that # instrumentation slows down a lot. my_sleep () { if $INSTRUMENT; then sleep $(($1 * 5)) else sleep $1 fi } ## -------------- ## ## Main program. ## ## -------------- ## exec 3>&2 : ${abs_builddir='@abs_builddir@'} check_dir abs_builddir liburbi-check : ${abs_top_builddir='@abs_top_builddir@'} check_dir abs_top_builddir config.status : ${abs_top_srcdir='@abs_top_srcdir@'} check_dir abs_top_srcdir configure.ac # Make it absolute. chk=$(absolute "$1") if test ! -f "$chk.cc"; then fatal "no such file: $chk.cc" fi period=32 # ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x medir=$(basename $(dirname "$chk")) # ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp me=$medir/$(basename "$chk" ".cc") # ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp meraw=$(basename $me) # MERAW! srcdir=$(absolute $srcdir) export srcdir # Move to a private dir. rm -rf $me.dir mkdir -p $me.dir cd $me.dir # Help debugging set | rst_pre "$me variables" # $URBI_SERVER. # # If this SDK-Remote is part of the Kernel package, then we should not # use an installed urbi-console, but rather the one which is part of # this package. if test -d $abs_top_srcdir/../../src/kernel; then stderr "This SDK-Remote is part of a kernel package." URBI_SERVER=$abs_top_builddir/../src/urbi-console export URBI_PATH=$abs_top_srcdir/../share else stderr "This SDK-Remote is standalone." fi # Leaves trailing files, so run it in subdir. find_urbi_server # Compute expected output. sed -n -e 's@//= @@p' $chk.cc >output.exp touch error.exp echo 0 >status.exp # Start it. valgrind=$(instrument "server.val") cmd="$valgrind $URBI_SERVER --port 0 -w server.port --period $period" echo "$cmd" >server.cmd $cmd >server.out 2>server.err & children_register server my_sleep 2 # Start the test. valgrind=$(instrument "remote.val") cmd="$valgrind ../../tests localhost $(cat server.port) $meraw" echo "$cmd" >remote.cmd $cmd >remote.out.raw 2>remote.err & children_register remote # Let some time to run the tests. children_wait 10 # Ignore the "client errors". sed -e '/^E client error/d' remote.out.raw >remote.out.eff # Compare expected output with actual output. rst_expect output remote.out rst_pre "Error output" remote.err # Display Valgrind report. rst_pre "Valgrind" remote.val # Exit with success: liburbi-check made its job. But now clean (on # trap 0) will check $exit to see if there is a failure in the tests # and adjust the exit status accordingly. exit 0
m4_pattern_allow([^URBI_(PATH|SERVER)$]) -*- shell-script -*- AS_INIT()dnl URBI_PREPARE() set -e case $VERBOSE in x) set -x;; esac # Avoid zombies and preserve debugging information. cleanup () { exit_status=$? # In case we were caught by set -e, kill the children. children_kill children_harvest children_report children_sta=$(children_status remote) # Don't clean before calling children_status... test x$VERBOSE != x || children_clean case $exit_status:$children_sta in 0:0) ;; 0:*) # Maybe a children exited for SKIP etc. exit $children_sta;; *:*) # If liburbi-check failed, there is a big problem. error SOFTWARE "liburbi-check itself failed with $exit_status";; esac # rst_expect sets exit=false if it saw a failure. $exit } for signal in 1 2 13 15; do trap 'error $((128 + $signal)) \ "received signal $signal ($(kill -l $signal))"' $signal done trap cleanup 0 # Overriden to include the test name. stderr () { echo >&2 "$(basename $0): $me: $@" echo >&2 } # Sleep some time, but taking into account the fact that # instrumentation slows down a lot. my_sleep () { if $INSTRUMENT; then sleep $(($1 * 5)) else sleep $1 fi } ## -------------- ## ## Main program. ## ## -------------- ## exec 3>&2 : ${abs_builddir='@abs_builddir@'} check_dir abs_builddir liburbi-check : ${abs_top_builddir='@abs_top_builddir@'} check_dir abs_top_builddir config.status : ${abs_top_srcdir='@abs_top_srcdir@'} check_dir abs_top_srcdir configure.ac # Make it absolute. chk=$(absolute "$1") if test ! -f "$chk.cc"; then fatal "no such file: $chk.cc" fi period=32 # ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x medir=$(basename $(dirname "$chk")) # ./../../../tests/2.x/andexp-pipeexp.chk -> 2.x/andexp-pipeexp me=$medir/$(basename "$chk" ".cc") # ./../../../tests/2.x/andexp-pipeexp.chk -> andexp-pipeexp meraw=$(basename $me) # MERAW! srcdir=$(absolute $srcdir) export srcdir # Move to a private dir. rm -rf $me.dir mkdir -p $me.dir cd $me.dir # Help debugging set | rst_pre "$me variables" # $URBI_SERVER. # # If this SDK-Remote is part of the Kernel package, then we should not # use an installed urbi-console, but rather the one which is part of # this package. if test -d $abs_top_srcdir/../../src/kernel; then stderr "This SDK-Remote is part of a kernel package" \ " ($abs_top_srcdir/../../src/kernel exists)." URBI_SERVER=$abs_top_builddir/../src/urbi-console export URBI_PATH=$abs_top_srcdir/../share else stderr "This SDK-Remote is standalone." fi # Leaves trailing files, so run it in subdir. find_urbi_server # Compute expected output. sed -n -e 's@//= @@p' $chk.cc >output.exp touch error.exp echo 0 >status.exp # Start it. valgrind=$(instrument "server.val") cmd="$valgrind $URBI_SERVER --port 0 -w server.port --period $period" echo "$cmd" >server.cmd $cmd >server.out 2>server.err & children_register server my_sleep 2 # Start the test. valgrind=$(instrument "remote.val") cmd="$valgrind ../../tests localhost $(cat server.port) $meraw" echo "$cmd" >remote.cmd $cmd >remote.out.raw 2>remote.err & children_register remote # Let some time to run the tests. children_wait 10 # Ignore the "client errors". sed -e '/^E client error/d' remote.out.raw >remote.out.eff # Compare expected output with actual output. rst_expect output remote.out rst_pre "Error output" remote.err # Display Valgrind report. rst_pre "Valgrind" remote.val # Exit with success: liburbi-check made its job. But now clean (on # trap 0) will check $exit to see if there is a failure in the tests # and adjust the exit status accordingly. exit 0
Improve a log message.
Improve a log message.
ActionScript
bsd-3-clause
urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi,aldebaran/urbi,urbiforge/urbi
d8f843b4cbff01f809afe56a27c7ead10278672d
test/stutter/StutterRunTimeTest.as
test/stutter/StutterRunTimeTest.as
package stutter { import org.flexunit.assertThat; import org.hamcrest.collection.array; import org.hamcrest.object.equalTo; import org.hamcrest.object.isFalse; import org.hamcrest.object.isTrue; public class StutterRunTimeTest { public var l:StutterRunTime; [Before] public function setup():void { l = new StutterRunTime(); } [Test] public function label():void { // (label a 42) l.eval([ S('label'), S('a'), 42 ]); // a // => 42 assertThat(l.eval(S('a')), equalTo(42)) } [Test] public function eq():void { l.eval([ S('label'), S('a'), 42 ]); // (eq 42 a) // => true assertThat(l.eval([ S('eq'), 42, S('a')]), isTrue()); } [Test] public function quote():void { // `(1 2) // => [1, 2] assertThat(l.eval([ S('quote'), [ 1, 2 ] ]), array(1, 2)); } [Test] public function car():void { // (car `(1 2)) // => 1 assertThat(l.eval([ S('car'), [ S('quote'), [ 1, 2 ] ]]), equalTo(1)); } [Test] public function cdr():void { // (cdr `(1 2)) // => [2] assertThat(l.eval([ S('cdr'), [ S('quote'), [ 1, 2 ] ]]), array(2)); } [Test] public function cons():void { // (cons 1 `(2 3)) // => [1, 2, 3] assertThat(l.eval([ S('cons'), 1, [ S('quote'), [ 2, 3 ] ]]), array(1, 2, 3)); } [Test] public function if_():void { // (if (eq 1 2) 42 43) // => 43 assertThat(l.eval([ S('if'), [ S('eq'), 1, 2 ], 42, 43 ]), equalTo(43)); } [Test] public function atom():void { l.eval([ S('label'), S('a'), 42 ]); // (atom a) // => true assertThat(l.eval([ S('atom'), [ S('a') ]]), isTrue()); // (atom 123) // => true assertThat(l.eval([ S('atom'), [ 123 ]]), isTrue()); // (atom `(1)) // => true assertThat(l.eval([ S('atom'), [ S('quote'), [ 1 ] ]]), isFalse()); // (atom `(1 2)) // => false assertThat(l.eval([ S('atom'), [ S('quote'), [ 1, 2 ]]]), isFalse()); } [Test] public function lambda():void { // (label second `(lambda (x) (car (cdr x)))) l.eval([ S('label'), S('second'), [ S('quote'), [ S('lambda'), [ S('x') ], [ S('car'), [ S('cdr'), S('x')]]]]]); // (second `(1 2 3)) assertThat(l.eval([ S('second'), [ S('quote'), [ 1, 2, 3 ]]]), equalTo(2)); } } }
package stutter { import org.flexunit.assertThat; import org.hamcrest.collection.array; import org.hamcrest.object.equalTo; import org.hamcrest.object.isFalse; import org.hamcrest.object.isTrue; public class StutterRunTimeTest { public var l:StutterRunTime; [Before] public function setup():void { l = new StutterRunTime(); } [Test] public function label():void { // (label a 42) l.eval([ S('label'), S('a'), 42 ]); // a // => 42 assertThat(l.eval(S('a')), equalTo(42)) } [Test] public function eq():void { l.eval([ S('label'), S('a'), 42 ]); // (eq 42 a) // => true assertThat(l.eval([ S('eq'), 42, S('a')]), isTrue()); } [Test] public function quote():void { // `(1 2) // => [1, 2] assertThat(l.eval([ S('quote'), [ 1, 2 ] ]), array(1, 2)); } [Test] public function car():void { // (car `(1 2)) // => 1 assertThat(l.eval([ S('car'), [ S('quote'), [ 1, 2 ] ]]), equalTo(1)); } [Test] public function cdr():void { // (cdr `(1 2)) // => [2] assertThat(l.eval([ S('cdr'), [ S('quote'), [ 1, 2 ] ]]), array(2)); } [Test] public function cons():void { // (cons 1 `(2 3)) // => [1, 2, 3] assertThat(l.eval([ S('cons'), 1, [ S('quote'), [ 2, 3 ] ]]), array(1, 2, 3)); } [Test] public function if_():void { // (if (eq 1 2) 42 43) // => 43 assertThat(l.eval([ S('if'), [ S('eq'), 1, 2 ], 42, 43 ]), equalTo(43)); } [Test] public function atom():void { l.eval([ S('label'), S('a'), 42 ]); // (atom a) // => true assertThat(l.eval([ S('atom'), [ S('a') ]]), isTrue()); // (atom 123) // => true assertThat(l.eval([ S('atom'), [ 123 ]]), isTrue()); // (atom `(1)) // => true assertThat(l.eval([ S('atom'), [ S('quote'), [ 1 ] ]]), isFalse()); // (atom `(1 2)) // => false assertThat(l.eval([ S('atom'), [ S('quote'), [ 1, 2 ]]]), isFalse()); } [Test] public function lambda():void { // (label second '(lambda (x) (car (cdr x)))) l.eval([ S('label'), S('second'), [ S('quote'), [ S('lambda'), [ S('x') ], [ S('car'), [ S('cdr'), S('x')]]]]]); // (second '(1 2 3)) assertThat(l.eval([ S('second'), [ S('quote'), [ 1, 2, 3 ]]]), equalTo(2)); } } }
correct syntax in examples
correct syntax in examples
ActionScript
mit
drewbourne/stutter
f73f636907752b8d9c0b640812d26a94537862df
src/main/actionscript/com/dotfold/dotvimstat/view/summary/VideosSummary.as
src/main/actionscript/com/dotfold/dotvimstat/view/summary/VideosSummary.as
package com.dotfold.dotvimstat.view.summary { import asx.string.empty; import com.dotfold.dotvimstat.net.service.VimeoBasicService; import com.dotfold.dotvimstat.view.IView; import com.greensock.TweenLite; import modena.core.Element; import modena.core.ElementContent; import modena.ui.Label; /** * VideosSummary view shows the count of videos retrieved from the Vimeo API. * * @author jamesmcnamee * */ public class VideosSummary extends Element implements IView { public static const ELEMENT_NAME:String = "videosSummary"; private var _label:Label; /** * Constructor. */ public function VideosSummary(styleClass:String = null) { super(styleClass); } /** * @inheritDoc */ override protected function createElementContent():ElementContent { var content:ElementContent = super.createElementContent(); _label = new Label("summaryCount"); content.addChild(_label); _label.alpha = 0; return content; } /** * Update the label with count of videos. */ public function set videosCount(value:int):void { _label.text = value.toString(); TweenLite.to(_label, 0.4, { alpha: 1, ease: 'easeInQuad' }); invalidateRender(); } override public function validateRender():void { super.validateRender(); _label.x = (width - _label.width) / 2; _label.y = (height - _label.height) / 2; } } }
package com.dotfold.dotvimstat.view.summary { import com.dotfold.dotvimstat.view.IView; import com.dotfold.dotvimstat.view.animation.ElementAnimationSequencer; import modena.core.ElementContent; import modena.ui.HBox; import modena.ui.Label; /** * VideosSummary view shows the count of videos retrieved from the Vimeo API. * * @author jamesmcnamee * */ public class VideosSummary extends HBox implements IView { public static const ELEMENT_NAME:String = "videosSummary"; private var _numVideos:Label; private var _staticText:Label; [Inject] public var animationQueue:ElementAnimationSequencer; /** * Constructor. */ public function VideosSummary(styleClass:String = null) { super(styleClass); } /** * @inheritDoc */ override protected function createElementContent():ElementContent { var content:ElementContent = super.createElementContent(); _numVideos = new Label("summaryDetail"); _numVideos.alpha = 0; _staticText = new Label("summarySmall"); _staticText.text = "total videos"; _staticText.alpha = 0; content.addChild(_numVideos); content.addChild(_staticText); return content; } /** * Called from Mediator once data load is complete. */ public function show():void { runAnimationQueue(); } /** * Update the num videos label. */ public function set videosCount(value:int):void { _numVideos.text = value.toString(); invalidateRender(); } /** * Add elements to the animation queue and start. */ private function runAnimationQueue():void { animationQueue .addElement(_numVideos) .addElement(_staticText) .play(); } } }
update video summary view
[feat] update video summary view - use animation queue - cleanup text handling
ActionScript
mit
dotfold/dotvimstat
a058098aa03d2a47cc8afa9edd314cfa69480988
src/aerys/minko/render/shader/part/phong/contribution/AbstractContributionShaderPart.as
src/aerys/minko/render/shader/part/phong/contribution/AbstractContributionShaderPart.as
package aerys.minko.render.shader.part.phong.contribution { import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.material.phong.PhongProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.part.phong.LightAwareShaderPart; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerFormat; /** * Methods in this class allow to compute light contributions. * It is extended by InfiniteShaderPart for directional lights, and LocalizedShaderPart for point and spot lights. * * All methods are available in tangent, local and world space. * * - Computing in tangent space is computationally more expensive, both in CPU and GPU, because we need to feed * more data to the shaders than the other methods but it allows to do both bump and parallax mapping. * * - Doing it in local space is computationally more expensive on the CPU, because the light * position will need to be converted in the CPU for each mesh and at each frame will produce the lighter shaders. * * Doing as much work on the CPU as possible, and have as short a possible shader would be the way to go * if adobe's compiler was better than it is. Therefor, minko defaults to computing everything in world space * which is faster in practical tests. * * The cost of each light will be in O(number of drawcalls) on the CPU. * However, this is the way that will lead to the smaller shaders, and is therefor recomended when used * in small scenes with many lights. * * - Computing lights in world space is cheaper on the CPU, because no extra computation is * needed for each mesh, but will cost one extra matrix multiplication on the GPU (we need the world position * or every fragment). * * @author Romain Gilliotte * */ public class AbstractContributionShaderPart extends LightAwareShaderPart { public function AbstractContributionShaderPart(main : Shader) { super(main); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computations will be done in tangent space. * * @param lightId The id of the localized light (PointLight or SpotLight) * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInTangentSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computation will be done in local space. * * @param lightId The id of the localized light (PointLight or SpotLight) * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInLocalSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computation will be done in world space. * * @param lightId The id of the light * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInWorldSpace(lightId : uint, normal : SFloat) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in tangent space. * * @param lightId * @return */ public function computeSpecularInTangentSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in local space. * * @param lightId * @return */ public function computeSpecularInLocalSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in world space. * * @param lightId * @return */ public function computeSpecularInWorldSpace(lightId : uint, normal : SFloat) : SFloat { throw new Error('Must be overriden'); } /** * Compute final diffuse value from light direction and normal. * Both requested vector can be in any space (tangent, local, light, view or whatever) but must be in the same space. * Also they must be recheable in the fragment shader (they must be constant, or already interpolated) * * @param lightId * @param fsLightDirection * @param fsNormal * @return */ protected function diffuseFromVectors(lightId : uint, fsLightDirection : SFloat, fsNormal : SFloat) : SFloat { var fsLambertProduct : SFloat = saturate(negate(dotProduct3(fsLightDirection, fsNormal))); var cDiffuse : SFloat = getLightParameter(lightId, 'diffuse', 1); if (meshBindings.propertyExists(PhongProperties.DIFFUSE_MULTIPLIER)) cDiffuse.scaleBy(meshBindings.getParameter(PhongProperties.DIFFUSE_MULTIPLIER, 1)); return multiply(cDiffuse, fsLambertProduct); } /** * Compute final specular value from light direction, normal, and camera direction. * All three requested vector can be in any space (tangent, local, light, view or whatever) but must all be in the same sapce. * Also they must be recheable in the fragment shader (they must be constant, or already interpolated) * * @param lightId * @param fsLightDirection * @param fsNormal * @param fsCameraDirection * @return */ protected function specularFromVectors(lightId : uint, fsLightDirection : SFloat, fsNormal : SFloat, fsCameraDirection : SFloat) : SFloat { var fsLightReflectedDirection : SFloat = reflect(fsLightDirection, fsNormal); var fsLambertProduct : SFloat = saturate(negate(dotProduct3(fsLightReflectedDirection, fsCameraDirection))); var cLightSpecular : SFloat = getLightParameter(lightId, 'specular', 1); var cLightShininess : SFloat = getLightParameter(lightId, 'shininess', 1); if (meshBindings.propertyExists(PhongProperties.SPECULAR)) { var specular : SFloat = meshBindings.getParameter(PhongProperties.SPECULAR, 4); cLightSpecular = multiply(cLightSpecular, specular.xyz); } if (meshBindings.propertyExists(PhongProperties.SPECULAR_MAP)) { var fsSpecularSample : SFloat = sampleTexture( meshBindings.getTextureParameter( PhongProperties.SPECULAR_MAP, 1, 0, 1, 0, meshBindings.getProperty(PhongProperties.SPECULAR_MAP_FORMAT, SamplerFormat.RGBA) ), fsUV ); cLightSpecular.scaleBy(fsSpecularSample.x); } if (meshBindings.propertyExists(PhongProperties.SHININESS)) cLightShininess.scaleBy(meshBindings.getParameter(PhongProperties.SHININESS, 1)); return multiply(cLightSpecular, power(fsLambertProduct, cLightShininess)); } } }
package aerys.minko.render.shader.part.phong.contribution { import aerys.minko.render.material.basic.BasicProperties; import aerys.minko.render.material.phong.PhongProperties; import aerys.minko.render.shader.SFloat; import aerys.minko.render.shader.Shader; import aerys.minko.render.shader.part.phong.LightAwareShaderPart; import aerys.minko.type.enum.SamplerFiltering; import aerys.minko.type.enum.SamplerFormat; /** * Methods in this class allow to compute light contributions. * It is extended by InfiniteShaderPart for directional lights, and LocalizedShaderPart for point and spot lights. * * All methods are available in tangent, local and world space. * * - Computing in tangent space is computationally more expensive, both in CPU and GPU, because we need to feed * more data to the shaders than the other methods but it allows to do both bump and parallax mapping. * * - Doing it in local space is computationally more expensive on the CPU, because the light * position will need to be converted in the CPU for each mesh and at each frame will produce the lighter shaders. * * Doing as much work on the CPU as possible, and have as short a possible shader would be the way to go * if adobe's compiler was better than it is. Therefor, minko defaults to computing everything in world space * which is faster in practical tests. * * The cost of each light will be in O(number of drawcalls) on the CPU. * However, this is the way that will lead to the smaller shaders, and is therefor recomended when used * in small scenes with many lights. * * - Computing lights in world space is cheaper on the CPU, because no extra computation is * needed for each mesh, but will cost one extra matrix multiplication on the GPU (we need the world position * or every fragment). * * @author Romain Gilliotte * */ public class AbstractContributionShaderPart extends LightAwareShaderPart { public function AbstractContributionShaderPart(main : Shader) { super(main); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computations will be done in tangent space. * * @param lightId The id of the localized light (PointLight or SpotLight) * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInTangentSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computation will be done in local space. * * @param lightId The id of the localized light (PointLight or SpotLight) * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInLocalSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the diffuse value of a given light. * Computation will be done in world space. * * @param lightId The id of the light * @return Shader subgraph representing the diffuse value of this light. */ public function computeDiffuseInWorldSpace(lightId : uint, normal : SFloat) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in tangent space. * * @param lightId * @return */ public function computeSpecularInTangentSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in local space. * * @param lightId * @return */ public function computeSpecularInLocalSpace(lightId : uint) : SFloat { throw new Error('Must be overriden'); } /** * Creates the shader subgraph to compute the specular value of a given light. * Computation will be done in world space. * * @param lightId * @return */ public function computeSpecularInWorldSpace(lightId : uint, normal : SFloat) : SFloat { throw new Error('Must be overriden'); } /** * Compute final diffuse value from light direction and normal. * Both requested vector can be in any space (tangent, local, light, view or whatever) but must be in the same space. * Also they must be recheable in the fragment shader (they must be constant, or already interpolated) * * @param lightId * @param fsLightDirection * @param fsNormal * @return */ protected function diffuseFromVectors(lightId : uint, fsLightDirection : SFloat, fsNormal : SFloat) : SFloat { var fsLambertProduct : SFloat = saturate(negate(dotProduct3(fsLightDirection, fsNormal))); var cDiffuse : SFloat = getLightParameter(lightId, 'diffuse', 1); if (meshBindings.propertyExists(PhongProperties.DIFFUSE_MULTIPLIER)) cDiffuse.scaleBy(meshBindings.getParameter(PhongProperties.DIFFUSE_MULTIPLIER, 1)); return multiply(cDiffuse, fsLambertProduct); } /** * Compute final specular value from light direction, normal, and camera direction. * All three requested vector can be in any space (tangent, local, light, view or whatever) but must all be in the same sapce. * Also they must be recheable in the fragment shader (they must be constant, or already interpolated) * * @param lightId * @param fsLightDirection * @param fsNormal * @param fsCameraDirection * @return */ protected function specularFromVectors(lightId : uint, fsLightDirection : SFloat, fsNormal : SFloat, fsCameraDirection : SFloat) : SFloat { var fsLightReflectedDirection : SFloat = reflect(fsLightDirection, fsNormal); var fsLambertProduct : SFloat = saturate(negate(dotProduct3(fsLightReflectedDirection, fsCameraDirection))); var cLightSpecular : SFloat = getLightParameter(lightId, 'specular', 1); var cLightShininess : SFloat = getLightParameter(lightId, 'shininess', 1); if (meshBindings.propertyExists(PhongProperties.SPECULAR) && !meshBindings.propertyExists(PhongProperties.SPECULAR_MAP)) { var specular : SFloat = meshBindings.getParameter(PhongProperties.SPECULAR, 4); cLightSpecular = multiply(cLightSpecular, specular.xyz); } if (meshBindings.propertyExists(PhongProperties.SPECULAR_MAP)) { var fsSpecularSample : SFloat = sampleTexture( meshBindings.getTextureParameter( PhongProperties.SPECULAR_MAP, 1, 0, 1, 0, meshBindings.getProperty(PhongProperties.SPECULAR_MAP_FORMAT, SamplerFormat.RGBA) ), fsUV ); cLightSpecular.scaleBy(fsSpecularSample.x); } if (meshBindings.propertyExists(PhongProperties.SHININESS)) cLightShininess.scaleBy(meshBindings.getParameter(PhongProperties.SHININESS, 1)); return multiply(cLightSpecular, power(fsLambertProduct, cLightShininess)); } } }
Remove specular color instruction when a specular map is available
Remove specular color instruction when a specular map is available
ActionScript
mit
aerys/minko-as3
5d466ac3f9d5ffba72d8884cce76fc9caa8b247a
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleStatesImpl.as
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/SimpleStatesImpl.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 mx.states.AddItems; import mx.states.SetProperty; import mx.states.State; import org.apache.flex.core.IParent; import org.apache.flex.core.IStatesObject; import org.apache.flex.events.Event; import org.apache.flex.events.EventDispatcher; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.events.ValueChangeEvent; import org.apache.flex.utils.MXMLDataInterpreter; /** * The SimpleStatesImpl class implements a minimal set of * view state functionality that is sufficient for most applications. * It only supports AddItems and SetProperty changes at this time. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class SimpleStatesImpl extends EventDispatcher implements IStatesImpl, IBead { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function SimpleStatesImpl() { 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; IEventDispatcher(_strand).addEventListener("currentStateChange", stateChangeHandler); IEventDispatcher(_strand).addEventListener("initComplete", initialStateHandler); } private function initialStateHandler(event:org.apache.flex.events.Event):void { stateChangeHandler(new ValueChangeEvent("currentStateChange", false, false, null, IStatesObject(_strand).currentState)); } private function stateChangeHandler(event:ValueChangeEvent):void { var doc:IStatesObject = _strand as IStatesObject; var arr:Array = doc.states; for each (var s:State in arr) { if (s.name == event.oldValue) { revert(s); break; } } for each (s in arr) { if (s.name == event.newValue) { apply(s); break; } } doc.dispatchEvent(new Event("stateChangeComplete")); } private function revert(s:State):void { var arr:Array = s.overrides; for each (var o:Object in arr) { if (o is AddItems) { var ai:AddItems = AddItems(o); for each (var item:DisplayObject in ai.items) { var parent:IParent = ai.document as IParent; if (ai.destination != null) parent = parent[ai.destination] as IParent; parent.removeElement(item); } if (parent is IContainer) IContainer(parent).childrenAdded(); } else if (o is SetProperty) { var sp:SetProperty = SetProperty(o); sp.document[sp.target][sp.name] = sp.previousValue; } } } private function apply(s:State):void { var arr:Array = s.overrides; for each (var o:Object in arr) { if (o is AddItems) { var ai:AddItems = AddItems(o); if (ai.items == null) { ai.items = MXMLDataInterpreter.generateMXMLArray(ai.document, null, ai.itemsDescriptor); } for each (var item:DisplayObject in ai.items) { var parent:IParent = ai.document as IParent; if (ai.destination != null) parent = parent[ai.destination] as IParent; if (ai.relativeTo != null) { var index:int = parent.numElements; if (ai.relativeTo != null) { var child:Object = ai.document[ai.relativeTo]; index = parent.getElementIndex(child); if (ai.position == "after") index++; } parent.addElementAt(item, index); } else { parent.addElement(item); } } if (parent is IContainer) IContainer(parent).childrenAdded(); } else if (o is SetProperty) { var sp:SetProperty = SetProperty(o); sp.previousValue = sp.document[sp.target][sp.name]; sp.document[sp.target][sp.name] = sp.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.core { import flash.display.DisplayObject; import mx.states.AddItems; import mx.states.SetProperty; import mx.states.State; import org.apache.flex.core.IParent; import org.apache.flex.core.IStatesObject; import org.apache.flex.events.Event; import org.apache.flex.events.EventDispatcher; import org.apache.flex.events.IEventDispatcher; import org.apache.flex.events.ValueChangeEvent; import org.apache.flex.utils.MXMLDataInterpreter; /** * The SimpleStatesImpl class implements a minimal set of * view state functionality that is sufficient for most applications. * It only supports AddItems and SetProperty changes at this time. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class SimpleStatesImpl extends EventDispatcher implements IStatesImpl, IBead { /** * Constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public function SimpleStatesImpl() { 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; IEventDispatcher(_strand).addEventListener("currentStateChange", stateChangeHandler); IEventDispatcher(_strand).addEventListener("initComplete", initialStateHandler); } private function initialStateHandler(event:org.apache.flex.events.Event):void { stateChangeHandler(new ValueChangeEvent("currentStateChange", false, false, null, IStatesObject(_strand).currentState)); } private function stateChangeHandler(event:ValueChangeEvent):void { var doc:IStatesObject = _strand as IStatesObject; var arr:Array = doc.states; for each (var s:State in arr) { if (s.name == event.oldValue) { revert(s); break; } } for each (s in arr) { if (s.name == event.newValue) { apply(s); break; } } doc.dispatchEvent(new Event("stateChangeComplete")); } private function revert(s:State):void { var arr:Array = s.overrides; for each (var o:Object in arr) { if (o is AddItems) { var ai:AddItems = AddItems(o); for each (var item:DisplayObject in ai.items) { var parent:IParent = ai.document as IParent; if (ai.destination != null) parent = parent[ai.destination] as IParent; parent.removeElement(item); } if (parent is IContainer) IContainer(parent).childrenAdded(); } else if (o is SetProperty) { var sp:SetProperty = SetProperty(o); if (sp.target != null) sp.document[sp.target][sp.name] = sp.previousValue; else sp.document[sp.name] = sp.previousValue; } } } private function apply(s:State):void { var arr:Array = s.overrides; for each (var o:Object in arr) { if (o is AddItems) { var ai:AddItems = AddItems(o); if (ai.items == null) { ai.items = MXMLDataInterpreter.generateMXMLArray(ai.document, null, ai.itemsDescriptor); } for each (var item:DisplayObject in ai.items) { var parent:IParent = ai.document as IParent; if (ai.destination != null) parent = parent[ai.destination] as IParent; if (ai.relativeTo != null) { var index:int = parent.numElements; if (ai.relativeTo != null) { var child:Object = ai.document[ai.relativeTo]; index = parent.getElementIndex(child); if (ai.position == "after") index++; } parent.addElementAt(item, index); } else { parent.addElement(item); } } if (parent is IContainer) IContainer(parent).childrenAdded(); } else if (o is SetProperty) { var sp:SetProperty = SetProperty(o); if (sp.target != null) { sp.previousValue = sp.document[sp.target][sp.name]; sp.document[sp.target][sp.name] = sp.value; } else { sp.previousValue = sp.document[sp.name]; sp.document[sp.name] = sp.value; } } } } } }
handle state vars on the top tag
handle state vars on the top tag
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
1b4fa9af28fdaa6a7b32dfab32ba14706d351630
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 = 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; } } }
/** * 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 - 2, offsetY, rowCount - 2 ); 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 homes
fix homes
ActionScript
apache-2.0
goc-flashplusplus/ageofai
de1e6cba8e2262312a0e4bce2bb889cdd8906d0f
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMP2PESVideo.as
HLSPlugin/src/org/denivip/osmf/net/httpstreaming/hls/HTTPStreamingMP2PESVideo.as
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.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 the at.matthew.httpstreaming package. * * The Initial Developer of the Original Code is * Matthew Kaufman. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ package org.denivip.osmf.net.httpstreaming.hls { import flash.utils.ByteArray; import org.osmf.logging.Log; import org.osmf.logging.Logger; import org.osmf.net.httpstreaming.flv.FLVTagVideo; internal class HTTPStreamingMP2PESVideo extends HTTPStreamingMP2PESBase { private var _nalData:ByteArray; private var _vTag:FLVTagVideo; private var _vTagData:ByteArray; private var _scState:int; private var spsNAL:HTTPStreamingH264NALU = null; private var ppsNAL:HTTPStreamingH264NALU = null; public function HTTPStreamingMP2PESVideo() { _scState = 0; _nalData = new ByteArray(); _vTag = null; _vTagData = null; } override public function processES(pusi:Boolean, packet:ByteArray, flush:Boolean = false): ByteArray { if(pusi) { // start of a new PES packet var startCode:uint = packet.readUnsignedInt(); if(startCode != 0x1e0 && startCode != 0x1ea && startCode != 0x1bd) { throw new Error("PES start code not found or not AAC/AVC"); } // Ignore packet length and marker bits. packet.position += 3; // Need PTS and DTS var flags:uint = (packet.readUnsignedByte() & 0xc0) >> 6; CONFIG::LOGGING { if(flags != 0x03) { logger.warn("video PES packet without DTS"); } } if(flags != 0x03 && flags != 0x02 && flags != 0x00) { throw new Error("video PES packet without PTS cannot be decoded"); } // Check PES header length var length:uint = packet.readUnsignedByte(); var pts:Number = uint((packet.readUnsignedByte() & 0x0e) << 29) + uint((packet.readUnsignedShort() & 0xfffe) << 14) + uint((packet.readUnsignedShort() & 0xfffe) >> 1); length -= 5; var timestamp:Number; if(flags == 0x03) { var dts:Number = ((packet.readUnsignedByte() & 0x0e) << 29) + ((packet.readUnsignedShort() & 0xfffe) << 14) + ((packet.readUnsignedShort() & 0xfffe) >> 1); timestamp = Math.round(dts/90); _compositionTime = Math.round(pts/90) - timestamp; length -= 5; } else { timestamp = Math.round(pts/90); _compositionTime = 0; } if(!_timestampReseted) { _offset += timestamp - _prevTimestamp; } if (_isDiscontunity || (!_streamOffsetSet)) {// && _prevTimestamp == 0)) { -- in most cases _prevTimestamp (like any timestamps in stream) can't be 0. /*if(timestamp > 0) { _offset += timestamp; }*/ _timestamp = _initialTimestamp; _streamOffsetSet = true; }else{ _timestamp = _initialTimestamp + _offset; } _prevTimestamp = timestamp; _timestampReseted = false; _isDiscontunity = false; // Skip other header data. packet.position += length; } if(!flush) var dStart:uint = packet.position; // assume that the copy will be from start-of-data var nals:Vector.<HTTPStreamingH264NALU> = new Vector.<HTTPStreamingH264NALU>; var nal:HTTPStreamingH264NALU; if(flush) { nal = new HTTPStreamingH264NALU(_nalData); // full length to end, don't need to trim last 3 bytes if(nal.NALtype != 0) { nals.push(nal); // could inline this (see below) CONFIG::LOGGING { logger.info("pushed one flush nal of type "+nal.NALtype.toString()); } } _nalData = new ByteArray(); } else while(packet.bytesAvailable > 0) { var value:uint = packet.readUnsignedByte(); // finding only 3-byte start codes is ok as trailing zeros are ignored in most (all?) cases switch(_scState) { case 0: if(value == 0x00) _scState = 1; break; case 1: if(value == 0x00) _scState = 2; else _scState = 0; break; case 2: if(value == 0x00) // more than 2 zeros... no problem { // state stays at 2 break; } else if(value == 0x01) { // perf _nalData.writeBytes(packet, dStart, packet.position-dStart); dStart = packet.position; // at this point we have the NAL data plus the *next* start code in _nalData // unless there was no previous NAL in which case _nalData is either empty or has the leading zeros, if any if(_nalData.length > 4) // require >1 byte of payload { _nalData.length -= 3; // trim off the 0 0 1 (might be one more zero, but in H.264 that's ok) nal = new HTTPStreamingH264NALU(_nalData); if(nal.NALtype != 0) { nals.push(nal); // could inline this as well, rather than stacking and processing later in the function } } else { CONFIG::LOGGING { logger.warn("length too short! = " + _nalData.length.toString()); } } _nalData = new ByteArray(); // and start collecting into the next one _scState = 0; // got one, now go back to looking break; } else { _scState = 0; // go back to looking break; } // notreached break; default: // shouldn't ever get here _scState = 0; break; } // switch _scState } // while bytesAvailable if(!flush && packet.position-dStart > 0) _nalData.writeBytes(packet, dStart, packet.position-dStart); // find SPS + PPS if we can for each(nal in nals) { switch(nal.NALtype) { case 7: spsNAL = nal; break; case 8: ppsNAL = nal; break; default: break; } } var tags:Vector.<FLVTagVideo> = new Vector.<FLVTagVideo>; var tag:FLVTagVideo; var avccTag:FLVTagVideo = null; var avcc:ByteArray = new ByteArray(); // note that this breaks if the sps and pps are in different segments that we process if(spsNAL && ppsNAL) { var spsLength:Number = spsNAL.length; var ppsLength:Number = ppsNAL.length; tag = new FLVTagVideo(); tag.timestamp = _timestamp; tag.codecID = FLVTagVideo.CODEC_ID_AVC; tag.frameType = FLVTagVideo.FRAME_TYPE_KEYFRAME; tag.avcPacketType = FLVTagVideo.AVC_PACKET_TYPE_SEQUENCE_HEADER; avcc.writeByte(0x01); // avcC version 1 // profile, compatibility, level avcc.writeBytes(spsNAL.NALdata, 1, 3); avcc.writeByte(0xff); // 111111 + 2 bit NAL size - 1 avcc.writeByte(0xe1); // number of SPS avcc.writeByte(spsLength >> 8); // 16-bit SPS byte count avcc.writeByte(spsLength); avcc.writeBytes(spsNAL.NALdata, 0, spsLength); // the SPS avcc.writeByte(0x01); // number of PPS avcc.writeByte(ppsLength >> 8); // 16-bit PPS byte count avcc.writeByte(ppsLength); avcc.writeBytes(ppsNAL.NALdata, 0, ppsLength); tag.data = avcc; tags.push(tag); avccTag = tag; spsNAL = null; ppsNAL = null; } for each(nal in nals) { if(nal.NALtype == 9) // AUD - should read the flags in here too, perhaps { // close the last _vTag and start a new one if(_vTag && _vTagData.length == 0){ ; // warnings =| CONFIG::LOGGING { logger.warn("zero-length vtag"); // can't happen if we are writing the AUDs in if(avccTag) logger.info(" avccts "+avccTag.timestamp.toString()+" vtagts "+_vTag.timestamp.toString()); } } if(_vTag && _vTagData.length > 0) { _vTag.data = _vTagData; // set at end (see below) tags.push(_vTag); if(avccTag) { avccTag.timestamp = _vTag.timestamp; avccTag = null; } } _vTag = new FLVTagVideo(); _vTagData = new ByteArray(); // we assemble the nalus outside, set at end _vTagData.writeUnsignedInt(nal.length); _vTagData.writeBytes(nal.NALdata); // start with this very NAL, an AUD (XXX not sure this is needed) _vTag.codecID = FLVTagVideo.CODEC_ID_AVC; _vTag.frameType = FLVTagVideo.FRAME_TYPE_INTER; // adjust to keyframe later _vTag.avcPacketType = FLVTagVideo.AVC_PACKET_TYPE_NALU; _vTag.timestamp = _timestamp; _vTag.avcCompositionTimeOffset = _compositionTime; } else if(nal.NALtype != 7 && nal.NALtype != 8) { if(_vTag == null) { CONFIG::LOGGING { logger.info("needed to create vtag"); } _vTag = new FLVTagVideo(); _vTagData = new ByteArray(); // we assemble the nalus outside, set at end _vTag.codecID = FLVTagVideo.CODEC_ID_AVC; _vTag.frameType = FLVTagVideo.FRAME_TYPE_INTER; // adjust to keyframe later _vTag.avcPacketType = FLVTagVideo.AVC_PACKET_TYPE_NALU; _vTag.timestamp = _timestamp; _vTag.avcCompositionTimeOffset = _compositionTime; } if(nal.NALtype == 5) // if keyframe { _vTag.frameType = FLVTagVideo.FRAME_TYPE_KEYFRAME; } _vTagData.writeUnsignedInt(nal.length); _vTagData.writeBytes(nal.NALdata); } } if(flush) { CONFIG::LOGGING { logger.info(" *** VIDEO FLUSH CALLED"); } if(_vTag && _vTagData.length > 0) { _vTag.data = _vTagData; // set at end (see below) tags.push(_vTag); if(avccTag) { avccTag.timestamp = _vTag.timestamp; avccTag = null; } CONFIG::LOGGING { logger.info("flushing one vtag"); } } _vTag = null; // can't start new one, don't have the info } var tagData:ByteArray = new ByteArray(); for each(tag in tags) { tag.write(tagData); } return tagData; } CONFIG::LOGGING { private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMP2PESVideo') as Logger; } } // class } // package
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.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 the at.matthew.httpstreaming package. * * The Initial Developer of the Original Code is * Matthew Kaufman. * Portions created by the Initial Developer are Copyright (C) 2011 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ package org.denivip.osmf.net.httpstreaming.hls { import flash.utils.ByteArray; import org.osmf.logging.Log; import org.osmf.logging.Logger; import org.osmf.net.httpstreaming.flv.FLVTagVideo; internal class HTTPStreamingMP2PESVideo extends HTTPStreamingMP2PESBase { private var _nalData:ByteArray; private var _vTag:FLVTagVideo; private var _vTagData:ByteArray; private var _scState:int; private var spsNAL:HTTPStreamingH264NALU = null; private var ppsNAL:HTTPStreamingH264NALU = null; public function HTTPStreamingMP2PESVideo() { _scState = 0; _nalData = new ByteArray(); _vTag = null; _vTagData = null; } override public function processES(pusi:Boolean, packet:ByteArray, flush:Boolean = false): ByteArray { if(pusi) { // start of a new PES packet var startCode:uint = packet.readUnsignedInt(); if(startCode != 0x1e0 && startCode != 0x1ea && startCode != 0x1bd) { throw new Error("PES start code not found or not AAC/AVC"); } // Ignore packet length and marker bits. packet.position += 3; // Need PTS and DTS var flags:uint = (packet.readUnsignedByte() & 0xc0) >> 6; CONFIG::LOGGING { if(flags != 0x03) { logger.warn("video PES packet without DTS"); } } if(flags != 0x03 && flags != 0x02 && flags != 0x00) { throw new Error("video PES packet without PTS cannot be decoded"); } // Check PES header length var length:uint = packet.readUnsignedByte(); var pts:Number = uint((packet.readUnsignedByte() & 0x0e) << 29) + uint((packet.readUnsignedShort() & 0xfffe) << 14) + uint((packet.readUnsignedShort() & 0xfffe) >> 1); length -= 5; var timestamp:Number; if(flags == 0x03) { var dts:Number = uint((packet.readUnsignedByte() & 0x0e) << 29) + uint((packet.readUnsignedShort() & 0xfffe) << 14) + uint((packet.readUnsignedShort() & 0xfffe) >> 1); timestamp = Math.round(dts/90); _compositionTime = Math.round(pts/90) - timestamp; length -= 5; } else { timestamp = Math.round(pts/90); _compositionTime = 0; } if(!_timestampReseted) { _offset += timestamp - _prevTimestamp; } if (_isDiscontunity || (!_streamOffsetSet)) {// && _prevTimestamp == 0)) { -- in most cases _prevTimestamp (like any timestamps in stream) can't be 0. /*if(timestamp > 0) { _offset += timestamp; }*/ _timestamp = _initialTimestamp; _streamOffsetSet = true; }else{ _timestamp = _initialTimestamp + _offset; } _prevTimestamp = timestamp; _timestampReseted = false; _isDiscontunity = false; // Skip other header data. packet.position += length; } if(!flush) var dStart:uint = packet.position; // assume that the copy will be from start-of-data var nals:Vector.<HTTPStreamingH264NALU> = new Vector.<HTTPStreamingH264NALU>; var nal:HTTPStreamingH264NALU; if(flush) { nal = new HTTPStreamingH264NALU(_nalData); // full length to end, don't need to trim last 3 bytes if(nal.NALtype != 0) { nals.push(nal); // could inline this (see below) CONFIG::LOGGING { logger.info("pushed one flush nal of type "+nal.NALtype.toString()); } } _nalData = new ByteArray(); } else while(packet.bytesAvailable > 0) { var value:uint = packet.readUnsignedByte(); // finding only 3-byte start codes is ok as trailing zeros are ignored in most (all?) cases switch(_scState) { case 0: if(value == 0x00) _scState = 1; break; case 1: if(value == 0x00) _scState = 2; else _scState = 0; break; case 2: if(value == 0x00) // more than 2 zeros... no problem { // state stays at 2 break; } else if(value == 0x01) { // perf _nalData.writeBytes(packet, dStart, packet.position-dStart); dStart = packet.position; // at this point we have the NAL data plus the *next* start code in _nalData // unless there was no previous NAL in which case _nalData is either empty or has the leading zeros, if any if(_nalData.length > 4) // require >1 byte of payload { _nalData.length -= 3; // trim off the 0 0 1 (might be one more zero, but in H.264 that's ok) nal = new HTTPStreamingH264NALU(_nalData); if(nal.NALtype != 0) { nals.push(nal); // could inline this as well, rather than stacking and processing later in the function } } else { CONFIG::LOGGING { logger.warn("length too short! = " + _nalData.length.toString()); } } _nalData = new ByteArray(); // and start collecting into the next one _scState = 0; // got one, now go back to looking break; } else { _scState = 0; // go back to looking break; } // notreached break; default: // shouldn't ever get here _scState = 0; break; } // switch _scState } // while bytesAvailable if(!flush && packet.position-dStart > 0) _nalData.writeBytes(packet, dStart, packet.position-dStart); // find SPS + PPS if we can for each(nal in nals) { switch(nal.NALtype) { case 7: spsNAL = nal; break; case 8: ppsNAL = nal; break; default: break; } } var tags:Vector.<FLVTagVideo> = new Vector.<FLVTagVideo>; var tag:FLVTagVideo; var avccTag:FLVTagVideo = null; var avcc:ByteArray = new ByteArray(); // note that this breaks if the sps and pps are in different segments that we process if(spsNAL && ppsNAL) { var spsLength:Number = spsNAL.length; var ppsLength:Number = ppsNAL.length; tag = new FLVTagVideo(); tag.timestamp = _timestamp; tag.codecID = FLVTagVideo.CODEC_ID_AVC; tag.frameType = FLVTagVideo.FRAME_TYPE_KEYFRAME; tag.avcPacketType = FLVTagVideo.AVC_PACKET_TYPE_SEQUENCE_HEADER; avcc.writeByte(0x01); // avcC version 1 // profile, compatibility, level avcc.writeBytes(spsNAL.NALdata, 1, 3); avcc.writeByte(0xff); // 111111 + 2 bit NAL size - 1 avcc.writeByte(0xe1); // number of SPS avcc.writeByte(spsLength >> 8); // 16-bit SPS byte count avcc.writeByte(spsLength); avcc.writeBytes(spsNAL.NALdata, 0, spsLength); // the SPS avcc.writeByte(0x01); // number of PPS avcc.writeByte(ppsLength >> 8); // 16-bit PPS byte count avcc.writeByte(ppsLength); avcc.writeBytes(ppsNAL.NALdata, 0, ppsLength); tag.data = avcc; tags.push(tag); avccTag = tag; spsNAL = null; ppsNAL = null; } for each(nal in nals) { if(nal.NALtype == 9) // AUD - should read the flags in here too, perhaps { // close the last _vTag and start a new one if(_vTag && _vTagData.length == 0){ ; // warnings =| CONFIG::LOGGING { logger.warn("zero-length vtag"); // can't happen if we are writing the AUDs in if(avccTag) logger.info(" avccts "+avccTag.timestamp.toString()+" vtagts "+_vTag.timestamp.toString()); } } if(_vTag && _vTagData.length > 0) { _vTag.data = _vTagData; // set at end (see below) tags.push(_vTag); if(avccTag) { avccTag.timestamp = _vTag.timestamp; avccTag = null; } } _vTag = new FLVTagVideo(); _vTagData = new ByteArray(); // we assemble the nalus outside, set at end _vTagData.writeUnsignedInt(nal.length); _vTagData.writeBytes(nal.NALdata); // start with this very NAL, an AUD (XXX not sure this is needed) _vTag.codecID = FLVTagVideo.CODEC_ID_AVC; _vTag.frameType = FLVTagVideo.FRAME_TYPE_INTER; // adjust to keyframe later _vTag.avcPacketType = FLVTagVideo.AVC_PACKET_TYPE_NALU; _vTag.timestamp = _timestamp; _vTag.avcCompositionTimeOffset = _compositionTime; } else if(nal.NALtype != 7 && nal.NALtype != 8) { if(_vTag == null) { CONFIG::LOGGING { logger.info("needed to create vtag"); } _vTag = new FLVTagVideo(); _vTagData = new ByteArray(); // we assemble the nalus outside, set at end _vTag.codecID = FLVTagVideo.CODEC_ID_AVC; _vTag.frameType = FLVTagVideo.FRAME_TYPE_INTER; // adjust to keyframe later _vTag.avcPacketType = FLVTagVideo.AVC_PACKET_TYPE_NALU; _vTag.timestamp = _timestamp; _vTag.avcCompositionTimeOffset = _compositionTime; } if(nal.NALtype == 5) // if keyframe { _vTag.frameType = FLVTagVideo.FRAME_TYPE_KEYFRAME; } _vTagData.writeUnsignedInt(nal.length); _vTagData.writeBytes(nal.NALdata); } } if(flush) { CONFIG::LOGGING { logger.info(" *** VIDEO FLUSH CALLED"); } if(_vTag && _vTagData.length > 0) { _vTag.data = _vTagData; // set at end (see below) tags.push(_vTag); if(avccTag) { avccTag.timestamp = _vTag.timestamp; avccTag = null; } CONFIG::LOGGING { logger.info("flushing one vtag"); } } _vTag = null; // can't start new one, don't have the info } var tagData:ByteArray = new ByteArray(); for each(tag in tags) { tag.write(tagData); } return tagData; } CONFIG::LOGGING { private var logger:Logger = Log.getLogger('org.denivip.osmf.net.httpstreaming.hls.HTTPStreamingMP2PESVideo') as Logger; } } // class } // package
Update HTTPStreamingMP2PESVideo.as
Update HTTPStreamingMP2PESVideo.as
ActionScript
isc
denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,denivip/osmf-hls-plugin,mruse/osmf-hls-plugin
07ee6c4a7659d26f770fe4627bf11b1bfc334485
flash/org/windmill/Windmill.as
flash/org/windmill/Windmill.as
/* Copyright 2009, Matthew Eernisse ([email protected]) and Slide, 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. */ package org.windmill { // FIXME: // Relying on implicit imports of org.windmill.* // to avoid infinite recursion in build script import flash.utils.*; import mx.core.Application; import flash.display.Stage; import flash.display.DisplayObject; import flash.external.ExternalInterface; public class Windmill { public static var context:*; // A reference to the Stage public static var controllerMethods:Array = []; public static var assertMethods:Array = []; public static var packages:Object = { controller: { // Ref to the namespace, since you can't // do it via string lookup packageRef: org.windmill.WMController, // Gets filled with the list of public methods -- // used to generate the wrapped methods exposed // via ExternalInterface methodNames: [] }, assert: { packageRef: org.windmill.WMAssert, methodNames: [] } }; public function Windmill():void {} // Initializes the Windmill Flash code // 1. Saves a reference to the stage in 'context' // this is the equivalent of the window obj in // Windmill's JS impl. See WMLocator to see how // it's used // 2. Does some introspection/metaprogramming to // expose all the public methods in WMController // and WMAsserts through the ExternalInterface // as wrapped functions that return either the // Boolean true, or the Error object if an error // happens (as in the case of all failed tests) // 3. Exposes the start/stop method of WMExplorer // to turn on and off the explorer public static function init(config:Object):void { var methodName:String; var item:*; var descr:XML; // Returns a wrapped version of the method that returns // the Error obj to JS-land instead of actually throwing var genExtFunc:Function = function (func:Function):Function { return function (...args):* { try { return func.apply(null, args); } catch (e:Error) { return e; } } } // A reference to the Stage // ---------------- if (!(config.context is Stage || config.context is Application)) { throw new Error('Windmill.context must be a reference to the Application or Stage.'); } context = config.context; // Expose controller and assert methods // ---------------- for (var key:String in packages) { // Introspect all the public packages // to expose via ExternalInterface descr = flash.utils.describeType( packages[key].packageRef); for each (item in descr..method) { packages[key].methodNames.push([email protected]()); } // Expose public packages via ExternalInterface // 'dragDropOnCoords' becomes 'wm_dragDropOnCoords' // The exposed method is wrapped in a try/catch // that returns the Error obj to JS instead of throwing for each (methodName in packages[key].methodNames) { ExternalInterface.addCallback('wm_' + methodName, genExtFunc(packages[key].packageRef[methodName])); } } // Other misc ExternalInterface methods var miscMethods:Object = { explorerStart: WMExplorer.start, explorerStop: WMExplorer.stop, recorderStart: WMRecorder.start, recorderStop: WMRecorder.stop } // Don't care what order these happen in for (methodName in miscMethods) { ExternalInterface.addCallback('wm_' + methodName, genExtFunc(miscMethods[methodName])); } } public static function getStage():Stage { var context:* = Windmill.context; var stage:Stage; if (context is Application) { stage = context.stage; } else if (context is Stage) { stage = context; } else { throw new Error('Windmill.context must be a reference to an Application or Stage.' + ' Perhaps Windmill.init has not run yet.'); } return stage; } public static function getTopLevel():DisplayObject { var topLevel:*; var context:* = Windmill.context; if (context is Application) { topLevel = context.parent; } else if (context is Stage) { topLevel = context; } else { throw new Error('Windmill.context must be a reference to an Application or Stage.' + ' Perhaps Windmill.init has not run yet.'); } return topLevel; } } }
/* Copyright 2009, Matthew Eernisse ([email protected]) and Slide, 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. */ package org.windmill { // FIXME: // Relying on implicit imports of org.windmill.* // to avoid infinite recursion in build script import flash.utils.*; import mx.core.Application; import flash.display.Sprite; import flash.display.Stage; import flash.display.DisplayObject; import flash.external.ExternalInterface; public class Windmill extends Sprite { public static var context:*; // A reference to the Stage public static var controllerMethods:Array = []; public static var assertMethods:Array = []; public static var packages:Object = { controller: { // Ref to the namespace, since you can't // do it via string lookup packageRef: org.windmill.WMController, // Gets filled with the list of public methods -- // used to generate the wrapped methods exposed // via ExternalInterface methodNames: [] }, assert: { packageRef: org.windmill.WMAssert, methodNames: [] } }; public function Windmill():void {} // Initializes the Windmill Flash code // 1. Saves a reference to the stage in 'context' // this is the equivalent of the window obj in // Windmill's JS impl. See WMLocator to see how // it's used // 2. Does some introspection/metaprogramming to // expose all the public methods in WMController // and WMAsserts through the ExternalInterface // as wrapped functions that return either the // Boolean true, or the Error object if an error // happens (as in the case of all failed tests) // 3. Exposes the start/stop method of WMExplorer // to turn on and off the explorer public static function init(config:Object):void { var methodName:String; var item:*; var descr:XML; // Returns a wrapped version of the method that returns // the Error obj to JS-land instead of actually throwing var genExtFunc:Function = function (func:Function):Function { return function (...args):* { try { return func.apply(null, args); } catch (e:Error) { return e; } } } // A reference to the Stage // ---------------- if (!(config.context is Stage || config.context is Application)) { throw new Error('Windmill.context must be a reference to the Application or Stage.'); } context = config.context; // Expose controller and assert methods // ---------------- for (var key:String in packages) { // Introspect all the public packages // to expose via ExternalInterface descr = flash.utils.describeType( packages[key].packageRef); for each (item in descr..method) { packages[key].methodNames.push([email protected]()); } // Expose public packages via ExternalInterface // 'dragDropOnCoords' becomes 'wm_dragDropOnCoords' // The exposed method is wrapped in a try/catch // that returns the Error obj to JS instead of throwing for each (methodName in packages[key].methodNames) { ExternalInterface.addCallback('wm_' + methodName, genExtFunc(packages[key].packageRef[methodName])); } } // Other misc ExternalInterface methods var miscMethods:Object = { explorerStart: WMExplorer.start, explorerStop: WMExplorer.stop, recorderStart: WMRecorder.start, recorderStop: WMRecorder.stop } // Don't care what order these happen in for (methodName in miscMethods) { ExternalInterface.addCallback('wm_' + methodName, genExtFunc(miscMethods[methodName])); } } public static function getStage():Stage { var context:* = Windmill.context; var stage:Stage; if (context is Application) { stage = context.stage; } else if (context is Stage) { stage = context; } else { throw new Error('Windmill.context must be a reference to an Application or Stage.' + ' Perhaps Windmill.init has not run yet.'); } return stage; } public static function getTopLevel():DisplayObject { var topLevel:*; var context:* = Windmill.context; if (context is Application) { topLevel = context.parent; } else if (context is Stage) { topLevel = context; } else { throw new Error('Windmill.context must be a reference to an Application or Stage.' + ' Perhaps Windmill.init has not run yet.'); } return topLevel; } } }
Make Windmill base lib a subclass of Sprite so it can be dynamically loaded.
Make Windmill base lib a subclass of Sprite so it can be dynamically loaded.
ActionScript
apache-2.0
windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill
9a9d12974e14ae89c481908e0620b1ae2b3810cd
dolly-framework/src/test/actionscript/dolly/CopyingOfCompositeCopyableClassTest.as
dolly-framework/src/test/actionscript/dolly/CopyingOfCompositeCopyableClassTest.as
package dolly { import dolly.core.dolly_internal; import dolly.data.CompositeCopyableClass; import mx.collections.ArrayCollection; import mx.collections.ArrayList; import org.as3commons.reflect.Field; import org.as3commons.reflect.Type; import org.flexunit.asserts.assertEquals; import org.flexunit.asserts.assertNotNull; use namespace dolly_internal; public class CopyingOfCompositeCopyableClassTest { private var compositeCopyableClass:CompositeCopyableClass; private var compositeCopyableClassType:Type; [Before] public function before():void { compositeCopyableClass = new CompositeCopyableClass(); compositeCopyableClass.array = [1, 2, 3, 4, 5]; compositeCopyableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]); compositeCopyableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]); compositeCopyableClassType = Type.forInstance(compositeCopyableClass); } [After] public function after():void { compositeCopyableClass = null; compositeCopyableClassType = null; } [Test] public function findingAllWritableFieldsForType():void { const writableFields:Vector.<Field> = Copier.findCopyableFieldsForType(compositeCopyableClassType); assertNotNull(writableFields); assertEquals(4, writableFields.length); } } }
package dolly { import dolly.core.dolly_internal; import dolly.data.CompositeCopyableClass; import mx.collections.ArrayCollection; import mx.collections.ArrayList; 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; import org.hamcrest.assertThat; import org.hamcrest.collection.array; import org.hamcrest.collection.arrayWithSize; import org.hamcrest.collection.everyItem; import org.hamcrest.core.isA; import org.hamcrest.object.equalTo; use namespace dolly_internal; public class CopyingOfCompositeCopyableClassTest { private var compositeCopyableClass:CompositeCopyableClass; private var compositeCopyableClassType:Type; [Before] public function before():void { compositeCopyableClass = new CompositeCopyableClass(); compositeCopyableClass.array = [1, 2, 3, 4, 5]; compositeCopyableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]); compositeCopyableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]); compositeCopyableClassType = Type.forInstance(compositeCopyableClass); } [After] public function after():void { compositeCopyableClass = null; compositeCopyableClassType = null; } [Test] public function findingAllWritableFieldsForType():void { const writableFields:Vector.<Field> = Copier.findCopyableFieldsForType(compositeCopyableClassType); assertNotNull(writableFields); assertEquals(4, writableFields.length); } [Test] public function copyingOfArray():void { const copy:CompositeCopyableClass = Copier.copy(compositeCopyableClass); assertNotNull(copy.array); assertThat(copy.array, arrayWithSize(5)); assertThat(copy.array, compositeCopyableClass.array); assertFalse(copy.array == compositeCopyableClass.array); assertThat(copy.array, everyItem(isA(Number))); assertThat(copy.array, array(equalTo(1), equalTo(2), equalTo(3), equalTo(4), equalTo(5))); } } }
Test for copying Array in CompositeCloneableClass.
Test for copying Array in CompositeCloneableClass.
ActionScript
mit
Yarovoy/dolly
4c547bbd560bc867ec76fdba7c3b689b13cf8536
test/src/FRESteamWorksTest.as
test/src/FRESteamWorksTest.as
package { import com.amanitadesign.steam.FRESteamWorks; import com.amanitadesign.steam.SteamConstants; import com.amanitadesign.steam.SteamEvent; import flash.desktop.NativeApplication; import flash.display.SimpleButton; import flash.display.Sprite; 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; public function FRESteamWorksTest() { tf = new TextField(); tf.width = stage.stageWidth; tf.height = stage.stageHeight; addChild(tf); tf.addEventListener(MouseEvent.MOUSE_DOWN, onClick); Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit); try { if(Steamworks.init()){ log("STEAMWORKS API is available\n"); //comment.. current stats and achievement ids are from steam example app which is provided with their SDK 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')); log("setCloudEnabledForApp(false) == "+Steamworks.setCloudEnabledForApp(false) ); log("setCloudEnabledForApp(true) == "+Steamworks.setCloudEnabledForApp(true) ); log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() ); log("getFileCount() == "+Steamworks.getFileCount() ); log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') ); //comment.. writing to app with id 480 is somehow not working, but works with our real appId log("writeFileToCloud('test.txt','hello steam') == "+writeFileToCloud('test.txt','hello steam')); log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); //----------- //Steamworks.requestStats(); Steamworks.resetAllStats(true); }else { tf.appendText("STEAMWORKS API is NOT available\n"); } } catch(e:Error) { tf.appendText("*** ERROR ***"); tf.appendText(e.message); } } 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; } public function onClick(e:MouseEvent):void{ log("--click--"); if(Steamworks.isReady){ if(!Steamworks.isAchievement("ACH_WIN_ONE_GAME")) { 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")); } if(Steamworks.fileExists('test.txt')){ log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); log("Steamworks.fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt')); } else { log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click')); } //Steamworks.storeStats(); } else { log("not able to set achievement\n"); } } public 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; default: log("STEAMresponse type:"+e.req_type+" response:"+e.response); } } public function onExit(e:Event):void{ log("Exiting application, cleaning up"); Steamworks.dispose(); } } }
package { import com.amanitadesign.steam.FRESteamWorks; import com.amanitadesign.steam.SteamConstants; import com.amanitadesign.steam.SteamEvent; import flash.desktop.NativeApplication; import flash.display.SimpleButton; import flash.display.Sprite; 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; public function FRESteamWorksTest() { tf = new TextField(); tf.width = stage.stageWidth; tf.height = stage.stageHeight; addChild(tf); tf.addEventListener(MouseEvent.MOUSE_DOWN, onClick); Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse); NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit); try { if(Steamworks.init()){ log("STEAMWORKS API is available\n"); //comment.. current stats and achievement ids are from steam example app which is provided with their SDK 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')); log("setCloudEnabledForApp(false) == "+Steamworks.setCloudEnabledForApp(false) ); log("setCloudEnabledForApp(true) == "+Steamworks.setCloudEnabledForApp(true) ); log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp() ); log("getFileCount() == "+Steamworks.getFileCount() ); log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt') ); //comment.. writing to app with id 480 is somehow not working, but works with our real appId log("writeFileToCloud('test.txt','hello steam') == "+writeFileToCloud('test.txt','hello steam')); log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); //----------- //Steamworks.requestStats(); Steamworks.resetAllStats(true); }else { tf.appendText("STEAMWORKS API is NOT available\n"); } } catch(e:Error) { tf.appendText("*** ERROR ***"); tf.appendText(e.message + "\n"); tf.appendText(e.getStackTrace() + "\n"); } } 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; } public function onClick(e:MouseEvent):void{ log("--click--"); if(Steamworks.isReady){ if(!Steamworks.isAchievement("ACH_WIN_ONE_GAME")) { 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")); } if(Steamworks.fileExists('test.txt')){ log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') ); log("Steamworks.fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt')); } else { log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click')); } //Steamworks.storeStats(); } else { log("not able to set achievement\n"); } } public 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; default: log("STEAMresponse type:"+e.req_type+" response:"+e.response); } } public function onExit(e:Event):void{ log("Exiting application, cleaning up"); Steamworks.dispose(); } } }
Print stack trace when error occurs in test program
Print stack trace when error occurs in test program
ActionScript
bsd-2-clause
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
f99d82230c53445d94e5f313f549d8a21111aac1
actionscript/src/com/freshplanet/ane/AirAACPlayer/AirAACPlayer.as
actionscript/src/com/freshplanet/ane/AirAACPlayer/AirAACPlayer.as
////////////////////////////////////////////////////////////////////////////////////// // // Copyright 2012 Freshplanet (http://freshplanet.com | [email protected]) // // 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.freshplanet.ane.AirAACPlayer { import flash.events.Event; import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirAACPlayer extends EventDispatcher { // --------------------------------------------------------------------------------------// // // // PUBLIC API // // // // --------------------------------------------------------------------------------------// public static const AAC_PLAYER_PREPARED:String = "AAC_PLAYER_PREPARED"; /** AirAACPlayer is supported on Android devices. */ public static function get isSupported():Boolean { var isAndroid:Boolean = (Capabilities.manufacturer.indexOf("Android") != -1) return isAndroid; } public function AirAACPlayer() { _context = ExtensionContext.createExtensionContext(EXTENSION_ID, null); if (!_context) { log("ERROR - Extension context is null. Please check if extension.xml is setup correctly."); return; } _context.addEventListener(StatusEvent.STATUS, onStatus); } public var logEnabled:Boolean = true; /** * Load a music stream url * @param url:String */ public function loadUrl(url:String):void { _context.call("loadUrl", url); } /** * Start playing the stream. * If the playback has been paused before, it will continue from this point. * @param startTime:int the start time in milliseconds */ public function play(startTime:int=0):void { _context.call("play", startTime); } /** * Pause the playback */ public function pause():void { _context.call("pause"); } /** * Stop the playback */ public function stop():void { _context.call("stop"); } /** * Close the stream and release. * Note that loadUrl() has to be called again before replaying if close has been called. */ public function close():void { _context.call("close"); } /** * Length in milliseconds */ public function get length():int { return _context.call("getLength") as int; } /** * Progress in milliseconds */ public function get progress():int { return _context.call("getProgress") as int; } // --------------------------------------------------------------------------------------// // // // PRIVATE API // // // // --------------------------------------------------------------------------------------// private static const EXTENSION_ID:String = "com.freshplanet.AirAACPlayer"; private static var _instance:AirAACPlayer; private var _context:ExtensionContext; private function onStatus( event:StatusEvent ):void { if (event.code == "LOGGING") // Simple log message { log(event.level); } else if (event.code == AAC_PLAYER_PREPARED) { dispatchEvent(new Event(event.code)); } } private function log( message:String ):void { if (logEnabled) trace("[AirAACPlayer] " + message); } } }
////////////////////////////////////////////////////////////////////////////////////// // // Copyright 2012 Freshplanet (http://freshplanet.com | [email protected]) // // 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.freshplanet.ane.AirAACPlayer { import flash.events.Event; import flash.events.EventDispatcher; import flash.events.StatusEvent; import flash.external.ExtensionContext; import flash.system.Capabilities; public class AirAACPlayer extends EventDispatcher { // --------------------------------------------------------------------------------------// // // // PUBLIC API // // // // --------------------------------------------------------------------------------------// public static const AAC_PLAYER_PREPARED:String = "AAC_PLAYER_PREPARED"; /** AirAACPlayer is supported on Android devices. */ public static function get isSupported():Boolean { var isAndroid:Boolean = (Capabilities.manufacturer.indexOf("Android") != -1) return isAndroid; } public function AirAACPlayer() { _context = ExtensionContext.createExtensionContext(EXTENSION_ID, null); if (!_context) { log("ERROR - Extension context is null. Please check if extension.xml is setup correctly."); return; } _context.addEventListener(StatusEvent.STATUS, onStatus); } public var logEnabled:Boolean = true; /** * Load a music stream url * @param url:String */ public function loadUrl(url:String):void { _context.call("loadUrl", url); } /** * Start playing the stream. * If the playback has been paused before, it will continue from this point. * @param startTime:int the start time in milliseconds */ public function play(startTime:int=0):void { _context.call("play", startTime); } /** * Pause the playback */ public function pause():void { _context.call("pause"); } /** * Stop the playback */ public function stop():void { _context.call("stop"); } /** * Close the stream and release. * Note that loadUrl() has to be called again before replaying if close has been called. */ public function close():void { _context.call("close"); } /** * Length in milliseconds */ public function get length():int { return _context.call("getLength") as int; } /** * Progress in milliseconds */ public function get progress():int { return _context.call("getProgress") as int; } // --------------------------------------------------------------------------------------// // // // PRIVATE API // // // // --------------------------------------------------------------------------------------// private static const EXTENSION_ID:String = "com.freshplanet.AirAACPlayer"; private var _context:ExtensionContext; private function onStatus( event:StatusEvent ):void { if (event.code == "LOGGING") // Simple log message { log(event.level); } else if (event.code == AAC_PLAYER_PREPARED) { dispatchEvent(new Event(event.code)); } } private function log( message:String ):void { if (logEnabled) trace("[AirAACPlayer] " + message); } } }
Remove instance property
Remove instance property
ActionScript
apache-2.0
freshplanet/ANE-AACPlayer,freshplanet/ANE-AACPlayer,freshplanet/ANE-AACPlayer
585774517c5ee419e69667a568173e20ada93c29
src/aerys/minko/render/shader/Shader.as
src/aerys/minko/render/shader/Shader.as
package aerys.minko.render.shader { import aerys.minko.ns.minko_render; import aerys.minko.ns.minko_shader; import aerys.minko.render.RenderTarget; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.shader.compiler.graph.ShaderGraph; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.part.ShaderPart; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import flash.utils.getQualifiedClassName; import aerys.minko.type.binding.Signature; import aerys.minko.render.ShaderDataBindingsProxy; use namespace minko_shader; /** * The base class to extend in order to create ActionScript shaders * and program the GPU using AS3. * * @author Jean-Marc Le Roux * @author Romain Gilliotte * * @see aerys.minko.render.shader.ShaderPart * @see aerys.minko.render.shader.ShaderInstance * @see aerys.minko.render.shader.ShaderSignature * @see aerys.minko.render.shader.ShaderDataBindings */ public class Shader extends ShaderPart { use namespace minko_shader; use namespace minko_render; minko_shader var _meshBindings : ShaderDataBindingsProxy = null; minko_shader var _sceneBindings : ShaderDataBindingsProxy = null; minko_shader var _kills : Vector.<AbstractNode> = new <AbstractNode>[]; private var _name : String = null; private var _enabled : Boolean = true; private var _defaultSettings : ShaderSettings = new ShaderSettings(null); private var _instances : Vector.<ShaderInstance> = new <ShaderInstance>[]; private var _numActiveInstances : uint = 0; private var _numRenderedInstances : uint = 0; private var _settings : Vector.<ShaderSettings> = new <ShaderSettings>[]; private var _programs : Vector.<Program3DResource> = new <Program3DResource>[]; private var _begin : Signal = new Signal('Shader.begin'); private var _end : Signal = new Signal('Shader.end'); /** * The name of the shader. Default value is the qualified name of the * ActionScript shader class (example: "aerys.minko.render.effect.basic::BasicShader"). * * @return * */ public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very first time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get begin() : Signal { return _begin; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very last time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get end() : Signal { return _end; } /** * Whether the shader (and all its forks) are enabled for rendering * or not. * * @return * */ public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } /** * * @param priority Default value is 0. * @param renderTarget Default value is null. * */ public function Shader(renderTarget : RenderTarget = null, priority : Number = 0.0) { super(this); _defaultSettings.renderTarget = renderTarget; _defaultSettings.priority = priority; _name = getQualifiedClassName(this); } public function fork(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderInstance { var pass : ShaderInstance = findPass(sceneBindings, meshBindings); if (!pass) { var signature : Signature = new Signature(); var config : ShaderSettings = findOrCreateSettings( sceneBindings, meshBindings ); signature.mergeWith(config.signature); var program : Program3DResource = null; if (config.enabled) { program = findOrCreateProgram(sceneBindings, meshBindings); signature.mergeWith(program.signature); } pass = new ShaderInstance(this, config, program, signature); pass.retained.add(shaderInstanceRetainedHandler); pass.released.add(shaderInstanceReleasedHandler); _instances.push(pass); } return pass; } public function disposeUnusedResources() : void { var numInstances : uint = _instances.length; var currentId : uint = 0; for (var instanceId : uint = 0; instanceId < numInstances; ++instanceId) { var passInstance : ShaderInstance = _instances[instanceId]; if (!passInstance.isDisposable) _instances[currentId++] = passInstance; } _instances.length = currentId; } /** * Override this method to initialize the settings * - such as the blending operands or the triangle culling - of the shader. * This values can be read from both the mesh and the scene bindings. * * @param settings * * @see aerys.minko.render.shader.ShaderSettings * */ protected function initializeSettings(settings : ShaderSettings) : void { // nothing } /** * The getVertexPosition() method is called to evaluate the vertex shader * program that shall be executed on the GPU. * * @return The position of the vertex in clip space (normalized screen space). * */ protected function getVertexPosition() : SFloat { throw new Error("The method 'getVertexPosition' must be implemented."); } /** * The getPixelColor() method is called to evaluate the fragment shader * program that shall be executed on the GPU. * * @return The color of the pixel on the screen. * */ protected function getPixelColor() : SFloat { throw new Error("The method 'getPixelColor' must be implemented."); } private function findPass(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderInstance { var numPasses : int = _instances.length; for (var passId : uint = 0; passId < numPasses; ++passId) if (_instances[passId].signature.isValid(sceneBindings, meshBindings)) return _instances[passId]; return null; } private function findOrCreateProgram(sceneBindings : DataBindings, meshBindings : DataBindings) : Program3DResource { var numPrograms : int = _programs.length; var program : Program3DResource; for (var programId : uint = 0; programId < numPrograms; ++programId) if (_programs[programId].signature.isValid(sceneBindings, meshBindings)) return _programs[programId]; var signature : Signature = new Signature(); _meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE); var vertexPosition : AbstractNode = getVertexPosition()._node; var pixelColor : AbstractNode = getPixelColor()._node; var shaderGraph : ShaderGraph = new ShaderGraph(vertexPosition, pixelColor, _kills); program = shaderGraph.generateProgram(_name, signature); _meshBindings = null; _sceneBindings = null; _kills.length = 0; _programs.push(program); return program; } private function findOrCreateSettings(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderSettings { var numConfigs : int = _settings.length; var config : ShaderSettings = null; for (var configId : int = 0; configId < numConfigs; ++configId) if (_settings[configId].signature.isValid(sceneBindings, meshBindings)) return _settings[configId]; var signature : Signature = new Signature(); config = _defaultSettings.clone(signature); _meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE); initializeSettings(config); _meshBindings = null; _sceneBindings = null; _settings.push(config); return config; } private function shaderInstanceRetainedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 1) { ++_numActiveInstances; instance.begin.add(shaderInstanceBeginHandler); instance.end.add(shaderInstanceEndHandler); } } private function shaderInstanceReleasedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 0) { --_numActiveInstances; instance.begin.remove(shaderInstanceBeginHandler); instance.end.remove(shaderInstanceEndHandler); } } private function shaderInstanceBeginHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { if (_numRenderedInstances == 0) _begin.execute(this, context, backBuffer); } private function shaderInstanceEndHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { _numRenderedInstances++; if (_numRenderedInstances == _numActiveInstances) { _numRenderedInstances = 0; _end.execute(this, context, backBuffer); } } } }
package aerys.minko.render.shader { import aerys.minko.ns.minko_render; import aerys.minko.ns.minko_shader; import aerys.minko.render.RenderTarget; import aerys.minko.render.ShaderDataBindingsProxy; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.shader.compiler.graph.ShaderGraph; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.part.ShaderPart; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.Signature; import flash.utils.getQualifiedClassName; use namespace minko_shader; /** * The base class to extend in order to create ActionScript shaders * and program the GPU using AS3. * * @author Jean-Marc Le Roux * @author Romain Gilliotte * * @see aerys.minko.render.shader.ShaderPart * @see aerys.minko.render.shader.ShaderInstance * @see aerys.minko.render.shader.ShaderSignature * @see aerys.minko.render.shader.ShaderDataBindings */ public class Shader extends ShaderPart { use namespace minko_shader; use namespace minko_render; minko_shader var _meshBindings : ShaderDataBindingsProxy = null; minko_shader var _sceneBindings : ShaderDataBindingsProxy = null; minko_shader var _kills : Vector.<AbstractNode> = new <AbstractNode>[]; private var _name : String = null; private var _enabled : Boolean = true; private var _defaultSettings : ShaderSettings = new ShaderSettings(null); private var _instances : Vector.<ShaderInstance> = new <ShaderInstance>[]; private var _numActiveInstances : uint = 0; private var _numRenderedInstances : uint = 0; private var _settings : Vector.<ShaderSettings> = new <ShaderSettings>[]; private var _programs : Vector.<Program3DResource> = new <Program3DResource>[]; private var _begin : Signal = new Signal('Shader.begin'); private var _end : Signal = new Signal('Shader.end'); /** * The name of the shader. Default value is the qualified name of the * ActionScript shader class (example: "aerys.minko.render.effect.basic::BasicShader"). * * @return * */ public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very first time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get begin() : Signal { return _begin; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very last time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get end() : Signal { return _end; } /** * Whether the shader (and all its forks) are enabled for rendering * or not. * * @return * */ public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } /** * * @param priority Default value is 0. * @param renderTarget Default value is null. * */ public function Shader(renderTarget : RenderTarget = null, priority : Number = 0.0) { super(this); _defaultSettings.renderTarget = renderTarget; _defaultSettings.priority = priority; _name = getQualifiedClassName(this); } public function fork(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderInstance { var pass : ShaderInstance = findPass(sceneBindings, meshBindings); if (!pass) { var signature : Signature = new Signature(); var config : ShaderSettings = findOrCreateSettings( sceneBindings, meshBindings ); signature.mergeWith(config.signature); var program : Program3DResource = null; if (config.enabled) { program = findOrCreateProgram(sceneBindings, meshBindings); signature.mergeWith(program.signature); } pass = new ShaderInstance(this, config, program, signature); pass.retained.add(shaderInstanceRetainedHandler); pass.released.add(shaderInstanceReleasedHandler); _instances.push(pass); } return pass; } public function disposeUnusedResources() : void { var numInstances : uint = _instances.length; var currentId : uint = 0; for (var instanceId : uint = 0; instanceId < numInstances; ++instanceId) { var passInstance : ShaderInstance = _instances[instanceId]; if (!passInstance.isDisposable) _instances[currentId++] = passInstance; } _instances.length = currentId; } /** * Override this method to initialize the settings * - such as the blending operands or the triangle culling - of the shader. * This values can be read from both the mesh and the scene bindings. * * @param settings * * @see aerys.minko.render.shader.ShaderSettings * */ protected function initializeSettings(settings : ShaderSettings) : void { // nothing } /** * The getVertexPosition() method is called to evaluate the vertex shader * program that shall be executed on the GPU. * * @return The position of the vertex in clip space (normalized screen space). * */ protected function getVertexPosition() : SFloat { throw new Error("The method 'getVertexPosition' must be implemented."); } /** * The getPixelColor() method is called to evaluate the fragment shader * program that shall be executed on the GPU. * * @return The color of the pixel on the screen. * */ protected function getPixelColor() : SFloat { throw new Error("The method 'getPixelColor' must be implemented."); } private function findPass(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderInstance { var numPasses : int = _instances.length; for (var passId : uint = 0; passId < numPasses; ++passId) if (_instances[passId].signature.isValid(sceneBindings, meshBindings)) return _instances[passId]; return null; } private function findOrCreateProgram(sceneBindings : DataBindings, meshBindings : DataBindings) : Program3DResource { var numPrograms : int = _programs.length; var program : Program3DResource; for (var programId : uint = 0; programId < numPrograms; ++programId) if (_programs[programId].signature.isValid(sceneBindings, meshBindings)) return _programs[programId]; var signature : Signature = new Signature(); _meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE); var vertexPosition : AbstractNode = getVertexPosition()._node; var pixelColor : AbstractNode = getPixelColor()._node; var shaderGraph : ShaderGraph = new ShaderGraph(vertexPosition, pixelColor, _kills); program = shaderGraph.generateProgram(_name, signature); _meshBindings = null; _sceneBindings = null; _kills.length = 0; _programs.push(program); return program; } private function findOrCreateSettings(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderSettings { var numConfigs : int = _settings.length; var config : ShaderSettings = null; for (var configId : int = 0; configId < numConfigs; ++configId) if (_settings[configId].signature.isValid(sceneBindings, meshBindings)) return _settings[configId]; var signature : Signature = new Signature(); config = _defaultSettings.clone(signature); _meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE); initializeSettings(config); _meshBindings = null; _sceneBindings = null; _settings.push(config); return config; } private function shaderInstanceRetainedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 1) { ++_numActiveInstances; instance.begin.add(shaderInstanceBeginHandler); instance.end.add(shaderInstanceEndHandler); } } private function shaderInstanceReleasedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 0) { --_numActiveInstances; instance.begin.remove(shaderInstanceBeginHandler); instance.end.remove(shaderInstanceEndHandler); } } private function shaderInstanceBeginHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { if (_numRenderedInstances == 0) _begin.execute(this, context, backBuffer); } private function shaderInstanceEndHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { _numRenderedInstances++; if (_numRenderedInstances == _numActiveInstances) { _numRenderedInstances = 0; _end.execute(this, context, backBuffer); } } } }
refactor imports
refactor imports
ActionScript
mit
aerys/minko-as3
00db69165a9d9019bb65fbf24b19f631e2aed3fa
src/aerys/minko/render/shader/Shader.as
src/aerys/minko/render/shader/Shader.as
package aerys.minko.render.shader { import aerys.minko.ns.minko_render; import aerys.minko.ns.minko_shader; import aerys.minko.render.RenderTarget; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.shader.compiler.graph.ShaderGraph; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.part.ShaderPart; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import flash.utils.getQualifiedClassName; use namespace minko_shader; /** * The base class to extend in order to create ActionScript shaders * and program the GPU using AS3. * * @author Jean-Marc Le Roux * @author Romain Gilliotte * * @see aerys.minko.render.shader.ShaderPart * @see aerys.minko.render.shader.ShaderInstance * @see aerys.minko.render.shader.ShaderSignature * @see aerys.minko.render.shader.ShaderDataBindings */ public class Shader extends ShaderPart { use namespace minko_shader; use namespace minko_render; minko_shader var _meshBindings : ShaderDataBindings = null; minko_shader var _sceneBindings : ShaderDataBindings = null; minko_shader var _kills : Vector.<AbstractNode> = new <AbstractNode>[]; private var _name : String = null; private var _enabled : Boolean = true; private var _defaultSettings : ShaderSettings = new ShaderSettings(null); private var _instances : Vector.<ShaderInstance> = new <ShaderInstance>[] private var _numActiveInstances : uint = 0; private var _numRenderedInstances : uint = 0; private var _settings : Vector.<ShaderSettings> = new <ShaderSettings>[]; private var _programs : Vector.<Program3DResource> = new <Program3DResource>[]; private var _begin : Signal = new Signal('Shader.begin'); private var _end : Signal = new Signal('Shader.end'); /** * The name of the shader. Default value is the qualified name of the * ActionScript shader class (example: "aerys.minko.render.effect.basic::BasicShader"). * * @return * */ public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very first time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get begin() : Signal { return _begin; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very last time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get end() : Signal { return _end; } /** * Whether the shader (and all its forks) are enabled for rendering * or not. * * @return * */ public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } /** * * @param priority Default value is 0. * @param renderTarget Default value is null. * */ public function Shader(renderTarget : RenderTarget = null, priority : Number = 0.0) { super(this); _defaultSettings.renderTarget = renderTarget; _defaultSettings.priority = priority; _name = getQualifiedClassName(this); } public function fork(meshBindings : DataBindings, sceneBindings : DataBindings) : ShaderInstance { var pass : ShaderInstance = findPass(meshBindings, sceneBindings); if (pass == null) { var signature : Signature = new Signature(_name); var config : ShaderSettings = findOrCreateSettings(meshBindings, sceneBindings); signature.mergeWith(config.signature); var program : Program3DResource = null; if (config.enabled) { program = findOrCreateProgram(meshBindings, sceneBindings); signature.mergeWith(program.signature); } pass = new ShaderInstance(this, config, program, signature); pass.retained.add(shaderInstanceRetainedHandler); pass.released.add(shaderInstanceReleasedHandler); _instances.push(pass); } return pass; } public function disposeUnusedResources() : void { var numInstances : uint = _instances.length; var currentId : uint = 0; for (var instanceId : uint = 0; instanceId < numInstances; ++instanceId) { var passInstance : ShaderInstance = _instances[instanceId]; if (!passInstance.isDisposable) _instances[currentId++] = passInstance; } _instances.length = currentId; } /** * Override this method to initialize the settings * - such as the blending operands or the triangle culling - of the shader. * This values can be read from both the mesh and the scene bindings. * * @param settings * * @see aerys.minko.render.shader.ShaderSettings * */ protected function initializeSettings(settings : ShaderSettings) : void { // throw new Error("The method 'initializeSettings' must be implemented."); } /** * The getVertexPosition() method is called to evaluate the vertex shader * program that shall be executed on the GPU. * * @return The position of the vertex in clip space (normalized screen space). * */ protected function getVertexPosition() : SFloat { throw new Error("The method 'getVertexPosition' must be implemented."); } /** * The getPixelColor() method is called to evaluate the fragment shader * program that shall be executed on the GPU. * * @return The color of the pixel on the screen. * */ protected function getPixelColor() : SFloat { throw new Error("The method 'getPixelColor' must be implemented."); } private function findPass(meshBindings : DataBindings, sceneBindings : DataBindings) : ShaderInstance { var numPasses : int = _instances.length; for (var passId : uint = 0; passId < numPasses; ++passId) if (_instances[passId].signature.isValid(meshBindings, sceneBindings)) return _instances[passId]; return null; } private function findOrCreateProgram(meshBindings : DataBindings, sceneBindings : DataBindings) : Program3DResource { var numPrograms : int = _programs.length; var program : Program3DResource; for (var programId : uint = 0; programId < numPrograms; ++programId) if (_programs[programId].signature.isValid(meshBindings, sceneBindings)) return _programs[programId]; var signature : Signature = new Signature(_name); _meshBindings = new ShaderDataBindings(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindings(sceneBindings, signature, Signature.SOURCE_SCENE); var vertexPosition : AbstractNode = getVertexPosition()._node; var pixelColor : AbstractNode = getPixelColor()._node; var shaderGraph : ShaderGraph = new ShaderGraph(vertexPosition, pixelColor, _kills); program = shaderGraph.generateProgram(_name, signature); _meshBindings = null; _sceneBindings = null; _kills.length = 0; _programs.push(program); return program; } private function findOrCreateSettings(meshBindings : DataBindings, sceneBindings : DataBindings) : ShaderSettings { var numConfigs : int = _settings.length; var config : ShaderSettings = null; for (var configId : int = 0; configId < numConfigs; ++configId) if (_settings[configId].signature.isValid(meshBindings, sceneBindings)) return _settings[configId]; var signature : Signature = new Signature(_name); config = _defaultSettings.clone(signature); _meshBindings = new ShaderDataBindings(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindings(sceneBindings, signature, Signature.SOURCE_SCENE); initializeSettings(config); _meshBindings = null; _sceneBindings = null; _settings.push(config); return config; } private function shaderInstanceRetainedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 1) { ++_numActiveInstances; instance.begin.add(shaderInstanceBeginHandler); instance.end.add(shaderInstanceEndHandler); } } private function shaderInstanceReleasedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 0) { --_numActiveInstances; instance.begin.remove(shaderInstanceBeginHandler); instance.end.remove(shaderInstanceEndHandler); } } private function shaderInstanceBeginHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { if (_numRenderedInstances == 0) _begin.execute(this, context, backBuffer); } private function shaderInstanceEndHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { _numRenderedInstances++; if (_numRenderedInstances == _numActiveInstances) { _numRenderedInstances = 0; _end.execute(this, context, backBuffer); } } } }
package aerys.minko.render.shader { import aerys.minko.ns.minko_render; import aerys.minko.ns.minko_shader; import aerys.minko.render.RenderTarget; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.shader.compiler.graph.ShaderGraph; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.part.ShaderPart; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import flash.utils.getQualifiedClassName; use namespace minko_shader; /** * The base class to extend in order to create ActionScript shaders * and program the GPU using AS3. * * @author Jean-Marc Le Roux * @author Romain Gilliotte * * @see aerys.minko.render.shader.ShaderPart * @see aerys.minko.render.shader.ShaderInstance * @see aerys.minko.render.shader.ShaderSignature * @see aerys.minko.render.shader.ShaderDataBindings */ public class Shader extends ShaderPart { use namespace minko_shader; use namespace minko_render; minko_shader var _meshBindings : ShaderDataBindings = null; minko_shader var _sceneBindings : ShaderDataBindings = null; minko_shader var _kills : Vector.<AbstractNode> = new <AbstractNode>[]; private var _name : String = null; private var _enabled : Boolean = true; private var _defaultSettings : ShaderSettings = new ShaderSettings(null); private var _instances : Vector.<ShaderInstance> = new <ShaderInstance>[] private var _numActiveInstances : uint = 0; private var _numRenderedInstances : uint = 0; private var _settings : Vector.<ShaderSettings> = new <ShaderSettings>[]; private var _programs : Vector.<Program3DResource> = new <Program3DResource>[]; private var _begin : Signal = new Signal('Shader.begin'); private var _end : Signal = new Signal('Shader.end'); /** * The name of the shader. Default value is the qualified name of the * ActionScript shader class (example: "aerys.minko.render.effect.basic::BasicShader"). * * @return * */ public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very first time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get begin() : Signal { return _begin; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very last time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get end() : Signal { return _end; } /** * Whether the shader (and all its forks) are enabled for rendering * or not. * * @return * */ public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } /** * * @param priority Default value is 0. * @param renderTarget Default value is null. * */ public function Shader(renderTarget : RenderTarget = null, priority : Number = 0.0) { super(this); _defaultSettings.renderTarget = renderTarget; _defaultSettings.priority = priority; _name = getQualifiedClassName(this); } public function fork(meshBindings : DataBindings, sceneBindings : DataBindings) : ShaderInstance { var pass : ShaderInstance = findPass(meshBindings, sceneBindings); if (pass == null) { var signature : Signature = new Signature(_name); var config : ShaderSettings = findOrCreateSettings(meshBindings, sceneBindings); signature.mergeWith(config.signature); var program : Program3DResource = null; if (config.enabled) { program = findOrCreateProgram(meshBindings, sceneBindings); signature.mergeWith(program.signature); } pass = new ShaderInstance(this, config, program, signature); pass.retained.add(shaderInstanceRetainedHandler); pass.released.add(shaderInstanceReleasedHandler); _instances.push(pass); } return pass; } public function disposeUnusedResources() : void { var numInstances : uint = _instances.length; var currentId : uint = 0; for (var instanceId : uint = 0; instanceId < numInstances; ++instanceId) { var passInstance : ShaderInstance = _instances[instanceId]; if (!passInstance.isDisposable) _instances[currentId++] = passInstance; } _instances.length = currentId; } /** * Override this method to initialize the settings * - such as the blending operands or the triangle culling - of the shader. * This values can be read from both the mesh and the scene bindings. * * @param settings * * @see aerys.minko.render.shader.ShaderSettings * */ protected function initializeSettings(settings : ShaderSettings) : void { // nothing } /** * The getVertexPosition() method is called to evaluate the vertex shader * program that shall be executed on the GPU. * * @return The position of the vertex in clip space (normalized screen space). * */ protected function getVertexPosition() : SFloat { throw new Error("The method 'getVertexPosition' must be implemented."); } /** * The getPixelColor() method is called to evaluate the fragment shader * program that shall be executed on the GPU. * * @return The color of the pixel on the screen. * */ protected function getPixelColor() : SFloat { throw new Error("The method 'getPixelColor' must be implemented."); } private function findPass(meshBindings : DataBindings, sceneBindings : DataBindings) : ShaderInstance { var numPasses : int = _instances.length; for (var passId : uint = 0; passId < numPasses; ++passId) if (_instances[passId].signature.isValid(meshBindings, sceneBindings)) return _instances[passId]; return null; } private function findOrCreateProgram(meshBindings : DataBindings, sceneBindings : DataBindings) : Program3DResource { var numPrograms : int = _programs.length; var program : Program3DResource; for (var programId : uint = 0; programId < numPrograms; ++programId) if (_programs[programId].signature.isValid(meshBindings, sceneBindings)) return _programs[programId]; var signature : Signature = new Signature(_name); _meshBindings = new ShaderDataBindings(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindings(sceneBindings, signature, Signature.SOURCE_SCENE); var vertexPosition : AbstractNode = getVertexPosition()._node; var pixelColor : AbstractNode = getPixelColor()._node; var shaderGraph : ShaderGraph = new ShaderGraph(vertexPosition, pixelColor, _kills); program = shaderGraph.generateProgram(_name, signature); _meshBindings = null; _sceneBindings = null; _kills.length = 0; _programs.push(program); return program; } private function findOrCreateSettings(meshBindings : DataBindings, sceneBindings : DataBindings) : ShaderSettings { var numConfigs : int = _settings.length; var config : ShaderSettings = null; for (var configId : int = 0; configId < numConfigs; ++configId) if (_settings[configId].signature.isValid(meshBindings, sceneBindings)) return _settings[configId]; var signature : Signature = new Signature(_name); config = _defaultSettings.clone(signature); _meshBindings = new ShaderDataBindings(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindings(sceneBindings, signature, Signature.SOURCE_SCENE); initializeSettings(config); _meshBindings = null; _sceneBindings = null; _settings.push(config); return config; } private function shaderInstanceRetainedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 1) { ++_numActiveInstances; instance.begin.add(shaderInstanceBeginHandler); instance.end.add(shaderInstanceEndHandler); } } private function shaderInstanceReleasedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 0) { --_numActiveInstances; instance.begin.remove(shaderInstanceBeginHandler); instance.end.remove(shaderInstanceEndHandler); } } private function shaderInstanceBeginHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { if (_numRenderedInstances == 0) _begin.execute(this, context, backBuffer); } private function shaderInstanceEndHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { _numRenderedInstances++; if (_numRenderedInstances == _numActiveInstances) { _numRenderedInstances = 0; _end.execute(this, context, backBuffer); } } } }
fix coding style
fix coding style
ActionScript
mit
aerys/minko-as3
d9b51b0939da67445f0c1d69ed6c12635e09de2c
src/aerys/minko/render/geometry/stream/iterator/TriangleIterator.as
src/aerys/minko/render/geometry/stream/iterator/TriangleIterator.as
package aerys.minko.render.geometry.stream.iterator { import aerys.minko.ns.minko_stream; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.IndexStream; import flash.utils.Proxy; import flash.utils.flash_proxy; /** * TriangleIterator allow per-triangle access on VertexStream objects. * * @author Jean-Marc Le Roux * */ public final class TriangleIterator extends Proxy { use namespace minko_stream; private var _singleReference : Boolean = true; private var _offset : int = 0; private var _index : int = 0; private var _vb : IVertexStream = null; private var _ib : IndexStream = null; private var _triangle : TriangleReference = null; public function get length() : int { return _ib ? _ib.length / 3 : _vb.numVertices / 3; } public function TriangleIterator(vertexStream : IVertexStream, indexStream : IndexStream, singleReference : Boolean = true) { super(); _vb = vertexStream; _ib = indexStream; _singleReference = singleReference; } override flash_proxy function hasProperty(name : *) : Boolean { return int(name) < _ib.length / 3; } override flash_proxy function nextNameIndex(index : int) : int { index -= _offset; _offset = 0; return index < _ib.length / 3 ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { _index = index - 1; if (!_singleReference || !_triangle) _triangle = new TriangleReference(_vb, _ib, _index); if (_singleReference) { _triangle._index = _index; _triangle.v0._index = _ib._data[int(_index * 3)]; _triangle.v1._index = _ib._data[int(_index * 3 + 1)]; _triangle.v2._index = _ib._data[int(_index * 3 + 2)]; _triangle._update = TriangleReference.UPDATE_ALL; } return _triangle; } override flash_proxy function getProperty(name : *) : * { return new TriangleReference(_vb, _ib, int(name)); } override flash_proxy function deleteProperty(name : *) : Boolean { var index : uint = uint(name); _ib.deleteTriangle(index); return true; } } }
package aerys.minko.render.geometry.stream.iterator { import aerys.minko.ns.minko_stream; import aerys.minko.render.geometry.stream.IVertexStream; import aerys.minko.render.geometry.stream.IndexStream; import flash.utils.Proxy; import flash.utils.flash_proxy; /** * TriangleIterator allow per-triangle access on VertexStream objects. * * @author Jean-Marc Le Roux * */ public final class TriangleIterator extends Proxy { use namespace minko_stream; private var _singleReference : Boolean = true; private var _offset : int = 0; private var _index : int = 0; private var _vb : IVertexStream = null; private var _ib : IndexStream = null; private var _triangle : TriangleReference = null; public function get length() : int { return _ib ? _ib.length / 3 : _vb.numVertices / 3; } public function TriangleIterator(vertexStream : IVertexStream, indexStream : IndexStream, singleReference : Boolean = true) { super(); _vb = vertexStream; _ib = indexStream; _singleReference = singleReference; } override flash_proxy function hasProperty(name : *) : Boolean { return int(name) < _ib.length / 3; } override flash_proxy function nextNameIndex(index : int) : int { index -= _offset; _offset = 0; return index < _ib.length / 3 ? index + 1 : 0; } override flash_proxy function nextName(index : int) : String { return String(index - 1); } override flash_proxy function nextValue(index : int) : * { _index = index - 1; if (!_singleReference || !_triangle) _triangle = new TriangleReference(_vb, _ib, _index); if (_singleReference) { _triangle._index = _index; _triangle.v0.index = _ib.get(_index * 3); _triangle.v1.index = _ib.get(_index * 3 + 1); _triangle.v2.index = _ib.get(_index * 3 + 2); _triangle._update = TriangleReference.UPDATE_ALL; } return _triangle; } override flash_proxy function getProperty(name : *) : * { return new TriangleReference(_vb, _ib, int(name)); } override flash_proxy function deleteProperty(name : *) : Boolean { var index : uint = uint(name); _ib.deleteTriangle(index); return true; } } }
fix triangle iterator
fix triangle iterator
ActionScript
mit
aerys/minko-as3
bd8ee0fd4d38bc9ef525dca7c70e484e2d60cafc
src/as/com/threerings/util/Hashtable.as
src/as/com/threerings/util/Hashtable.as
package com.threerings.util { import flash.errors.IllegalOperationError; import flash.utils.Dictionary; /** * An implementation of a Hashtable in actionscript. Any object (and null) may * be used as a key. Simple keys (Number, int, uint, Boolean, String) utilize * a Dictionary internally for storage; keys that implement Hashable are * stored efficiently, and any other key can also be used if the equalsFn * and hashFn are specified to the constructor. */ public class Hashtable implements Map { /** * Construct a Hashtable * * @param loadFactor - A measure of how full the hashtable is allowed to * get before it is automatically resized. The default * value of 1.75 should be fine. * @param equalsFn - (Optional) A function to use to compare object * equality for keys that are neither simple nor * implement Hashable. The signature should be * "function (o1, o2) :Boolean". * @param hashFn - (Optional) A function to use to generate a hash * code for keys that are neither simple nor * implement Hashable. The signature should be * "function (obj) :*", where the return type is * numeric or String. Two objects that are equals * according to the specified equalsFn *must* * generate equal values when passed to the hashFn. */ public function Hashtable ( loadFactor :Number = 1.75, equalsFn :Function = null, hashFn :Function = null) { if ((equalsFn != null) != (hashFn != null)) { throw new ArgumentError("Both the equals and hash functions " + "must be specified, or neither."); } _loadFactor = loadFactor; _equalsFn = equalsFn; _hashFn = hashFn; } // documentation inherited from interface Map public function clear () :void { _simpleData = null; _simpleSize = 0; _entries = null; _entriesSize = 0; } // documentation inherited from interface Map public function containsKey (key :Object) :Boolean { return (undefined !== get(key)); } // documentation inherited from interface Map public function get (key :Object) :* { if (isSimple(key)) { return (_simpleData == null) ? undefined : _simpleData[key]; } if (_entries == null) { return undefined; } var hkey :Hashable = keyFor(key); var hash :int = hkey.hashCode(); var index :int = indexFor(hash); var e :Entry = (_entries[index] as Entry); while (true) { if (e == null) { return null; } if (e.hash == hash && e.key.equals(hkey)) { return e.value; } e = e.next; } } // documentation inherited from interface Map public function isEmpty () :Boolean { return (size() == 0); } // documentation inherited from interface Map public function put (key :Object, value :Object) :* { var oldValue :*; if (isSimple(key)) { if (_simpleData == null) { _simpleData = new Dictionary(); } oldValue = _simpleData[key]; _simpleData[key] = value; if (oldValue === undefined) { _simpleSize++; } return oldValue; } // lazy-create the array holding other hashables if (_entries == null) { _entries = new Array(); _entries.length = DEFAULT_BUCKETS; } var hkey :Hashable = keyFor(key); var hash :int = hkey.hashCode(); var index :int = indexFor(hash); var firstEntry :Entry = (_entries[index] as Entry); for (var e :Entry = firstEntry; e != null; e = e.next) { if (e.hash == hash && e.key.equals(hkey)) { oldValue = e.value; e.value = value; return oldValue; // size did not change } } _entries[index] = new Entry(hash, hkey, value, firstEntry); _entriesSize++; // check to see if we should grow the map if (_entriesSize > _entries.length * _loadFactor) { resize(2 * _entries.length); } // indicate that there was no value previously stored for the key return undefined; } // documentation inherited from interface Map public function remove (key :Object) :* { if (isSimple(key)) { if (_simpleData == null) { return undefined; } var oldValue :* = _simpleData[key]; if (oldValue !== undefined) { _simpleSize--; } delete _simpleData[key]; return oldValue; } if (_entries == null) { return undefined; } var hkey :Hashable = keyFor(key); var hash :int = hkey.hashCode(); var index :int = indexFor(hash); var prev :Entry = (_entries[index] as Entry); var e :Entry = prev; while (e != null) { var next :Entry = e.next; if (e.hash == hash && e.key.equals(hkey)) { if (prev == e) { _entries[index] = next; } else { prev.next = next; } _entriesSize--; // check to see if we should shrink the map if ((_entries.length > DEFAULT_BUCKETS) && (_entriesSize < _entries.length * _loadFactor * .125)) { resize(Math.max(DEFAULT_BUCKETS, _entries.length / 2)); } return e.value; } prev = e; e = next; } return undefined; // never found } // documentation inherited from interface Map public function size () :int { return _simpleSize + _entriesSize; } // documentation inherited from interface Map public function keys () :Array { var keys :Array = new Array(); // get the simple keys first if (_simpleData != null) { for (var key :* in _simpleData) { keys.push(key); } } // get the more complex keys if (_entries != null) { for (var ii :int = _entries.length - 1; ii >= 0; ii--) { for (var e :Entry = (_entries[ii] as Entry); e != null; e = e.next) { keys.push(e.getOriginalKey()); } } } return keys; } // documentation inherited from interface Map public function values () :Array { var vals :Array = new Array(); // get the simple properties first if (_simpleData != null) { for each (var value :* in _simpleData) { vals.push(value); } } // get the more complex properties if (_entries != null) { for (var ii :int = _entries.length - 1; ii >= 0; ii--) { for (var e :Entry = (_entries[ii] as Entry); e != null; e = e.next) { vals.push(e.value); } } } return vals; } // documentation inherited from interface Map public function forEach (fn :Function) :void { if (_simpleData != null) { for (var key :Object in _simpleData) { fn(key, _simpleData[key]); } } if (_entries != null) { for (var ii :int = _entries.length - 1; ii >= 0; ii--) { for (var e :Entry = (_entries[ii] as Entry); e != null; e = e.next) { fn(e.getOriginalKey(), e.value); } } } } /** * Return a Hashable that represents the key. */ protected function keyFor (key :Object) :Hashable { if (key is Hashable) { return (key as Hashable); } else if (_hashFn == null) { throw new IllegalOperationError("Illegal key specified " + "for Hashtable created without hashing functions."); } else { return new KeyWrapper(key, _equalsFn, _hashFn); } } /** * Return an index for the specified hashcode. */ protected function indexFor (hash :int) :int { // TODO: improve? return Math.abs(hash) % _entries.length; } /** * Return true if the specified key may be used to store values in a * Dictionary object. */ protected function isSimple (key :Object) :Boolean { return (key is String) || (key is Number) || (key is Boolean); } /** * Resize the entries with Hashable keys to optimize * the memory/performance tradeoff. */ protected function resize (newSize :int) :void { var oldEntries :Array = _entries; _entries = new Array(); _entries.length = newSize; // place all the old entries in the new map for (var ii :int = 0; ii < oldEntries.length; ii++) { var e :Entry = (oldEntries[ii] as Entry); while (e != null) { var next :Entry = e.next; var index :int = indexFor(e.hash); e.next = (_entries[index] as Entry); _entries[index] = e; e = next; } } } /** The current number of key/value pairs stored in the Dictionary. */ protected var _simpleSize :int = 0; /** The current number of key/value pairs stored in the _entries. */ protected var _entriesSize :int = 0; /** The load factor. */ protected var _loadFactor :Number; /** If non-null, contains simple key/value pairs. */ protected var _simpleData :Dictionary /** If non-null, contains Hashable keys and their values. */ protected var _entries :Array; /** The hashing function to use for non-Hashable complex keys. */ protected var _hashFn :Function; /** The equality function to use for non-Hashable complex keys. */ protected var _equalsFn :Function; /** The default size for the bucketed hashmap. */ protected static const DEFAULT_BUCKETS :int = 16; } } // end: package com.threerings.util import com.threerings.util.Hashable; class Entry { public var key :Hashable; public var value :Object; public var hash :int; public var next :Entry; public function Entry (hash :int, key :Hashable, value :Object, next :Entry) { this.hash = hash; this.key = key; this.value = value; this.next = next; } /** * Get the original key used to store this entry. */ public function getOriginalKey () :Object { if (key is KeyWrapper) { return (key as KeyWrapper).key; } return key; } } class KeyWrapper implements Hashable { public var key :Object; public function KeyWrapper ( key :Object, equalsFn :Function, hashFn :Function) { this.key = key; _equalsFn = equalsFn; var hashValue :* = hashFn(key); if (hashValue is String) { var uid :String = (hashValue as String); // examine at most 32 characters of the string var inc :int = int(Math.max(1, Math.ceil(uid.length / 32))); for (var ii :int = 0; ii < uid.length; ii += inc) { _hash = (_hash << 1) ^ int(uid.charCodeAt(ii)); } } else { _hash = int(hashValue); } } // documentation inherited from interface Hashable public function equals (other :Object) :Boolean { return (other is KeyWrapper) && Boolean(_equalsFn(key, (other as KeyWrapper).key)); } // documentation inherited from interface Hashable public function hashCode () :int { return _hash; } protected var _key :Object; protected var _hash :int; protected var _equalsFn :Function; }
package com.threerings.util { import flash.errors.IllegalOperationError; import flash.utils.Dictionary; /** * An implementation of a Hashtable in actionscript. Any object (and null) may * be used as a key. Simple keys (Number, int, uint, Boolean, String) utilize * a Dictionary internally for storage; keys that implement Hashable are * stored efficiently, and any other key can also be used if the equalsFn * and hashFn are specified to the constructor. */ public class Hashtable implements Map { /** * Construct a Hashtable * * @param loadFactor - A measure of how full the hashtable is allowed to * get before it is automatically resized. The default * value of 1.75 should be fine. * @param equalsFn - (Optional) A function to use to compare object * equality for keys that are neither simple nor * implement Hashable. The signature should be * "function (o1, o2) :Boolean". * @param hashFn - (Optional) A function to use to generate a hash * code for keys that are neither simple nor * implement Hashable. The signature should be * "function (obj) :*", where the return type is * numeric or String. Two objects that are equals * according to the specified equalsFn *must* * generate equal values when passed to the hashFn. */ public function Hashtable ( loadFactor :Number = 1.75, equalsFn :Function = null, hashFn :Function = null) { if ((equalsFn != null) != (hashFn != null)) { throw new ArgumentError("Both the equals and hash functions " + "must be specified, or neither."); } _loadFactor = loadFactor; _equalsFn = equalsFn; _hashFn = hashFn; } // documentation inherited from interface Map public function clear () :void { _simpleData = null; _simpleSize = 0; _entries = null; _entriesSize = 0; } // documentation inherited from interface Map public function containsKey (key :Object) :Boolean { return (undefined !== get(key)); } // documentation inherited from interface Map public function get (key :Object) :* { if (isSimple(key)) { return (_simpleData == null) ? undefined : _simpleData[key]; } if (_entries == null) { return undefined; } var hkey :Hashable = keyFor(key); var hash :int = hkey.hashCode(); var index :int = indexFor(hash); var e :Entry = (_entries[index] as Entry); while (true) { if (e == null) { return undefined; } if (e.hash == hash && e.key.equals(hkey)) { return e.value; } e = e.next; } } // documentation inherited from interface Map public function isEmpty () :Boolean { return (size() == 0); } // documentation inherited from interface Map public function put (key :Object, value :Object) :* { var oldValue :*; if (isSimple(key)) { if (_simpleData == null) { _simpleData = new Dictionary(); } oldValue = _simpleData[key]; _simpleData[key] = value; if (oldValue === undefined) { _simpleSize++; } return oldValue; } // lazy-create the array holding other hashables if (_entries == null) { _entries = new Array(); _entries.length = DEFAULT_BUCKETS; } var hkey :Hashable = keyFor(key); var hash :int = hkey.hashCode(); var index :int = indexFor(hash); var firstEntry :Entry = (_entries[index] as Entry); for (var e :Entry = firstEntry; e != null; e = e.next) { if (e.hash == hash && e.key.equals(hkey)) { oldValue = e.value; e.value = value; return oldValue; // size did not change } } _entries[index] = new Entry(hash, hkey, value, firstEntry); _entriesSize++; // check to see if we should grow the map if (_entriesSize > _entries.length * _loadFactor) { resize(2 * _entries.length); } // indicate that there was no value previously stored for the key return undefined; } // documentation inherited from interface Map public function remove (key :Object) :* { if (isSimple(key)) { if (_simpleData == null) { return undefined; } var oldValue :* = _simpleData[key]; if (oldValue !== undefined) { _simpleSize--; } delete _simpleData[key]; return oldValue; } if (_entries == null) { return undefined; } var hkey :Hashable = keyFor(key); var hash :int = hkey.hashCode(); var index :int = indexFor(hash); var prev :Entry = (_entries[index] as Entry); var e :Entry = prev; while (e != null) { var next :Entry = e.next; if (e.hash == hash && e.key.equals(hkey)) { if (prev == e) { _entries[index] = next; } else { prev.next = next; } _entriesSize--; // check to see if we should shrink the map if ((_entries.length > DEFAULT_BUCKETS) && (_entriesSize < _entries.length * _loadFactor * .125)) { resize(Math.max(DEFAULT_BUCKETS, _entries.length / 2)); } return e.value; } prev = e; e = next; } return undefined; // never found } // documentation inherited from interface Map public function size () :int { return _simpleSize + _entriesSize; } // documentation inherited from interface Map public function keys () :Array { var keys :Array = new Array(); // get the simple keys first if (_simpleData != null) { for (var key :* in _simpleData) { keys.push(key); } } // get the more complex keys if (_entries != null) { for (var ii :int = _entries.length - 1; ii >= 0; ii--) { for (var e :Entry = (_entries[ii] as Entry); e != null; e = e.next) { keys.push(e.getOriginalKey()); } } } return keys; } // documentation inherited from interface Map public function values () :Array { var vals :Array = new Array(); // get the simple properties first if (_simpleData != null) { for each (var value :* in _simpleData) { vals.push(value); } } // get the more complex properties if (_entries != null) { for (var ii :int = _entries.length - 1; ii >= 0; ii--) { for (var e :Entry = (_entries[ii] as Entry); e != null; e = e.next) { vals.push(e.value); } } } return vals; } // documentation inherited from interface Map public function forEach (fn :Function) :void { if (_simpleData != null) { for (var key :Object in _simpleData) { fn(key, _simpleData[key]); } } if (_entries != null) { for (var ii :int = _entries.length - 1; ii >= 0; ii--) { for (var e :Entry = (_entries[ii] as Entry); e != null; e = e.next) { fn(e.getOriginalKey(), e.value); } } } } /** * Return a Hashable that represents the key. */ protected function keyFor (key :Object) :Hashable { if (key is Hashable) { return (key as Hashable); } else if (_hashFn == null) { throw new IllegalOperationError("Illegal key specified " + "for Hashtable created without hashing functions."); } else { return new KeyWrapper(key, _equalsFn, _hashFn); } } /** * Return an index for the specified hashcode. */ protected function indexFor (hash :int) :int { // TODO: improve? return Math.abs(hash) % _entries.length; } /** * Return true if the specified key may be used to store values in a * Dictionary object. */ protected function isSimple (key :Object) :Boolean { return (key is String) || (key is Number) || (key is Boolean); } /** * Resize the entries with Hashable keys to optimize * the memory/performance tradeoff. */ protected function resize (newSize :int) :void { var oldEntries :Array = _entries; _entries = new Array(); _entries.length = newSize; // place all the old entries in the new map for (var ii :int = 0; ii < oldEntries.length; ii++) { var e :Entry = (oldEntries[ii] as Entry); while (e != null) { var next :Entry = e.next; var index :int = indexFor(e.hash); e.next = (_entries[index] as Entry); _entries[index] = e; e = next; } } } /** The current number of key/value pairs stored in the Dictionary. */ protected var _simpleSize :int = 0; /** The current number of key/value pairs stored in the _entries. */ protected var _entriesSize :int = 0; /** The load factor. */ protected var _loadFactor :Number; /** If non-null, contains simple key/value pairs. */ protected var _simpleData :Dictionary /** If non-null, contains Hashable keys and their values. */ protected var _entries :Array; /** The hashing function to use for non-Hashable complex keys. */ protected var _hashFn :Function; /** The equality function to use for non-Hashable complex keys. */ protected var _equalsFn :Function; /** The default size for the bucketed hashmap. */ protected static const DEFAULT_BUCKETS :int = 16; } } // end: package com.threerings.util import com.threerings.util.Hashable; class Entry { public var key :Hashable; public var value :Object; public var hash :int; public var next :Entry; public function Entry (hash :int, key :Hashable, value :Object, next :Entry) { this.hash = hash; this.key = key; this.value = value; this.next = next; } /** * Get the original key used to store this entry. */ public function getOriginalKey () :Object { if (key is KeyWrapper) { return (key as KeyWrapper).key; } return key; } } class KeyWrapper implements Hashable { public var key :Object; public function KeyWrapper ( key :Object, equalsFn :Function, hashFn :Function) { this.key = key; _equalsFn = equalsFn; var hashValue :* = hashFn(key); if (hashValue is String) { var uid :String = (hashValue as String); // examine at most 32 characters of the string var inc :int = int(Math.max(1, Math.ceil(uid.length / 32))); for (var ii :int = 0; ii < uid.length; ii += inc) { _hash = (_hash << 1) ^ int(uid.charCodeAt(ii)); } } else { _hash = int(hashValue); } } // documentation inherited from interface Hashable public function equals (other :Object) :Boolean { return (other is KeyWrapper) && Boolean(_equalsFn(key, (other as KeyWrapper).key)); } // documentation inherited from interface Hashable public function hashCode () :int { return _hash; } protected var _key :Object; protected var _hash :int; protected var _equalsFn :Function; }
return undefined, not null, to indicate absence in the map.
Bugfix: return undefined, not null, to indicate absence in the map. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4386 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
4bb40b43fa0101409ca5a49b80dc3b6e37e5d16c
src/battlecode/client/viewer/render/DrawMap.as
src/battlecode/client/viewer/render/DrawMap.as
package battlecode.client.viewer.render { import battlecode.client.viewer.MatchController; import battlecode.common.MapLocation; import battlecode.common.Team; import battlecode.common.TerrainTile; import battlecode.events.MatchEvent; import battlecode.world.GameMap; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.ColorTransform; import flash.geom.Rectangle; import mx.containers.Canvas; import mx.core.UIComponent; public class DrawMap extends Canvas { private var controller:MatchController; private var origin:MapLocation; // various canvases for layering and quick toggling of features private var mapCanvas:UIComponent; private var gridCanvas:UIComponent; private var rubbleCanvas:UIComponent; private var partsCanvas:UIComponent; private var groundUnitCanvas:UIComponent; private var zombieUnitCanvas:UIComponent; // optimizations for caching private var lastRound:uint = 0; public function DrawMap(controller:MatchController) { super(); this.controller = controller; this.controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange); this.controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange); this.addEventListener(Event.ENTER_FRAME, onEnterFrame); this.mapCanvas = new UIComponent(); this.gridCanvas = new UIComponent(); this.rubbleCanvas = new UIComponent(); this.partsCanvas = new UIComponent(); this.groundUnitCanvas = new UIComponent(); this.zombieUnitCanvas = new UIComponent(); this.mapCanvas.cacheAsBitmap = true; this.gridCanvas.cacheAsBitmap = true; this.addChild(mapCanvas); this.addChild(rubbleCanvas); this.addChild(partsCanvas); this.addChild(gridCanvas); this.addChild(groundUnitCanvas); this.addChild(zombieUnitCanvas); } /////////////////////////////////////////////////////// ////////////////// UTILITY METHODS //////////////////// /////////////////////////////////////////////////////// public function getMapWidth():uint { if (controller.match) return controller.match.getMap().getWidth() * RenderConfiguration.GRID_SIZE; return 0; } public function getMapHeight():uint { if (controller.match) return controller.match.getMap().getHeight() * RenderConfiguration.GRID_SIZE + 5; return 0; } private function getGridSize():Number { return RenderConfiguration.getGridSize(); } /////////////////////////////////////////////////////// ////////////////// DRAWING METHODS //////////////////// /////////////////////////////////////////////////////// public function redrawAll():void { drawMap(); drawGridlines(); drawUnits(); drawRubble(); drawParts(); var o:DrawObject; for each (o in controller.currentState.getGroundRobots()) { o.draw(true); } this.scrollRect = new Rectangle(this.mapCanvas.x, this.mapCanvas.y, getMapWidth() * RenderConfiguration.getScalingFactor(), getMapHeight() * RenderConfiguration.getScalingFactor()); } private function drawMap():void { var i:uint, j:uint, tile:TerrainTile; var map:GameMap = controller.match.getMap(); var terrain:Array = map.getTerrainTiles(); var colorTransform:ColorTransform, scalar:uint; var g:Number = getGridSize(); origin = map.getOrigin(); this.mapCanvas.graphics.clear(); // draw terrain for (i = 0; i < map.getHeight(); i++) { for (j = 0; j < map.getWidth(); j++) { tile = terrain[i][j] as TerrainTile; if (tile.getType() == TerrainTile.LAND) { scalar = 0xFF * 0.9; colorTransform = new ColorTransform(0, 0, 0, 1, scalar, scalar, scalar, 0); this.mapCanvas.graphics.beginFill(colorTransform.color, 1.0); this.mapCanvas.graphics.drawRect(j * g, i * g, g, g); this.mapCanvas.graphics.endFill(); } else { colorTransform = new ColorTransform(0, 0, 0, 1, 0x00, 0x00, 0x99, 0); this.mapCanvas.graphics.beginFill(colorTransform.color, 1.0); this.mapCanvas.graphics.drawRect(j * g, i * g, g, g); this.mapCanvas.graphics.endFill(); } } } // draw void outlines for (i = 0; i < map.getHeight(); i++) { for (j = 0; j < map.getWidth(); j++) { tile = terrain[i][j] as TerrainTile; if (tile.getType() == TerrainTile.VOID) { this.mapCanvas.graphics.lineStyle(2, 0xFFFFFF); if (i > 0 && terrain[i-1][j].getType() == TerrainTile.LAND) { this.mapCanvas.graphics.moveTo(j * g, i * g); this.mapCanvas.graphics.lineTo((j + 1) * g, i * g); } if (j > 0 && terrain[i][j-1].getType() == TerrainTile.LAND) { this.mapCanvas.graphics.moveTo(j * g, i * g); this.mapCanvas.graphics.lineTo(j * g, (i + 1) * g); } if (i < map.getHeight() - 1 && terrain[i+1][j].getType() == TerrainTile.LAND) { this.mapCanvas.graphics.moveTo(j * g, (i + 1) * g); this.mapCanvas.graphics.lineTo((j + 1) * g, (i + 1) * g); } if (j < map.getWidth() - 1 && terrain[i][j+1].getType() == TerrainTile.LAND) { this.mapCanvas.graphics.moveTo((j + 1) * g, i * g); this.mapCanvas.graphics.lineTo((j + 1) * g, (i + 1) * g); } this.mapCanvas.graphics.lineStyle(); } } } } private function drawGridlines():void { var i:uint, j:uint; var map:GameMap = controller.match.getMap(); this.gridCanvas.graphics.clear(); for (i = 0; i < map.getHeight(); i++) { for (j = 0; j < map.getWidth(); j++) { this.gridCanvas.graphics.lineStyle(.5, 0x999999, 0.3); this.gridCanvas.graphics.drawRect(j * getGridSize(), i * getGridSize(), getGridSize(), getGridSize()); } } } private function drawRubble():void { var terrain:Array = controller.match.getMap().getTerrainTiles(); var rubble:Array = controller.currentState.getRubble(); var i:uint, j:uint; this.rubbleCanvas.graphics.clear(); this.rubbleCanvas.graphics.lineStyle(); var g:Number = getGridSize(); for (i = 0; i < rubble.length; i++) { for (j = 0; j < rubble[i].length; j++) { var tile:TerrainTile = terrain[i][j] as TerrainTile; if (tile.getType() == TerrainTile.VOID) { continue; } var density:Number = Math.min(1, rubble[i][j] / 100); if (density <= 0) { continue; } // grey var scalarR:uint = (1 - density) * 0xFF; var scalarG:uint = (1 - density) * 0xFF; var scalarB:uint = (1 - density) * 0xFF; var colorTransform:ColorTransform = new ColorTransform(0, 0, 0, 1, scalarR, scalarG, scalarB, 0); this.rubbleCanvas.graphics.beginFill(colorTransform.color, 1.0); this.rubbleCanvas.graphics.drawRect(j * g, i * g, g, g); this.rubbleCanvas.graphics.endFill(); } } } private function drawParts():void { var terrain:Array = controller.match.getMap().getTerrainTiles(); var parts:Array = controller.currentState.getParts(); var i:uint, j:uint; this.partsCanvas.graphics.clear(); this.partsCanvas.graphics.lineStyle(); var g:Number = getGridSize(); for (i = 0; i < parts.length; i++) { for (j = 0; j < parts[i].length; j++) { var tile:TerrainTile = terrain[i][j] as TerrainTile; if (tile.getType() == TerrainTile.VOID) { continue; } var density:Number = Math.min(1, parts[i][j] / 200); if (density <= 0) { continue; } this.partsCanvas.graphics.beginFill(0xCC33CC, 0.7); this.partsCanvas.graphics.drawCircle(j * g + g / 2, i * g + g / 2, density * g / 2); this.partsCanvas.graphics.endFill(); } } } private function drawUnits():void { var loc:MapLocation, i:uint, j:uint, robot:DrawRobot; var groundRobots:Object = controller.currentState.getGroundRobots(); var zombieRobots:Object = controller.currentState.getZombieRobots(); while (groundUnitCanvas.numChildren > 0) groundUnitCanvas.removeChildAt(0); while (zombieUnitCanvas.numChildren > 0) zombieUnitCanvas.removeChildAt(0); for each (robot in groundRobots) { loc = robot.getLocation(); j = (loc.getX() - origin.getX()); i = (loc.getY() - origin.getY()); robot.x = j * getGridSize() + getGridSize() / 2; robot.y = i * getGridSize() + getGridSize() / 2; robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true); groundUnitCanvas.addChild(robot); robot.draw(); } for each (robot in zombieRobots) { loc = robot.getLocation(); j = (loc.getX() - origin.getX()); i = (loc.getY() - origin.getY()); robot.x = j * getGridSize() + getGridSize() / 2; robot.y = i * getGridSize() + getGridSize() / 2; robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true); zombieUnitCanvas.addChild(robot); robot.draw(); } } private function updateUnits():void { var loc:MapLocation, i:uint, j:uint, robot:DrawRobot; var groundRobots:Object = controller.currentState.getGroundRobots(); var zombieRobots:Object = controller.currentState.getZombieRobots(); for each (robot in groundRobots) { loc = robot.getLocation(); j = (loc.getX() - origin.getX()); i = (loc.getY() - origin.getY()); robot.x = j * getGridSize() + getGridSize() / 2; robot.y = i * getGridSize() + getGridSize() / 2; if (!robot.parent && robot.isAlive()) { robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true); groundUnitCanvas.addChild(robot); } robot.draw(); } for each (robot in zombieRobots) { loc = robot.getLocation(); j = (loc.getX() - origin.getX()); i = (loc.getY() - origin.getY()); robot.x = j * getGridSize() + getGridSize() / 2; robot.y = i * getGridSize() + getGridSize() / 2; if (!robot.parent && robot.isAlive()) { robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true); zombieUnitCanvas.addChild(robot); } robot.draw(); } } /////////////////////////////////////////////////////// //////////////////// EVENT HANDLERS /////////////////// /////////////////////////////////////////////////////// private function onEnterFrame(e:Event):void { gridCanvas.visible = RenderConfiguration.showGridlines(); groundUnitCanvas.visible = RenderConfiguration.showGround(); zombieUnitCanvas.visible = RenderConfiguration.showGround(); // TODO showZombies partsCanvas.visible = RenderConfiguration.showRubble(); // TODO showParts rubbleCanvas.visible = RenderConfiguration.showRubble(); } private function onRoundChange(e:MatchEvent):void { if (e.currentRound < lastRound) { drawUnits(); } updateUnits(); drawRubble(); drawParts(); lastRound = e.currentRound; this.visible = (e.currentRound != 0); } private function onMatchChange(e:MatchEvent):void { redrawAll(); } private function onRobotSelect(e:MouseEvent):void { var x:Number, y:Number; if (RenderConfiguration.isTournament()) return; if (controller.selectedRobot && controller.selectedRobot.parent) { controller.selectedRobot.setSelected(false); x = controller.selectedRobot.x; y = controller.selectedRobot.y; controller.selectedRobot.draw(true); controller.selectedRobot.x = x; controller.selectedRobot.y = y; } var robot:DrawRobot = e.currentTarget as DrawRobot; robot.setSelected(true); x = robot.x; y = robot.y; robot.draw(true); robot.x = x; robot.y = y; controller.selectedRobot = robot; } } }
package battlecode.client.viewer.render { import battlecode.client.viewer.MatchController; import battlecode.common.MapLocation; import battlecode.common.Team; import battlecode.common.TerrainTile; import battlecode.events.MatchEvent; import battlecode.world.GameMap; import flash.events.Event; import flash.events.MouseEvent; import flash.geom.ColorTransform; import flash.geom.Rectangle; import mx.containers.Canvas; import mx.core.UIComponent; public class DrawMap extends Canvas { private var controller:MatchController; private var origin:MapLocation; // various canvases for layering and quick toggling of features private var mapCanvas:UIComponent; private var gridCanvas:UIComponent; private var rubbleCanvas:UIComponent; private var partsCanvas:UIComponent; private var groundUnitCanvas:UIComponent; private var zombieUnitCanvas:UIComponent; // optimizations for caching private var lastRound:uint = 0; public function DrawMap(controller:MatchController) { super(); this.controller = controller; this.controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange); this.controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange); this.addEventListener(Event.ENTER_FRAME, onEnterFrame); this.mapCanvas = new UIComponent(); this.gridCanvas = new UIComponent(); this.rubbleCanvas = new UIComponent(); this.partsCanvas = new UIComponent(); this.groundUnitCanvas = new UIComponent(); this.zombieUnitCanvas = new UIComponent(); this.mapCanvas.cacheAsBitmap = true; this.gridCanvas.cacheAsBitmap = true; this.addChild(mapCanvas); this.addChild(rubbleCanvas); this.addChild(partsCanvas); this.addChild(gridCanvas); this.addChild(groundUnitCanvas); this.addChild(zombieUnitCanvas); } /////////////////////////////////////////////////////// ////////////////// UTILITY METHODS //////////////////// /////////////////////////////////////////////////////// public function getMapWidth():uint { if (controller.match) return controller.match.getMap().getWidth() * RenderConfiguration.GRID_SIZE; return 0; } public function getMapHeight():uint { if (controller.match) return controller.match.getMap().getHeight() * RenderConfiguration.GRID_SIZE + 5; return 0; } private function getGridSize():Number { return RenderConfiguration.getGridSize(); } /////////////////////////////////////////////////////// ////////////////// DRAWING METHODS //////////////////// /////////////////////////////////////////////////////// public function redrawAll():void { drawMap(); drawGridlines(); drawUnits(); drawRubble(); drawParts(); var o:DrawObject; for each (o in controller.currentState.getGroundRobots()) { o.draw(true); } this.scrollRect = new Rectangle(this.mapCanvas.x, this.mapCanvas.y, getMapWidth() * RenderConfiguration.getScalingFactor(), getMapHeight() * RenderConfiguration.getScalingFactor()); } private function drawMap():void { var i:uint, j:uint, tile:TerrainTile; var map:GameMap = controller.match.getMap(); var terrain:Array = map.getTerrainTiles(); var colorTransform:ColorTransform, scalar:uint; var g:Number = getGridSize(); origin = map.getOrigin(); this.mapCanvas.graphics.clear(); // draw terrain for (i = 0; i < map.getHeight(); i++) { for (j = 0; j < map.getWidth(); j++) { tile = terrain[i][j] as TerrainTile; if (tile.getType() == TerrainTile.LAND) { scalar = 0xFF * 0.9; colorTransform = new ColorTransform(0, 0, 0, 1, scalar, scalar, scalar, 0); this.mapCanvas.graphics.beginFill(colorTransform.color, 1.0); this.mapCanvas.graphics.drawRect(j * g, i * g, g, g); this.mapCanvas.graphics.endFill(); } else { colorTransform = new ColorTransform(0, 0, 0, 1, 0x00, 0x00, 0x99, 0); this.mapCanvas.graphics.beginFill(colorTransform.color, 1.0); this.mapCanvas.graphics.drawRect(j * g, i * g, g, g); this.mapCanvas.graphics.endFill(); } } } // draw void outlines for (i = 0; i < map.getHeight(); i++) { for (j = 0; j < map.getWidth(); j++) { tile = terrain[i][j] as TerrainTile; if (tile.getType() == TerrainTile.VOID) { this.mapCanvas.graphics.lineStyle(2, 0xFFFFFF); if (i > 0 && terrain[i-1][j].getType() == TerrainTile.LAND) { this.mapCanvas.graphics.moveTo(j * g, i * g); this.mapCanvas.graphics.lineTo((j + 1) * g, i * g); } if (j > 0 && terrain[i][j-1].getType() == TerrainTile.LAND) { this.mapCanvas.graphics.moveTo(j * g, i * g); this.mapCanvas.graphics.lineTo(j * g, (i + 1) * g); } if (i < map.getHeight() - 1 && terrain[i+1][j].getType() == TerrainTile.LAND) { this.mapCanvas.graphics.moveTo(j * g, (i + 1) * g); this.mapCanvas.graphics.lineTo((j + 1) * g, (i + 1) * g); } if (j < map.getWidth() - 1 && terrain[i][j+1].getType() == TerrainTile.LAND) { this.mapCanvas.graphics.moveTo((j + 1) * g, i * g); this.mapCanvas.graphics.lineTo((j + 1) * g, (i + 1) * g); } this.mapCanvas.graphics.lineStyle(); } } } } private function drawGridlines():void { var i:uint, j:uint; var map:GameMap = controller.match.getMap(); this.gridCanvas.graphics.clear(); for (i = 0; i < map.getHeight(); i++) { for (j = 0; j < map.getWidth(); j++) { this.gridCanvas.graphics.lineStyle(.5, 0x999999, 0.3); this.gridCanvas.graphics.drawRect(j * getGridSize(), i * getGridSize(), getGridSize(), getGridSize()); } } } private function drawRubble():void { var terrain:Array = controller.match.getMap().getTerrainTiles(); var rubble:Array = controller.currentState.getRubble(); var i:uint, j:uint; this.rubbleCanvas.graphics.clear(); this.rubbleCanvas.graphics.lineStyle(); var g:Number = getGridSize(); for (i = 0; i < rubble.length; i++) { for (j = 0; j < rubble[i].length; j++) { var tile:TerrainTile = terrain[i][j] as TerrainTile; if (tile.getType() == TerrainTile.VOID) { continue; } var density:Number = Math.min(1, rubble[i][j] / 100); if (density <= .5) { continue; } var color:uint = density < 1 ? 0x999999 : 0x000000; this.rubbleCanvas.graphics.beginFill(color, 1.0); this.rubbleCanvas.graphics.drawRect(j * g, i * g, g, g); this.rubbleCanvas.graphics.endFill(); } } } private function drawParts():void { var terrain:Array = controller.match.getMap().getTerrainTiles(); var parts:Array = controller.currentState.getParts(); var i:uint, j:uint; this.partsCanvas.graphics.clear(); this.partsCanvas.graphics.lineStyle(); var g:Number = getGridSize(); for (i = 0; i < parts.length; i++) { for (j = 0; j < parts[i].length; j++) { var tile:TerrainTile = terrain[i][j] as TerrainTile; if (tile.getType() == TerrainTile.VOID) { continue; } var density:Number = Math.min(1, parts[i][j] / 200); if (density <= 0) { continue; } this.partsCanvas.graphics.beginFill(0xCC33CC, 0.7); this.partsCanvas.graphics.drawCircle(j * g + g / 2, i * g + g / 2, density * g / 2); this.partsCanvas.graphics.endFill(); } } } private function drawUnits():void { var loc:MapLocation, i:uint, j:uint, robot:DrawRobot; var groundRobots:Object = controller.currentState.getGroundRobots(); var zombieRobots:Object = controller.currentState.getZombieRobots(); while (groundUnitCanvas.numChildren > 0) groundUnitCanvas.removeChildAt(0); while (zombieUnitCanvas.numChildren > 0) zombieUnitCanvas.removeChildAt(0); for each (robot in groundRobots) { loc = robot.getLocation(); j = (loc.getX() - origin.getX()); i = (loc.getY() - origin.getY()); robot.x = j * getGridSize() + getGridSize() / 2; robot.y = i * getGridSize() + getGridSize() / 2; robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true); groundUnitCanvas.addChild(robot); robot.draw(); } for each (robot in zombieRobots) { loc = robot.getLocation(); j = (loc.getX() - origin.getX()); i = (loc.getY() - origin.getY()); robot.x = j * getGridSize() + getGridSize() / 2; robot.y = i * getGridSize() + getGridSize() / 2; robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true); zombieUnitCanvas.addChild(robot); robot.draw(); } } private function updateUnits():void { var loc:MapLocation, i:uint, j:uint, robot:DrawRobot; var groundRobots:Object = controller.currentState.getGroundRobots(); var zombieRobots:Object = controller.currentState.getZombieRobots(); for each (robot in groundRobots) { loc = robot.getLocation(); j = (loc.getX() - origin.getX()); i = (loc.getY() - origin.getY()); robot.x = j * getGridSize() + getGridSize() / 2; robot.y = i * getGridSize() + getGridSize() / 2; if (!robot.parent && robot.isAlive()) { robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true); groundUnitCanvas.addChild(robot); } robot.draw(); } for each (robot in zombieRobots) { loc = robot.getLocation(); j = (loc.getX() - origin.getX()); i = (loc.getY() - origin.getY()); robot.x = j * getGridSize() + getGridSize() / 2; robot.y = i * getGridSize() + getGridSize() / 2; if (!robot.parent && robot.isAlive()) { robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true); zombieUnitCanvas.addChild(robot); } robot.draw(); } } /////////////////////////////////////////////////////// //////////////////// EVENT HANDLERS /////////////////// /////////////////////////////////////////////////////// private function onEnterFrame(e:Event):void { gridCanvas.visible = RenderConfiguration.showGridlines(); groundUnitCanvas.visible = RenderConfiguration.showGround(); zombieUnitCanvas.visible = RenderConfiguration.showGround(); // TODO showZombies partsCanvas.visible = RenderConfiguration.showRubble(); // TODO showParts rubbleCanvas.visible = RenderConfiguration.showRubble(); } private function onRoundChange(e:MatchEvent):void { if (e.currentRound < lastRound) { drawUnits(); } updateUnits(); drawRubble(); drawParts(); lastRound = e.currentRound; this.visible = (e.currentRound != 0); } private function onMatchChange(e:MatchEvent):void { redrawAll(); } private function onRobotSelect(e:MouseEvent):void { var x:Number, y:Number; if (RenderConfiguration.isTournament()) return; if (controller.selectedRobot && controller.selectedRobot.parent) { controller.selectedRobot.setSelected(false); x = controller.selectedRobot.x; y = controller.selectedRobot.y; controller.selectedRobot.draw(true); controller.selectedRobot.x = x; controller.selectedRobot.y = y; } var robot:DrawRobot = e.currentTarget as DrawRobot; robot.setSelected(true); x = robot.x; y = robot.y; robot.draw(true); robot.x = x; robot.y = y; controller.selectedRobot = robot; } } }
make rubble easier to see
make rubble easier to see
ActionScript
mit
trun/battlecode-webclient
be0eaf6a2214eb1330e3f2eb1b303ff38c3d4af7
src/as/com/threerings/util/Assert.as
src/as/com/threerings/util/Assert.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.system.Capabilities; /** * Simple implementation of assertion checks for debug environments. * When running in a debug player, each function will test the assert expression, * and if it fails, log an error message with a stack trace. When running in a * release player, these functions do not run any tests, and exit immediately. * * Note: stack dumping is controlled via the Assert.dumpStack parameter. * * Usage example: * <pre> * Assert.isNotNull(mystack.top()); * Assert.isTrue(mystack.length == 1, "Unexpected number of items on stack!"); * </pre> */ public class Assert { /** Controls whether stack dumps should be included in the error log (default value is true).*/ public static var dumpStack :Boolean = true; /** Asserts that the value is equal to null. */ public static function isNull (value :*, message :String = null) :void { if (_debug && ! (value == null)) { fail(message); } } /** Asserts that the value is not equal to null. */ public static function isNotNull (value :*, message :String = null) :void { if (_debug && ! (value != null)) { fail(message); } } /** Asserts that the value is false. */ public static function isFalse (value :Boolean, message :String = null) :void { if (_debug && value) { fail(message); } } /** Asserts that the value is true. */ public static function isTrue (value :Boolean, message :String = null) :void { if (_debug && ! value) { fail(message); } } /** Displays an error message, with an optional stack trace. */ public static function fail (message :String) :void { _log.warning("Failure" + ((message != null) ? (": " + message) : "")); if (dumpStack) { _log.warning(new Error("dumpStack").getStackTrace()); } } protected static var _log :Log = Log.getLog(Assert); protected static var _debug :Boolean = Capabilities.isDebugger; } }
// // $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.system.Capabilities; /** * Simple implementation of assertion checks for debug environments. * When running in a debug player, each function will test the assert expression, * and if it fails, log an error message with a stack trace. When running in a * release player, these functions do not run any tests, and exit immediately. * * Note: stack dumping is controlled via the Assert.dumpStack parameter. * * Usage example: * <pre> * Assert.isNotNull(mystack.top()); * Assert.isTrue(mystack.length == 1, "Unexpected number of items on stack!"); * </pre> */ public class Assert { /** Controls whether stack dumps should be included in the error log (default value is true).*/ public static var dumpStack :Boolean = true; /** Asserts that the value is equal to null. */ public static function isNull (value :Object, message :String = null) :void { if (_debug && ! (value == null)) { fail(message); } } /** Asserts that the value is not equal to null. */ public static function isNotNull (value :Object, message :String = null) :void { if (_debug && ! (value != null)) { fail(message); } } /** Asserts that the value is false. */ public static function isFalse (value :Boolean, message :String = null) :void { if (_debug && value) { fail(message); } } /** Asserts that the value is true. */ public static function isTrue (value :Boolean, message :String = null) :void { if (_debug && ! value) { fail(message); } } /** Displays an error message, with an optional stack trace. */ public static function fail (message :String) :void { _log.warning("Failure" + ((message != null) ? (": " + message) : "")); if (dumpStack) { _log.warning(new Error("dumpStack").getStackTrace()); } } protected static var _log :Log = Log.getLog(Assert); protected static var _debug :Boolean = Capabilities.isDebugger; } }
Make it explicit in the function signature that we're just doing an "Object == null" comparison. Otherwise the user might pass in an undefined, and expect a strict equality test.
Make it explicit in the function signature that we're just doing an "Object == null" comparison. Otherwise the user might pass in an undefined, and expect a strict equality test. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4886 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
871a0211160477e25b9555716bb35c50e692bf44
as3/com/netease/protobuf/WritingBuffer.as
as3/com/netease/protobuf/WritingBuffer.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.errors.*; import flash.utils.*; public final class WritingBuffer extends ByteArray { private const _slices:ByteArray = new ByteArray public function beginBlock():uint { _slices.writeUnsignedInt(position) const beginSliceIndex:uint = _slices.length if (beginSliceIndex % 8 != 4) { throw new IllegalOperationError } _slices.writeDouble(0) _slices.writeUnsignedInt(position) return beginSliceIndex } public function endBlock(beginSliceIndex:uint):void { if (_slices.length % 8 != 0) { throw new IllegalOperationError } _slices.writeUnsignedInt(position) _slices.position = beginSliceIndex + 8 const beginPosition:uint = _slices.readUnsignedInt() _slices.position = beginSliceIndex _slices.writeUnsignedInt(position) WriteUtils.write_TYPE_UINT32(this, position - beginPosition) _slices.writeUnsignedInt(position) _slices.position = _slices.length _slices.writeUnsignedInt(position) } public function toNormal(output:IDataOutput):void { if (_slices.length % 8 != 0) { throw new IllegalOperationError } _slices.position = 0 var begin:uint = 0 while (_slices.bytesAvailable > 0) { var end:uint = _slices.readUnsignedInt() if (end > begin) { output.writeBytes(this, begin, end - begin) } else if (end < begin) { throw new IllegalOperationError } begin = _slices.readUnsignedInt() } if (begin < length) { output.writeBytes(this, begin) } } } }
// 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.errors.*; import flash.utils.*; /** * @private */ public final class WritingBuffer extends ByteArray { private const _slices:ByteArray = new ByteArray public function beginBlock():uint { _slices.writeUnsignedInt(position) const beginSliceIndex:uint = _slices.length if (beginSliceIndex % 8 != 4) { throw new IllegalOperationError } _slices.writeDouble(0) _slices.writeUnsignedInt(position) return beginSliceIndex } public function endBlock(beginSliceIndex:uint):void { if (_slices.length % 8 != 0) { throw new IllegalOperationError } _slices.writeUnsignedInt(position) _slices.position = beginSliceIndex + 8 const beginPosition:uint = _slices.readUnsignedInt() _slices.position = beginSliceIndex _slices.writeUnsignedInt(position) WriteUtils.write_TYPE_UINT32(this, position - beginPosition) _slices.writeUnsignedInt(position) _slices.position = _slices.length _slices.writeUnsignedInt(position) } public function toNormal(output:IDataOutput):void { if (_slices.length % 8 != 0) { throw new IllegalOperationError } _slices.position = 0 var begin:uint = 0 while (_slices.bytesAvailable > 0) { var end:uint = _slices.readUnsignedInt() if (end > begin) { output.writeBytes(this, begin, end - begin) } else if (end < begin) { throw new IllegalOperationError } begin = _slices.readUnsignedInt() } if (begin < length) { output.writeBytes(this, begin) } } } }
把 WritingBuffer 标记为 @private
把 WritingBuffer 标记为 @private
ActionScript
bsd-2-clause
tconkling/protoc-gen-as3
61f7ca778b4edf7c0a02d3c47b37bcc67676d8bb
tests/visual/text/src/text/TextState.as
tests/visual/text/src/text/TextState.as
package text { import flash.system.Capabilities; import org.flixel.*; public class TextState extends FlxState { override public function create():void { var os:String = Capabilities.version.substr(0, 3); var isMobile:Boolean = false; if (os == "AND") { isMobile = true; } else { var mobileSystems:Array = new Array("Windows SmartPhone", "Windows PocketPC", "Windows Mobile"); isMobile = (mobileSystems.indexOf(Capabilities.os) != -1) } var helloWorld:FlxText = new FlxText(10, 10, 620, String(isMobile)) helloWorld.setFormat("system", 16, FlxG.WHITE, "center", FlxG.PINK) add(helloWorld) var leftAlignedText:FlxText = new FlxText(10, 70, 150, "This text is left-aligned") leftAlignedText.setFormat("system", 16, FlxG.RED, "left") add(leftAlignedText) var rightAlignedText:FlxText = new FlxText(480, 70, 150, "This text is right-aligned") rightAlignedText.setFormat("system", 16, FlxG.GREEN, "right") add(rightAlignedText) var abouFlixel:FlxText = new FlxText(10, 140, 620, "Flixel is an open source game-making library that is completely free for personal or commercial use. Written entirely in ActionScript 3 by Adam “Atomic” Saltsman, and designed to be used with free development tools, Flixel is easy to learn, extend and customize.") abouFlixel.setFormat("system", 15, FlxG.BLUE, "left") add(abouFlixel) } } }
package text { import org.flixel.*; public class TextState extends FlxState { override public function create():void { var helloWorld:FlxText = new FlxText(10, 10, 620, "Hello World!") helloWorld.setFormat("system", 16, FlxG.WHITE, "center", FlxG.PINK) add(helloWorld) var leftAlignedText:FlxText = new FlxText(10, 70, 150, "This text is left-aligned") leftAlignedText.setFormat("system", 16, FlxG.RED, "left") add(leftAlignedText) var rightAlignedText:FlxText = new FlxText(480, 70, 150, "This text is right-aligned") rightAlignedText.setFormat("system", 16, FlxG.GREEN, "right") add(rightAlignedText) var abouFlixel:FlxText = new FlxText(10, 140, 620, "Flixel is an open source game-making library that is completely free for personal or commercial use. Written entirely in ActionScript 3 by Adam “Atomic” Saltsman, and designed to be used with free development tools, Flixel is easy to learn, extend and customize.") abouFlixel.setFormat("system", 15, FlxG.BLUE, "left") add(abouFlixel) } } }
Reset text test changes
Reset text test changes
ActionScript
mit
devolonter/flixel-monkey,devolonter/flixel-monkey,devolonter/flixel-monkey,devolonter/flixel-monkey
a4dbc498709041017f64f28b505dbd987f6ff7fd
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; import flash.utils.setTimeout; [SWF(width="400", height="300")] public class swfcat extends Sprite { /* David's bridge (nickname eRYaZuvY02FpExln) that also serves a crossdomain policy. */ private const DEFAULT_TOR_ADDR:Object = { // host: "173.255.221.44", 3VXRyxz67OeRoqHn host: "69.164.193.231", port: 9001 }; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Socket to facilitator. private var s_f:Socket; private var output_text:TextField; private var fac_addr:Object; public function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { output_text = new TextField(); output_text.width = 400; output_text.height = 300; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); fac_spec = this.loaderInfo.parameters["facilitator"]; if (!fac_spec) { puts("Error: no \"facilitator\" specification provided."); return; } puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } main(); } /* The main logic begins here, after start-up issues are taken care of. */ private function main():void { s_f = new Socket(); s_f.addEventListener(Event.CONNECT, fac_connected); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: closed connection."); setTimeout(main, FACILITATOR_POLL_INTERVAL); }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + "."); s_f.connect(fac_addr.host, fac_addr.port); } private function fac_connected(e:Event):void { puts("Facilitator: connected."); s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data); s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); } private function fac_data(e:ProgressEvent):void { var client_spec:String; var client_addr:Object; var proxy_pair:Object; client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8"); puts("Facilitator: got \"" + client_spec + "\""); client_addr = parse_addr_spec(client_spec); if (!client_addr) { puts("Error: Client spec must be in the form \"host:port\"."); return; } if (client_addr.host == "0.0.0.0" && client_addr.port == 0) { puts("Error: Facilitator has no clients."); return; } proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR); proxy_pair.connect(); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.Socket; import flash.utils.ByteArray; /* An instance of a client-relay connection. */ class ProxyPair { // Address ({host, port}) of client. private var addr_c:Object; // Address ({host, port}) of relay. private var addr_r:Object; // Socket to client. private var s_c:Socket; // Socket to relay. private var s_r:Socket; // Parent swfcat, for UI updates. private var ui:swfcat; private function log(msg:String):void { ui.puts(id() + ": " + msg) } // String describing this pair for output. private function id():String { return "<" + this.addr_c.host + ":" + this.addr_c.port + "," + this.addr_r.host + ":" + this.addr_r.port + ">"; } public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object) { this.ui = ui; this.addr_c = addr_c; this.addr_r = addr_r; } public function connect():void { s_r = new Socket(); s_r.addEventListener(Event.CONNECT, tor_connected); s_r.addEventListener(Event.CLOSE, function (e:Event):void { log("Tor: closed."); if (s_c.connected) s_c.close(); }); s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); }); s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); }); log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + "."); s_r.connect(addr_r.host, addr_r.port); } private function tor_connected(e:Event):void { log("Tor: connected."); s_c = new Socket(); s_c.addEventListener(Event.CONNECT, client_connected); s_c.addEventListener(Event.CLOSE, function (e:Event):void { log("Client: closed."); if (s_r.connected) s_r.close(); }); s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Client: I/O error: " + e.text + "."); if (s_r.connected) s_r.close(); }); s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Client: security error: " + e.text + "."); if (s_r.connected) s_r.close(); }); log("Client: connecting to " + addr_c.host + ":" + addr_c.port + "."); s_c.connect(addr_c.host, addr_c.port); } private function client_connected(e:Event):void { log("Client: connected."); s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_r.readBytes(bytes, 0, e.bytesLoaded); log("Tor: read " + bytes.length + "."); s_c.writeBytes(bytes); }); s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_c.readBytes(bytes, 0, e.bytesLoaded); log("Client: read " + bytes.length + "."); s_r.writeBytes(bytes); }); } }
package { import flash.display.Sprite; import flash.text.TextField; import flash.net.Socket; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.utils.ByteArray; import flash.utils.setTimeout; [SWF(width="640", height="480")] public class swfcat extends Sprite { /* David's bridge (nickname eRYaZuvY02FpExln) that also serves a crossdomain policy. */ private const DEFAULT_TOR_ADDR:Object = { // host: "173.255.221.44", 3VXRyxz67OeRoqHn host: "69.164.193.231", port: 9001 }; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Socket to facilitator. private var s_f:Socket; private var output_text:TextField; private var fac_addr:Object; public function puts(s:String):void { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } public function swfcat() { output_text = new TextField(); output_text.width = 640; output_text.height = 480; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44CC44; addChild(output_text); puts("Starting."); // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } private function loaderinfo_complete(e:Event):void { var fac_spec:String; puts("Parameters loaded."); fac_spec = this.loaderInfo.parameters["facilitator"]; if (!fac_spec) { puts("Error: no \"facilitator\" specification provided."); return; } puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } main(); } /* The main logic begins here, after start-up issues are taken care of. */ private function main():void { s_f = new Socket(); s_f.addEventListener(Event.CONNECT, fac_connected); s_f.addEventListener(Event.CLOSE, function (e:Event):void { puts("Facilitator: closed connection."); setTimeout(main, FACILITATOR_POLL_INTERVAL); }); s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { puts("Facilitator: I/O error: " + e.text + "."); }); s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { puts("Facilitator: security error: " + e.text + "."); }); puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + "."); s_f.connect(fac_addr.host, fac_addr.port); } private function fac_connected(e:Event):void { puts("Facilitator: connected."); s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data); s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n"); } private function fac_data(e:ProgressEvent):void { var client_spec:String; var client_addr:Object; var proxy_pair:Object; client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8"); puts("Facilitator: got \"" + client_spec + "\""); client_addr = parse_addr_spec(client_spec); if (!client_addr) { puts("Error: Client spec must be in the form \"host:port\"."); return; } if (client_addr.host == "0.0.0.0" && client_addr.port == 0) { puts("Error: Facilitator has no clients."); return; } proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR); proxy_pair.connect(); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private static function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.display.Sprite; import flash.events.Event; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.Socket; import flash.utils.ByteArray; /* An instance of a client-relay connection. */ class ProxyPair { // Address ({host, port}) of client. private var addr_c:Object; // Address ({host, port}) of relay. private var addr_r:Object; // Socket to client. private var s_c:Socket; // Socket to relay. private var s_r:Socket; // Parent swfcat, for UI updates. private var ui:swfcat; private function log(msg:String):void { ui.puts(id() + ": " + msg) } // String describing this pair for output. private function id():String { return "<" + this.addr_c.host + ":" + this.addr_c.port + "," + this.addr_r.host + ":" + this.addr_r.port + ">"; } public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object) { this.ui = ui; this.addr_c = addr_c; this.addr_r = addr_r; } public function connect():void { s_r = new Socket(); s_r.addEventListener(Event.CONNECT, tor_connected); s_r.addEventListener(Event.CLOSE, function (e:Event):void { log("Tor: closed."); if (s_c.connected) s_c.close(); }); s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Tor: I/O error: " + e.text + "."); if (s_c.connected) s_c.close(); }); s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Tor: security error: " + e.text + "."); if (s_c.connected) s_c.close(); }); log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + "."); s_r.connect(addr_r.host, addr_r.port); } private function tor_connected(e:Event):void { log("Tor: connected."); s_c = new Socket(); s_c.addEventListener(Event.CONNECT, client_connected); s_c.addEventListener(Event.CLOSE, function (e:Event):void { log("Client: closed."); if (s_r.connected) s_r.close(); }); s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void { log("Client: I/O error: " + e.text + "."); if (s_r.connected) s_r.close(); }); s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void { log("Client: security error: " + e.text + "."); if (s_r.connected) s_r.close(); }); log("Client: connecting to " + addr_c.host + ":" + addr_c.port + "."); s_c.connect(addr_c.host, addr_c.port); } private function client_connected(e:Event):void { log("Client: connected."); s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_r.readBytes(bytes, 0, e.bytesLoaded); log("Tor: read " + bytes.length + "."); s_c.writeBytes(bytes); }); s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void { var bytes:ByteArray = new ByteArray(); s_c.readBytes(bytes, 0, e.bytesLoaded); log("Client: read " + bytes.length + "."); s_r.writeBytes(bytes); }); } }
Increase size of movie to 640×480 from 400×300.
Increase size of movie to 640×480 from 400×300.
ActionScript
mit
arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy
ab7eff3c217d9b9dc398c79db84d9d4678b1d606
mustella/as3/src/mustella/WaitForLayoutManager.as
mustella/as3/src/mustella/WaitForLayoutManager.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.display.IBitmapDrawable; import flash.utils.*; import flash.net.*; import flash.events.*; import flash.display.*; import flash.geom.Matrix; /** * WaitForLayoutManager - waits for LayoutManager to complete validation * MXML attributes: * timeout (optional) */ public class WaitForLayoutManager extends TestStep { private var eventListenerListening:Boolean = false; /** * Test the value of a property, log result if failure. */ override public function execute(root:DisplayObject, context:UnitTester, testCase:TestCase, testResult:TestResult):Boolean { this.root = root; this.context = context; this.testCase = testCase; this.testResult = testResult; waitEvent = eventName; waitTarget = target; var actualTarget:Object = context.stringToObject(target); if (actualTarget) { actualTarget.addEventListener(eventName, eventListener); eventListenerListening = true; } if (numEvents < numExpectedEvents ) { testCase.setExpirationTime (getTimer() + timeout); if (!eventListenerListening) { actualTarget.addEventListener(eventName, eventListener); eventListenerListening = true; testCase.cleanupAsserts.push(this); } doStep(); waitEvent = eventName; waitTarget = target; return false; } else { testCase.setExpirationTime (0); stepComplete(); return true; } return super.execute(root, context, testCase, testResult); } /** * Test the value of a property, log result if failure. */ override protected function doStep():void { var actualTarget:Object = context.stringToObject(target); if (!actualTarget) { testResult.doFail("Target " + target + " not found"); return; } } public function doTimeout ():void { testResult.doFail("Timeout waiting for " + waitEvent + " on " + target); } /** * The object to set a property on */ private var target:String = "mx.core::UIComponentGlobals.mx_internal:layoutManager"; /** * The event to wait for */ private var eventName:String = "updateComplete"; /** * Storage for numEvents */ protected var numEvents:int = 0; /** * Number of expected events (must be > 0), use AssertNoEvent for 0. * Set to -1 if you want to see at least one event and don't care if there's more. */ public var numExpectedEvents:int = 1; /** * The event object */ private var lastEvent:Event; /** * The event listener */ protected function eventListener(event:Event):void { testCase.setExpirationTime(0); lastEvent = event; numEvents++; waitEventHandler (event); } /** * Test the value of a property, log result if failure. */ public function cleanup():void { var actualTarget:Object = context.stringToObject(target); if (actualTarget) // might be null if object was killed actualTarget.removeEventListener(eventName, eventListener); } /** * customize string representation */ override public function toString():String { var s:String = "WaitForLayoutManager"; return s; } /** * The method that gets called back when the event we're waiting on fires */ override protected function waitEventHandler(event:Event):void { // we can rely on eventListener to update lastEvent and numEvents // keep waiting if there aren't enough events if (numExpectedEvents != -1 && numEvents < numExpectedEvents) { return; } if (numExpectedEvents == numEvents) { cleanup(); testCase.setExpirationTime (0); stepComplete(); return; } waitEvent = eventName; waitTarget = target; super.waitEventHandler(event); } } }
//////////////////////////////////////////////////////////////////////////////// // // 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.display.IBitmapDrawable; import flash.utils.*; import flash.net.*; import flash.events.*; import flash.display.*; import flash.geom.Matrix; /** * WaitForLayoutManager - waits for LayoutManager to complete validation * MXML attributes: * timeout (optional) */ public class WaitForLayoutManager extends TestStep { private var eventListenerListening:Boolean = false; /** * Test the value of a property, log result if failure. */ override public function execute(root:DisplayObject, context:UnitTester, testCase:TestCase, testResult:TestResult):Boolean { this.root = root; this.context = context; this.testCase = testCase; this.testResult = testResult; waitEvent = eventName; waitTarget = target; var actualTarget:Object = context.stringToObject(target); if (actualTarget) { if (actualTarget.isInvalid()) { actualTarget.addEventListener(eventName, eventListener); eventListenerListening = true; } else { return true; } } if (numEvents < numExpectedEvents ) { testCase.setExpirationTime (getTimer() + timeout); if (!eventListenerListening) { actualTarget.addEventListener(eventName, eventListener); eventListenerListening = true; testCase.cleanupAsserts.push(this); } doStep(); waitEvent = eventName; waitTarget = target; return false; } else { testCase.setExpirationTime (0); stepComplete(); return true; } return super.execute(root, context, testCase, testResult); } /** * Test the value of a property, log result if failure. */ override protected function doStep():void { var actualTarget:Object = context.stringToObject(target); if (!actualTarget) { testResult.doFail("Target " + target + " not found"); return; } } public function doTimeout ():void { testResult.doFail("Timeout waiting for " + waitEvent + " on " + target); } /** * The object to set a property on */ private var target:String = "mx.core::UIComponentGlobals.mx_internal:layoutManager"; /** * The event to wait for */ private var eventName:String = "updateComplete"; /** * Storage for numEvents */ protected var numEvents:int = 0; /** * Number of expected events (must be > 0), use AssertNoEvent for 0. * Set to -1 if you want to see at least one event and don't care if there's more. */ public var numExpectedEvents:int = 1; /** * The event object */ private var lastEvent:Event; /** * The event listener */ protected function eventListener(event:Event):void { testCase.setExpirationTime(0); lastEvent = event; numEvents++; waitEventHandler (event); } /** * Test the value of a property, log result if failure. */ public function cleanup():void { var actualTarget:Object = context.stringToObject(target); if (actualTarget) // might be null if object was killed actualTarget.removeEventListener(eventName, eventListener); } /** * customize string representation */ override public function toString():String { var s:String = "WaitForLayoutManager"; return s; } /** * The method that gets called back when the event we're waiting on fires */ override protected function waitEventHandler(event:Event):void { // we can rely on eventListener to update lastEvent and numEvents // keep waiting if there aren't enough events if (numExpectedEvents != -1 && numEvents < numExpectedEvents) { return; } if (numExpectedEvents == numEvents) { cleanup(); testCase.setExpirationTime (0); stepComplete(); return; } waitEvent = eventName; waitTarget = target; super.waitEventHandler(event); } } }
Make WaitForLayoutManager smarter. It checks to see if it needs to wait or not.
Make WaitForLayoutManager smarter. It checks to see if it needs to wait or not. git-svn-id: 7d913817b0a978d84de757191e4bce372605a781@1381412 13f79535-47bb-0310-9956-ffa450edef68
ActionScript
apache-2.0
adufilie/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk
0b1662715e4a6f62f8522dd35c07ea3da64ef965
src/aerys/minko/type/data/DataBindings.as
src/aerys/minko/type/data/DataBindings.as
package aerys.minko.type.data { import aerys.minko.type.Signal; import aerys.minko.type.enum.DataProviderUsage; import flash.utils.Dictionary; public class DataBindings { private var _numProviders : uint = 0; private var _providers : Vector.<IDataProvider> = new <IDataProvider>[]; private var _bindingNames : Vector.<String> = new Vector.<String>(); private var _bindingNameToValue : Object = {}; private var _bindingNameToChangedSignal : Object = {}; private var _bindingNameToProvider : Dictionary = new Dictionary(); private var _providerToBindingNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]] private var _attributeToProviders : Dictionary = new Dictionary(); // dic[Vector.<IDataProvider>[]] private var _attributeToProvidersAttrNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]] public function get numProviders() : uint { return _numProviders; } public function get numProperties() : uint { return _bindingNames.length; } public function DataBindings() { } public function contains(dataProvider : IDataProvider) : Boolean { return _providers.indexOf(dataProvider) != -1; } public function addProvider(provider : IDataProvider) : void { if (_providerToBindingNames[provider]) throw new Error('This provider is already bound.'); var providerBindingNames : Vector.<String> = new Vector.<String>(); var dataDescriptor : Object = provider.dataDescriptor; provider.changed.add(providerChangedHandler); for (var attrName : String in dataDescriptor) { // if this provider attribute is also a dataprovider, let's also bind it var bindingName : String = dataDescriptor[attrName]; var attribute : Object = provider[attrName] var dpAttribute : IMonitoredData = attribute as IMonitoredData; if (_bindingNames.indexOf(bindingName) != -1) throw new Error( 'Another Dataprovider is already declaring the \'' + bindingName + '\' property.' ); _bindingNameToProvider[bindingName] = provider; if (dpAttribute != null) { dpAttribute.changed.add(providerPropertyChangedHandler); _attributeToProviders[dpAttribute] ||= new <IDataProvider>[]; _attributeToProvidersAttrNames[dpAttribute] ||= new <String>[]; _attributeToProviders[dpAttribute].push(provider); _attributeToProvidersAttrNames[dpAttribute].push(attrName); } _bindingNameToValue[bindingName] = attribute; providerBindingNames.push(bindingName); _bindingNames.push(bindingName); if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, attribute); } _providerToBindingNames[provider] = providerBindingNames; _providers.push(provider); ++_numProviders; } public function removeProvider(provider : IDataProvider) : void { var bindingNames : Vector.<String> = _providerToBindingNames[provider]; if (bindingNames == null) throw new ArgumentError('Unkown provider.'); for each (var bindingName : String in bindingNames) { var indexOf : int = _bindingNames.indexOf(bindingName); _bindingNames.splice(indexOf, 1); if (_bindingNameToValue[bindingName] is IDataProvider) IDataProvider(_bindingNameToValue[bindingName]).changed.remove(providerPropertyChangedHandler); delete _bindingNameToValue[bindingName]; delete _bindingNameToProvider[bindingName]; } var attributesToDelete : Vector.<Object> = new Vector.<Object>(); for (var attribute : Object in _attributeToProviders) { var providers : Vector.<IDataProvider> = _attributeToProviders[attribute]; var attrNames : Vector.<String> = _attributeToProvidersAttrNames[attribute]; var indexOfProvider : int = providers.indexOf(provider); if (indexOfProvider != -1) { providers.splice(indexOfProvider, 1); attrNames.splice(indexOfProvider, 1); } if (providers.length == 0) attributesToDelete.push(attribute); } for (var attributeToDelete : Object in attributesToDelete) { delete _attributeToProviders[attributeToDelete]; delete _attributeToProvidersAttrNames[attributeToDelete]; } provider.changed.remove(providerChangedHandler); --_numProviders; _providers.splice(_providers.indexOf(provider), 1); delete _providerToBindingNames[provider]; for each (bindingName in bindingNames) if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, null); } public function removeAllProviders() : void { var numProviders : uint = this.numProviders; for (var providerId : uint = 0; providerId < numProviders; ++providerId) removeProvider(getProviderAt(providerId)); } public function hasCallback(bindingName : String, callback : Function) : Boolean { var signal : Signal = _bindingNameToChangedSignal[bindingName]; return signal != null && signal.hasCallback(callback); } public function addCallback(bindingName : String, callback : Function) : void { _bindingNameToChangedSignal[bindingName] ||= new Signal('DataBindings.changed[' + bindingName + ']'); Signal(_bindingNameToChangedSignal[bindingName]).add(callback); } public function removeCallback(bindingName : String, callback : Function) : void { var signal : Signal = _bindingNameToChangedSignal[bindingName]; if (!signal) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); signal.remove(callback); if (signal.numCallbacks == 0) delete _bindingNameToChangedSignal[bindingName]; } public function getProviderAt(index : uint) : IDataProvider { return _providers[index]; } public function getProviderByBindingName(bindingName : String) : IDataProvider { if (_bindingNameToProvider[bindingName] == null) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); return _bindingNameToProvider[bindingName]; } public function propertyExists(bindingName : String) : Boolean { return _bindingNameToValue.hasOwnProperty(bindingName); } public function getProperty(bindingName : String) : * { return _bindingNameToValue[bindingName]; } public function getPropertyName(bindingIndex : uint) : String { if (bindingIndex > numProperties) throw new ArgumentError('No such binding'); return _bindingNames[bindingIndex]; } public function copySharedProvidersFrom(source : DataBindings) : void { var numProviders : uint = source._providers.length; for (var providerId : uint = 0; providerId < numProviders; ++providerId) { var provider : IDataProvider = source._providers[providerId]; if (provider.usage == DataProviderUsage.SHARED) addProvider(provider); } } private function providerChangedHandler(source : IDataProvider, attributeName : String) : void { if (attributeName == null) { throw new Error('DataProviders must change one property at a time.'); } else if (attributeName == 'dataDescriptor') { removeProvider(source); addProvider(source); } else { var bindingName : String = source.dataDescriptor[attributeName]; var oldDpValue : IDataProvider = _bindingNameToValue[bindingName] as IDataProvider; var newValue : Object = source[attributeName]; var newDpValue : IDataProvider = newValue as IDataProvider; // we are replacing a data provider. We must remove listeners and related mapping keys if (oldDpValue != null) { oldDpValue.changed.remove(providerPropertyChangedHandler); var providers : Vector.<IDataProvider> = _attributeToProviders[oldDpValue]; var attrNames : Vector.<String> = _attributeToProvidersAttrNames[oldDpValue]; if (providers.length == 1) { delete _attributeToProviders[oldDpValue]; delete _attributeToProvidersAttrNames[oldDpValue]; } else { var index : uint = providers.indexOf(source); providers.splice(index, 1); attrNames.splice(index, 1); } } // the new value for this key is a dataprovider, we must listen changes. if (newDpValue != null) { newDpValue.changed.add(providerPropertyChangedHandler); _attributeToProviders[newDpValue] ||= new <IDataProvider>[]; _attributeToProvidersAttrNames[newDpValue] ||= new <String>[]; _attributeToProviders[newDpValue].push(source); _attributeToProvidersAttrNames[newDpValue].push(attributeName); } _bindingNameToValue[bindingName] = newValue; if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, newValue); } } private function providerPropertyChangedHandler(source : IMonitoredData, key : String) : void { var providers : Vector.<IDataProvider> = _attributeToProviders[source]; var attrNames : Vector.<String> = _attributeToProvidersAttrNames[source]; var numProviders : uint = providers.length; for (var providerId : uint = 0; providerId < numProviders; ++providerId) { var provider : IDataProvider = providers[providerId]; var attrName : String = attrNames[providerId]; var bindingName : String = provider.dataDescriptor[attrName]; if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, source); } } } }
package aerys.minko.type.data { import aerys.minko.type.Signal; import aerys.minko.type.enum.DataProviderUsage; import flash.utils.Dictionary; public class DataBindings { private var _numProviders : uint = 0; private var _providers : Vector.<IDataProvider> = new <IDataProvider>[]; private var _bindingNames : Vector.<String> = new Vector.<String>(); private var _bindingNameToValue : Object = {}; private var _bindingNameToChangedSignal : Object = {}; private var _bindingNameToProvider : Dictionary = new Dictionary(); private var _providerToBindingNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]] private var _attributeToProviders : Dictionary = new Dictionary(); // dic[Vector.<IDataProvider>[]] private var _attributeToProvidersAttrNames : Dictionary = new Dictionary(); // dic[Vector.<String>[]] public function get numProviders() : uint { return _numProviders; } public function get numProperties() : uint { return _bindingNames.length; } public function DataBindings() { } public function contains(dataProvider : IDataProvider) : Boolean { return _providers.indexOf(dataProvider) != -1; } public function addProvider(provider : IDataProvider) : void { if (_providerToBindingNames[provider]) throw new Error('This provider is already bound.'); var providerBindingNames : Vector.<String> = new Vector.<String>(); var dataDescriptor : Object = provider.dataDescriptor; provider.changed.add(providerChangedHandler); for (var attrName : String in dataDescriptor) { // if this provider attribute is also a dataprovider, let's also bind it var bindingName : String = dataDescriptor[attrName]; var attribute : Object = provider[attrName] var dpAttribute : IMonitoredData = attribute as IMonitoredData; if (_bindingNames.indexOf(bindingName) != -1) throw new Error( 'Another Dataprovider is already declaring the \'' + bindingName + '\' property.' ); _bindingNameToProvider[bindingName] = provider; if (dpAttribute != null) { dpAttribute.changed.add(providerPropertyChangedHandler); _attributeToProviders[dpAttribute] ||= new <IDataProvider>[]; _attributeToProvidersAttrNames[dpAttribute] ||= new <String>[]; _attributeToProviders[dpAttribute].push(provider); _attributeToProvidersAttrNames[dpAttribute].push(attrName); } _bindingNameToValue[bindingName] = attribute; providerBindingNames.push(bindingName); _bindingNames.push(bindingName); if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, attribute); } _providerToBindingNames[provider] = providerBindingNames; _providers.push(provider); ++_numProviders; } public function removeProvider(provider : IDataProvider) : void { var bindingNames : Vector.<String> = _providerToBindingNames[provider]; if (bindingNames == null) throw new ArgumentError('Unkown provider.'); for each (var bindingName : String in bindingNames) { var indexOf : int = _bindingNames.indexOf(bindingName); _bindingNames.splice(indexOf, 1); if (_bindingNameToValue[bindingName] is IMonitoredData) IMonitoredData(_bindingNameToValue[bindingName]).changed.remove(providerPropertyChangedHandler); delete _bindingNameToValue[bindingName]; delete _bindingNameToProvider[bindingName]; } var attributesToDelete : Vector.<Object> = new Vector.<Object>(); for (var attribute : Object in _attributeToProviders) { var providers : Vector.<IDataProvider> = _attributeToProviders[attribute]; var attrNames : Vector.<String> = _attributeToProvidersAttrNames[attribute]; var indexOfProvider : int = providers.indexOf(provider); if (indexOfProvider != -1) { providers.splice(indexOfProvider, 1); attrNames.splice(indexOfProvider, 1); } if (providers.length == 0) attributesToDelete.push(attribute); } for (var attributeToDelete : Object in attributesToDelete) { delete _attributeToProviders[attributeToDelete]; delete _attributeToProvidersAttrNames[attributeToDelete]; } provider.changed.remove(providerChangedHandler); --_numProviders; _providers.splice(_providers.indexOf(provider), 1); delete _providerToBindingNames[provider]; for each (bindingName in bindingNames) if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, null); } public function removeAllProviders() : void { var numProviders : uint = this.numProviders; for (var providerId : uint = 0; providerId < numProviders; ++providerId) removeProvider(getProviderAt(providerId)); } public function hasCallback(bindingName : String, callback : Function) : Boolean { var signal : Signal = _bindingNameToChangedSignal[bindingName]; return signal != null && signal.hasCallback(callback); } public function addCallback(bindingName : String, callback : Function) : void { _bindingNameToChangedSignal[bindingName] ||= new Signal('DataBindings.changed[' + bindingName + ']'); Signal(_bindingNameToChangedSignal[bindingName]).add(callback); } public function removeCallback(bindingName : String, callback : Function) : void { var signal : Signal = _bindingNameToChangedSignal[bindingName]; if (!signal) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); signal.remove(callback); if (signal.numCallbacks == 0) delete _bindingNameToChangedSignal[bindingName]; } public function getProviderAt(index : uint) : IDataProvider { return _providers[index]; } public function getProviderByBindingName(bindingName : String) : IDataProvider { if (_bindingNameToProvider[bindingName] == null) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); return _bindingNameToProvider[bindingName]; } public function propertyExists(bindingName : String) : Boolean { return _bindingNameToValue.hasOwnProperty(bindingName); } public function getProperty(bindingName : String) : * { return _bindingNameToValue[bindingName]; } public function getPropertyName(bindingIndex : uint) : String { if (bindingIndex > numProperties) throw new ArgumentError('No such binding'); return _bindingNames[bindingIndex]; } public function copySharedProvidersFrom(source : DataBindings) : void { var numProviders : uint = source._providers.length; for (var providerId : uint = 0; providerId < numProviders; ++providerId) { var provider : IDataProvider = source._providers[providerId]; if (provider.usage == DataProviderUsage.SHARED) addProvider(provider); } } private function providerChangedHandler(source : IDataProvider, attributeName : String) : void { if (attributeName == null) { throw new Error('DataProviders must change one property at a time.'); } else if (attributeName == 'dataDescriptor') { removeProvider(source); addProvider(source); } else { var bindingName : String = source.dataDescriptor[attributeName]; var oldDpValue : IDataProvider = _bindingNameToValue[bindingName] as IDataProvider; var newValue : Object = source[attributeName]; var newDpValue : IDataProvider = newValue as IDataProvider; // we are replacing a data provider. We must remove listeners and related mapping keys if (oldDpValue != null) { oldDpValue.changed.remove(providerPropertyChangedHandler); var providers : Vector.<IDataProvider> = _attributeToProviders[oldDpValue]; var attrNames : Vector.<String> = _attributeToProvidersAttrNames[oldDpValue]; if (providers.length == 1) { delete _attributeToProviders[oldDpValue]; delete _attributeToProvidersAttrNames[oldDpValue]; } else { var index : uint = providers.indexOf(source); providers.splice(index, 1); attrNames.splice(index, 1); } } // the new value for this key is a dataprovider, we must listen changes. if (newDpValue != null) { newDpValue.changed.add(providerPropertyChangedHandler); _attributeToProviders[newDpValue] ||= new <IDataProvider>[]; _attributeToProvidersAttrNames[newDpValue] ||= new <String>[]; _attributeToProviders[newDpValue].push(source); _attributeToProvidersAttrNames[newDpValue].push(attributeName); } _bindingNameToValue[bindingName] = newValue; if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, newValue); } } private function providerPropertyChangedHandler(source : IMonitoredData, key : String) : void { var providers : Vector.<IDataProvider> = _attributeToProviders[source]; var attrNames : Vector.<String> = _attributeToProvidersAttrNames[source]; var numProviders : uint = providers.length; for (var providerId : uint = 0; providerId < numProviders; ++providerId) { var provider : IDataProvider = providers[providerId]; var attrName : String = attrNames[providerId]; var bindingName : String = provider.dataDescriptor[attrName]; if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, source); } } } }
Fix minor bug
Fix minor bug
ActionScript
mit
aerys/minko-as3
89fef8992be209658318682c18a0b9544ee7937f
src/as/com/threerings/flex/CommandMenu.as
src/as/com/threerings/flex/CommandMenu.as
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // 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.flex { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.IEventDispatcher; import flash.geom.Point; import flash.geom.Rectangle; import mx.controls.Menu; import mx.controls.listClasses.BaseListData; import mx.controls.listClasses.IListItemRenderer; import mx.controls.menuClasses.IMenuItemRenderer; import mx.controls.menuClasses.MenuListData; import mx.core.mx_internal; import mx.core.Application; import mx.core.ClassFactory; import mx.core.IFlexDisplayObject; import mx.core.ScrollPolicy; import mx.events.MenuEvent; import mx.managers.PopUpManager; import mx.utils.ObjectUtil; import flexlib.controls.ScrollableArrowMenu; import com.threerings.util.CommandEvent; import com.threerings.flex.PopUpUtil; import com.threerings.flex.menuClasses.CommandMenuItemRenderer; import com.threerings.flex.menuClasses.CommandListData; use namespace mx_internal; /** * A pretty standard menu that can submit CommandEvents if menu items have "command" and possibly * "arg" properties. Commands are submitted to controllers for processing. Alternatively, you may * specify "callback" properties that specify a function closure to call, with the "arg" property * containing either a single arg or an array of args. * * Another property now supported is "iconObject", which is an already-instantiated * IFlexDisplayObject to use as the icon. This will only be applied if the "icon" property * (which specifies a Class) is not used. * * Example dataProvider array: * [ { label: "Go home", icon: homeIconClass, * command: Controller.GO_HOME, arg: homeId }, * { type: "separator"}, { label: "Crazytown", callback: setCrazy, arg: [ true, false ] }, * { label: "Other places", children: subMenuArray } * ]; * * See "Defining menu structure and data" in the Flex manual for the full list. */ public class CommandMenu extends Menu { /** * Factory method to create a command menu. * * @param items an array of menu items. * @param dispatcher an override event dispatcher to use for command events, rather than * our parent. */ public static function createMenu ( items :Array, dispatcher :IEventDispatcher = null) :CommandMenu { var menu :CommandMenu = new CommandMenu(); menu.owner = DisplayObjectContainer(Application.application); menu.tabEnabled = false; menu.showRoot = true; menu.setDispatcher(dispatcher); Menu.popUpMenu(menu, null, items); // does not actually pop up, but needed. return menu; } public function CommandMenu () { super(); itemRenderer = new ClassFactory(CommandMenuItemRenderer); verticalScrollPolicy = ScrollPolicy.OFF; addEventListener(MenuEvent.ITEM_CLICK, itemClicked); } /** * Configures the event dispatcher to be used when dispatching this menu's command events. * Normally they will be dispatched on our parent (usually the SystemManager or something). */ public function setDispatcher (dispatcher :IEventDispatcher) :void { _dispatcher = dispatcher; } /** * Sets a Rectangle (in stage coords) that the menu will attempt to keep submenus positioned * within. If a submenu is too large to fit, it will position it in the lower right corner * of this Rectangle (or top if popping upwards, or left if popping leftwards). This * value defaults to the stage bounds. */ public function setBounds (fitting :Rectangle) :void { _fitting = fitting; } /** * Actually pop up the menu. This can be used instead of show(). */ public function popUp ( trigger :DisplayObject, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; var r :Rectangle = trigger.getBounds(trigger.stage); show(_lefting ? r.left : r.right, _upping ? r.top : r.bottom); } /** * Shows the menu at the specified mouse coordinates. */ public function popUpAt ( mx :int, my :int, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(mx, my); } /** * Shows the menu at the current mouse location. */ public function popUpAtMouse (popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(); // our show, with no args, pops at the mouse } /** * Just like our superclass's show(), except that when invoked with no args, causes the menu to * show at the current mouse location instead of the top-left corner of the application. * Also, we ensure that the resulting menu is in-bounds. */ override public function show (xShow :Object = null, yShow :Object = null) :void { if (xShow == null) { xShow = DisplayObject(Application.application).mouseX; } if (yShow == null) { yShow = DisplayObject(Application.application).mouseY; } super.show(xShow, yShow); // reposition now that we know our size if (_lefting) { y = x - getExplicitOrMeasuredWidth(); } if (_upping) { y = y - getExplicitOrMeasuredHeight(); } PopUpUtil.fitInRect(this, _fitting || screen); } /** * Callback for MenuEvent.ITEM_CLICK. */ protected function itemClicked (event :MenuEvent) :void { var arg :Object = getItemProp(event.item, "arg"); var cmdOrFn :Object = getItemProp(event.item, "command"); if (cmdOrFn == null) { cmdOrFn = getItemProp(event.item, "callback"); } if (cmdOrFn != null) { event.stopImmediatePropagation(); CommandEvent.dispatch(_dispatcher == null ? mx_internal::parentDisplayObject : _dispatcher, cmdOrFn, arg); } // else: no warning. There may be non-command menu items mixed in. } // from ScrollableArrowMenu.. override mx_internal function openSubMenu (row :IListItemRenderer) :void { supposedToLoseFocus = true; var r :Menu = getRootMenu(); var menu :CommandMenu; // check to see if the menu exists, if not create it if (!IMenuItemRenderer(row).menu) { // the only differences between this method and the original method in mx.controls.Menu // are these few lines. menu = new CommandMenu(); menu.maxHeight = this.maxHeight; menu.verticalScrollPolicy = this.verticalScrollPolicy; menu.variableRowHeight = this.variableRowHeight; menu.parentMenu = this; menu.owner = this; menu.showRoot = showRoot; menu.dataDescriptor = r.dataDescriptor; menu.styleName = r; menu.labelField = r.labelField; menu.labelFunction = r.labelFunction; menu.iconField = r.iconField; menu.iconFunction = r.iconFunction; menu.itemRenderer = r.itemRenderer; menu.rowHeight = r.rowHeight; menu.scaleY = r.scaleY; menu.scaleX = r.scaleX; // if there's data and it has children then add the items if (row.data && _dataDescriptor.isBranch(row.data) && _dataDescriptor.hasChildren(row.data)) { menu.dataProvider = _dataDescriptor.getChildren(row.data); } menu.sourceMenuBar = sourceMenuBar; menu.sourceMenuBarItem = sourceMenuBarItem; IMenuItemRenderer(row).menu = menu; PopUpManager.addPopUp(menu, r, false); } super.openSubMenu(row); // if we're lefting, upping or fitting make sure our submenu does so as well var submenu :Menu = IMenuItemRenderer(row).menu; if (_lefting) { submenu.x -= submenu.getExplicitOrMeasuredWidth(); } if (_upping) { var displayObj :DisplayObject = DisplayObject(row); var rowLoc :Point = displayObj.localToGlobal(new Point(row.x, row.y)); submenu.y = rowLoc.y - submenu.getExplicitOrMeasuredHeight() + displayObj.height; } PopUpUtil.fitInRect(submenu, _fitting || screen); } // from List override protected function makeListData (data :Object, uid :String, rowNum :int) :BaseListData { // Oh, FFS. // We need to set up these "maxMeasuredIconWidth" fields on the MenuListData, but our // superclass has made those variables private. // We can get the values out of another MenuListData, so we just always call super() // to create one of those, and if we need to make a CommandListData, we construct one // from the fields in the MenuListData. var menuListData :MenuListData = super.makeListData(data, uid, rowNum) as MenuListData; var iconObject :IFlexDisplayObject = getItemProp(data, "iconObject") as IFlexDisplayObject; if (iconObject != null) { var cmdListData :CommandListData = new CommandListData(menuListData.label, menuListData.icon, iconObject, labelField, uid, this, rowNum); cmdListData.maxMeasuredIconWidth = menuListData.maxMeasuredIconWidth; cmdListData.maxMeasuredTypeIconWidth = menuListData.maxMeasuredTypeIconWidth; cmdListData.maxMeasuredBranchIconWidth = menuListData.maxMeasuredBranchIconWidth; cmdListData.useTwoColumns = menuListData.useTwoColumns; return cmdListData; } return menuListData; } /** * Get the specified property for the specified item, if any. Somewhat similar to bits in the * DefaultDataDescriptor. */ protected function getItemProp (item :Object, prop :String) :Object { try { if (item is XML) { return String((item as XML).attribute(prop)); } else if (prop in item) { return item[prop]; } } catch (e :Error) { // alas; fall through } return null; } protected var _dispatcher :IEventDispatcher; protected var _lefting :Boolean = false; protected var _upping :Boolean = false; protected var _fitting :Rectangle = null; } }
// // $Id$ // // Nenya library - tools for developing networked games // Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved // http://www.threerings.net/code/nenya/ // // 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.flex { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.events.IEventDispatcher; import flash.geom.Point; import flash.geom.Rectangle; import mx.controls.Menu; import mx.controls.listClasses.BaseListData; import mx.controls.listClasses.IListItemRenderer; import mx.controls.menuClasses.IMenuItemRenderer; import mx.controls.menuClasses.MenuListData; import mx.core.mx_internal; import mx.core.Application; import mx.core.ClassFactory; import mx.core.IFlexDisplayObject; import mx.core.ScrollPolicy; import mx.events.MenuEvent; import mx.managers.PopUpManager; import mx.utils.ObjectUtil; import flexlib.controls.ScrollableArrowMenu; import com.threerings.util.CommandEvent; import com.threerings.flex.PopUpUtil; import com.threerings.flex.menuClasses.CommandMenuItemRenderer; import com.threerings.flex.menuClasses.CommandListData; use namespace mx_internal; /** * A pretty standard menu that can submit CommandEvents if menu items have "command" and possibly * "arg" properties. Commands are submitted to controllers for processing. Alternatively, you may * specify "callback" properties that specify a function closure to call, with the "arg" property * containing either a single arg or an array of args. * * Another property now supported is "iconObject", which is an already-instantiated * IFlexDisplayObject to use as the icon. This will only be applied if the "icon" property * (which specifies a Class) is not used. * * Example dataProvider array: * [ { label: "Go home", icon: homeIconClass, * command: Controller.GO_HOME, arg: homeId }, * { type: "separator"}, { label: "Crazytown", callback: setCrazy, arg: [ true, false ] }, * { label: "Other places", children: subMenuArray } * ]; * * See "Defining menu structure and data" in the Flex manual for the full list. */ public class CommandMenu extends Menu { /** * Factory method to create a command menu. * * @param items an array of menu items. * @param dispatcher an override event dispatcher to use for command events, rather than * our parent. */ public static function createMenu ( items :Array, dispatcher :IEventDispatcher = null) :CommandMenu { var menu :CommandMenu = new CommandMenu(); menu.owner = DisplayObjectContainer(Application.application); menu.tabEnabled = false; menu.showRoot = true; menu.setDispatcher(dispatcher); Menu.popUpMenu(menu, null, items); // does not actually pop up, but needed. return menu; } /** * The mx.controls.Menu class overrides setting and getting the verticalScrollPolicy * basically setting the verticalScrollPolicy did nothing, and getting it always returned * ScrollPolicy.OFF. So that's not going to work if we want the menu to scroll. Here we * reinstate the verticalScrollPolicy setter, and keep a local copy of the value in a * protected variable _verticalScrollPolicy. * * This setter is basically a copy of what ScrollControlBase and ListBase do. */ override public function set verticalScrollPolicy (value :String) :void { var newPolicy :String = value.toLowerCase(); itemsSizeChanged = true; if (_verticalScrollPolicy != newPolicy) { _verticalScrollPolicy = newPolicy; dispatchEvent(new Event("verticalScrollPolicyChanged")); } invalidateDisplayList(); } override public function get verticalScrollPolicy () :String { return _verticalScrollPolicy; } public function CommandMenu () { super(); itemRenderer = new ClassFactory(CommandMenuItemRenderer); verticalScrollPolicy = ScrollPolicy.OFF; addEventListener(MenuEvent.ITEM_CLICK, itemClicked); } /** * Configures the event dispatcher to be used when dispatching this menu's command events. * Normally they will be dispatched on our parent (usually the SystemManager or something). */ public function setDispatcher (dispatcher :IEventDispatcher) :void { _dispatcher = dispatcher; } /** * Sets a Rectangle (in stage coords) that the menu will attempt to keep submenus positioned * within. If a submenu is too large to fit, it will position it in the lower right corner * of this Rectangle (or top if popping upwards, or left if popping leftwards). This * value defaults to the stage bounds. */ public function setBounds (fitting :Rectangle) :void { _fitting = fitting; } /** * Actually pop up the menu. This can be used instead of show(). */ public function popUp ( trigger :DisplayObject, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; var r :Rectangle = trigger.getBounds(trigger.stage); show(_lefting ? r.left : r.right, _upping ? r.top : r.bottom); } /** * Shows the menu at the specified mouse coordinates. */ public function popUpAt ( mx :int, my :int, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(mx, my); } /** * Shows the menu at the current mouse location. */ public function popUpAtMouse (popUpwards :Boolean = false, popLeftwards :Boolean = false) :void { _upping = popUpwards; _lefting = popLeftwards; show(); // our show, with no args, pops at the mouse } /** * Just like our superclass's show(), except that when invoked with no args, causes the menu to * show at the current mouse location instead of the top-left corner of the application. * Also, we ensure that the resulting menu is in-bounds. */ override public function show (xShow :Object = null, yShow :Object = null) :void { if (xShow == null) { xShow = DisplayObject(Application.application).mouseX; } if (yShow == null) { yShow = DisplayObject(Application.application).mouseY; } super.show(xShow, yShow); // reposition now that we know our size if (_lefting) { y = x - getExplicitOrMeasuredWidth(); } if (_upping) { y = y - getExplicitOrMeasuredHeight(); } PopUpUtil.fitInRect(this, _fitting || screen); } /** * The Menu class overrode configureScrollBars() and made the function do nothing. That means * the scrollbars don't know how to draw themselves, so here we reinstate configureScrollBars. * This is basically a copy of the same method from the mx.controls.List class. */ override protected function configureScrollBars () :void { var rowCount :int = listItems.length; if (rowCount == 0) { return; } // if there is more than one row and it is a partial row we don't count it if (rowCount > 1 && rowInfo[rowCount - 1].y + rowInfo[rowCount - 1].height > listContent.height) { rowCount--; } // offset, when added to rowCount, is hte index of the dataProvider item for that row. // IOW, row 10 in listItems is showing dataProvider item 10 + verticalScrollPosition - // lockedRowCount - 1 var offset :int = verticalScrollPosition - lockedRowCount - 1; // don't count filler rows at the bottom either. var fillerRows :int = 0; while (rowCount > 0 && listItems[rowCount - 1].length == 0) { if (collection && rowCount + offset >= collection.length) { rowCount--; fillerRows++; } else { break; } } var colCount :int = listItems[0].length; var oldHorizontalScrollBar :Object = horizontalScrollBar; var oldVerticalScrollBar :Object = verticalScrollBar; var roundedWidth :int = Math.round(unscaledWidth); var length :int = collection ? collection.length - lockedRowCount : 0; var numRows :int = rowCount - lockedRowCount; setScrollBarProperties(Math.round(listContent.width), roundedWidth, length, numRows); maxVerticalScrollPosition = Math.max(length - numRows, 0); } /** * Callback for MenuEvent.ITEM_CLICK. */ protected function itemClicked (event :MenuEvent) :void { var arg :Object = getItemProp(event.item, "arg"); var cmdOrFn :Object = getItemProp(event.item, "command"); if (cmdOrFn == null) { cmdOrFn = getItemProp(event.item, "callback"); } if (cmdOrFn != null) { event.stopImmediatePropagation(); CommandEvent.dispatch(_dispatcher == null ? mx_internal::parentDisplayObject : _dispatcher, cmdOrFn, arg); } // else: no warning. There may be non-command menu items mixed in. } // from ScrollableArrowMenu.. override mx_internal function openSubMenu (row :IListItemRenderer) :void { supposedToLoseFocus = true; var r :Menu = getRootMenu(); var menu :CommandMenu; // check to see if the menu exists, if not create it if (!IMenuItemRenderer(row).menu) { // the only differences between this method and the original method in mx.controls.Menu // are these few lines. menu = new CommandMenu(); menu.maxHeight = this.maxHeight; menu.verticalScrollPolicy = this.verticalScrollPolicy; menu.variableRowHeight = this.variableRowHeight; menu.parentMenu = this; menu.owner = this; menu.showRoot = showRoot; menu.dataDescriptor = r.dataDescriptor; menu.styleName = r; menu.labelField = r.labelField; menu.labelFunction = r.labelFunction; menu.iconField = r.iconField; menu.iconFunction = r.iconFunction; menu.itemRenderer = r.itemRenderer; menu.rowHeight = r.rowHeight; menu.scaleY = r.scaleY; menu.scaleX = r.scaleX; // if there's data and it has children then add the items if (row.data && _dataDescriptor.isBranch(row.data) && _dataDescriptor.hasChildren(row.data)) { menu.dataProvider = _dataDescriptor.getChildren(row.data); } menu.sourceMenuBar = sourceMenuBar; menu.sourceMenuBarItem = sourceMenuBarItem; IMenuItemRenderer(row).menu = menu; PopUpManager.addPopUp(menu, r, false); } super.openSubMenu(row); // if we're lefting, upping or fitting make sure our submenu does so as well var submenu :Menu = IMenuItemRenderer(row).menu; if (_lefting) { submenu.x -= submenu.getExplicitOrMeasuredWidth(); } if (_upping) { var displayObj :DisplayObject = DisplayObject(row); var rowLoc :Point = displayObj.localToGlobal(new Point(row.x, row.y)); submenu.y = rowLoc.y - submenu.getExplicitOrMeasuredHeight() + displayObj.height; } PopUpUtil.fitInRect(submenu, _fitting || screen); } override protected function measure () :void { super.measure(); if (measuredHeight > this.maxHeight) { measuredHeight = this.maxHeight; } if (verticalScrollPolicy == ScrollPolicy.ON || verticalScrollPolicy == ScrollPolicy.AUTO) { if (verticalScrollBar) { measuredMinWidth = measuredWidth = measuredWidth + verticalScrollBar.minWidth; } } commitProperties(); } // from List override protected function makeListData (data :Object, uid :String, rowNum :int) :BaseListData { // Oh, FFS. // We need to set up these "maxMeasuredIconWidth" fields on the MenuListData, but our // superclass has made those variables private. // We can get the values out of another MenuListData, so we just always call super() // to create one of those, and if we need to make a CommandListData, we construct one // from the fields in the MenuListData. var menuListData :MenuListData = super.makeListData(data, uid, rowNum) as MenuListData; var iconObject :IFlexDisplayObject = getItemProp(data, "iconObject") as IFlexDisplayObject; if (iconObject != null) { var cmdListData :CommandListData = new CommandListData(menuListData.label, menuListData.icon, iconObject, labelField, uid, this, rowNum); cmdListData.maxMeasuredIconWidth = menuListData.maxMeasuredIconWidth; cmdListData.maxMeasuredTypeIconWidth = menuListData.maxMeasuredTypeIconWidth; cmdListData.maxMeasuredBranchIconWidth = menuListData.maxMeasuredBranchIconWidth; cmdListData.useTwoColumns = menuListData.useTwoColumns; return cmdListData; } return menuListData; } /** * Get the specified property for the specified item, if any. Somewhat similar to bits in the * DefaultDataDescriptor. */ protected function getItemProp (item :Object, prop :String) :Object { try { if (item is XML) { return String((item as XML).attribute(prop)); } else if (prop in item) { return item[prop]; } } catch (e :Error) { // alas; fall through } return null; } protected var _dispatcher :IEventDispatcher; protected var _lefting :Boolean = false; protected var _upping :Boolean = false; protected var _fitting :Rectangle = null; protected var _verticalScrollPolicy :String; } }
Bring back the scrollable menu. However, we leave the default as not scrolling, and only do scrolling of any kind of the verticalScrollPolicy is set to ScrollPolicy.AUTO or ScrollPolicy.ON, and the maxHeight has been set.
Bring back the scrollable menu. However, we leave the default as not scrolling, and only do scrolling of any kind of the verticalScrollPolicy is set to ScrollPolicy.AUTO or ScrollPolicy.ON, and the maxHeight has been set. git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@525 ed5b42cb-e716-0410-a449-f6a68f950b19
ActionScript
lgpl-2.1
threerings/nenya,threerings/nenya
58cc712d4d8f648d91e9d177fd64bf7cebe60386
flexEditor/src/org/arisgames/editor/components/ItemEditorMediaPickerView.as
flexEditor/src/org/arisgames/editor/components/ItemEditorMediaPickerView.as
package org.arisgames.editor.components { import com.ninem.controls.TreeBrowser; import com.ninem.events.TreeBrowserEvent; import flash.events.MouseEvent; import mx.containers.Panel; import mx.controls.Alert; import mx.controls.Button; import mx.controls.DataGrid; import mx.core.ClassFactory; import mx.events.DynamicEvent; import mx.events.FlexEvent; import mx.managers.PopUpManager; import mx.rpc.Responder; import org.arisgames.editor.data.arisserver.Media; import org.arisgames.editor.data.businessobjects.ObjectPaletteItemBO; import org.arisgames.editor.models.GameModel; import org.arisgames.editor.services.AppServices; import org.arisgames.editor.util.AppConstants; import org.arisgames.editor.util.AppDynamicEventManager; import org.arisgames.editor.util.AppUtils; public class ItemEditorMediaPickerView extends Panel { // Data Object public var delegate:Object; private var objectPaletteItem:ObjectPaletteItemBO; private var isIconPicker:Boolean = false; private var isNPC:Boolean = false; private var uploadFormVisable:Boolean = false; // Media Data [Bindable] public var xmlData:XML; // GUI [Bindable] public var treeBrowser:TreeBrowser; [Bindable] public var closeButton:Button; [Bindable] public var selectButton:Button; // Tree Icons [Bindable] [Embed(source="assets/img/separator.png")] public var separatorIcon:Class; //If these names are changed, make sure it is also changed in AppConstants (MEDIATREEICON_*) [Bindable] [Embed(source="assets/img/upload.png")] public var uploadIcon:Class; //If these names are changed, make sure it is also changed in AppConstants (MEDIATREEICON_*) private var mediaUploader:ItemEditorMediaPickerUploadFormMX; /** * Constructor */ public function ItemEditorMediaPickerView() { super(); this.addEventListener(FlexEvent.CREATION_COMPLETE, handleInit); } private function handleInit(event:FlexEvent):void { trace("in ItemEditorMediaPickerView's handleInit"); var cf:ClassFactory = new ClassFactory(ItemEditorMediaPickerCustomEditorMX); cf.properties = {objectPaletteItem: this.objectPaletteItem}; treeBrowser.detailRenderer = cf; treeBrowser.addEventListener(TreeBrowserEvent.NODE_SELECTED, onNodeSelected); closeButton.addEventListener(MouseEvent.CLICK, handleCloseButton); selectButton.addEventListener(MouseEvent.CLICK, handleSelectButton); // Load Game's Media Into XML AppServices.getInstance().getMediaForGame(GameModel.getInstance().game.gameId, new Responder(handleLoadingOfMediaIntoXML, handleFault)); } private function printXMLData():void { trace("XML Data = '" + xmlData.toXMLString() + "'"); } public function setObjectPaletteItem(opi:ObjectPaletteItemBO):void { trace("setting objectPaletteItem with name = '" + opi.name + "' in ItemEditorPlaqueView"); objectPaletteItem = opi; } public function isInIconPickerMode():Boolean { return isIconPicker; } public function setIsIconPicker(isIconPickerMode:Boolean):void { trace("setting isIconPicker mode to: " + isIconPickerMode); this.isIconPicker = isIconPickerMode; this.updateTitleBasedOnMode(); } private function updateTitleBasedOnMode():void { if (isIconPicker) { title = "Icon Picker"; } else { title = "Media Picker"; } } private function handleCloseButton(evt:MouseEvent):void { trace("ItemEditorMediaPickerView: handleCloseButton()"); PopUpManager.removePopUp(this); } private function handleSelectButton(evt:MouseEvent):void { trace("Select Button clicked..."); var m:Media = new Media(); m.mediaId = treeBrowser.selectedItem.@mediaId; m.name = treeBrowser.selectedItem.@name; m.type = treeBrowser.selectedItem.@type; m.urlPath = treeBrowser.selectedItem.@urlPath; m.fileName = treeBrowser.selectedItem.@fileName; m.isDefault = treeBrowser.selectedItem.@isDefault; if (delegate.hasOwnProperty("didSelectMediaItem")){ delegate.didSelectMediaItem(this, m); } PopUpManager.removePopUp(this); } private function handleLoadingOfMediaIntoXML(obj:Object):void { if(this.objectPaletteItem.objectType == AppConstants.CONTENTTYPE_CHARACTER_DATABASE){ this.isNPC = true; trace("This is an NPC, so disallow Audio/Visual media"); } trace("In handleLoadingOfMediaIntoXML() Result called with obj = " + obj + "; Result = " + obj.result); if (obj.result.returnCode != 0) { trace("Bad loading of media attempt... let's see what happened. Error = '" + obj.result.returnCodeDescription + "'"); var msg:String = obj.result.returnCodeDescription; Alert.show("Error Was: " + msg, "Error While Loading Media"); return; } //Init the XML Data xmlData = new XML('<nodes label="' + AppConstants.MEDIATYPE + '"/>'); if (!this.isIconPicker && !this.isNPC) { xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_IMAGE + '"/>'); xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_AUDIO + '"/>'); xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_VIDEO + '"/>'); } this.printXMLData(); var media:Array = obj.result.data as Array; trace("Number of Media Objects returned from server = '" + media.length + "'"); //Puts media items in xml readable format var numImageDefaults:Number = 0; var numAudioDefaults:Number = 0; var numVideoDefaults:Number = 0; var numIconDefaults:Number = 0; for (var k:Number = 0; k <= 1; k++) //Iterates over list twice; once for uploaded items, again for default { for (var j:Number = 0; j < media.length; j++) { var o:Object = media[j]; if((k==0 && !o.is_default) || (k==1 && o.is_default)){ var m:Media = new Media(); m.mediaId = o.media_id; m.name = o.name; m.type = o.type; m.urlPath = o.url_path; m.fileName = o.file_name; m.isDefault = o.is_default; //for both default files and uploaded files var node:String = "<node label='" + AppUtils.filterStringToXMLEscapeCharacters(m.name) + "' mediaId='" + m.mediaId + "' type='" + m.type + "' urlPath='" + m.urlPath + "' fileName='" + m.fileName + "' isDefault='" + m.isDefault + "'/>"; switch (m.type) { case AppConstants.MEDIATYPE_IMAGE: if(!this.isNPC){ if (!this.isIconPicker) { //Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from if(k > numImageDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>'); xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild(node); numImageDefaults+=k; } } else{ if (!this.isIconPicker) { if(k > numIconDefaults) xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>'); xmlData.appendChild(node); numIconDefaults+=k; } } break; case AppConstants.MEDIATYPE_AUDIO: if (!this.isIconPicker && !this.isNPC) { //Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from if(k > numAudioDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>'); xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild(node); numAudioDefaults+=k; } break; case AppConstants.MEDIATYPE_VIDEO: if (!this.isIconPicker && !this.isNPC) { //Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from if(k > numVideoDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>'); xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild(node); numVideoDefaults+=k; } break; case AppConstants.MEDIATYPE_ICON: if (this.isIconPicker) { trace("hello?:"+node); if(k > numIconDefaults) xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>'); xmlData.appendChild(node); numIconDefaults+=k; } break; default: trace("Default statement reached in load media. This SHOULD NOT HAPPEN. The offending mediaId = '" + m.mediaId + "' and type = '" + m.type + "'"); break; } } } //Add "Upload new" in between uploaded and default pictures if(k==0 && (!this.isIconPicker && !this.isNPC)){ xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>'); xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>'); xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>'); } else if(k == 0){ xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>'); } } trace("ItemEditorMediaPickerView: handleLoadingOfMediaIntoXML: Just finished loading Media Objects into XML. Here's what the new XML looks like:"); this.printXMLData(); trace("Finished with handleLoadingOfMediaIntoXML()."); } public function handleFault(obj:Object):void { trace("Fault called: " + obj.message); Alert.show("Error occurred: " + obj.message, "Problems Loading Media"); } private function onNodeSelected(event:TreeBrowserEvent):void { if (!event.isBranch) { if (event.item.@label == AppConstants.MEDIATYPE_UPLOADNEW) { if (uploadFormVisable == false) { trace("ItemEditorMediaPickerView: onNodeSelected label == MEDIATYPE_UPLOADNEW, display form"); selectButton.enabled = false; uploadFormVisable = true; this.displayMediaUploader(); PopUpManager.removePopUp(this); } else trace("ItemEditorMediaPickerView: ignored second TreeBrowserEvent == MEDIATYPE_UPLOADNEW"); } else if(event.item.@label == AppConstants.MEDIATYPE_SEPARATOR){ //Do Nothing trace("Separator Selected"); selectButton.enabled = false; } else { trace("ItemEditorMediaPickerView: onNodeSelected is a media item"); selectButton.enabled = true; } } else { selectButton.enabled = false; } } private function displayMediaUploader():void { trace("itemEditorMediaPickerPickerView: displayMediaUploader"); mediaUploader = new ItemEditorMediaPickerUploadFormMX(); mediaUploader.isIconPicker = this.isIconPicker; mediaUploader.delegate = this; PopUpManager.addPopUp(mediaUploader, AppUtils.getInstance().getMainView(), true); PopUpManager.centerPopUp(mediaUploader); } public function didUploadMedia(uploader:ItemEditorMediaPickerUploadFormMX, m:Media):void{ trace("ItemEditorMediaPicker: didUploadMedia"); uploadFormVisable = false; if (delegate.hasOwnProperty("didSelectMediaItem")){ delegate.didSelectMediaItem(this, m); } PopUpManager.removePopUp(uploader); } } }
package org.arisgames.editor.components { import com.ninem.controls.TreeBrowser; import com.ninem.events.TreeBrowserEvent; import flash.events.MouseEvent; import mx.containers.Panel; import mx.controls.Alert; import mx.controls.Button; import mx.controls.DataGrid; import mx.core.ClassFactory; import mx.events.DynamicEvent; import mx.events.FlexEvent; import mx.managers.PopUpManager; import mx.rpc.Responder; import org.arisgames.editor.data.arisserver.Media; import org.arisgames.editor.data.businessobjects.ObjectPaletteItemBO; import org.arisgames.editor.models.GameModel; import org.arisgames.editor.services.AppServices; import org.arisgames.editor.util.AppConstants; import org.arisgames.editor.util.AppDynamicEventManager; import org.arisgames.editor.util.AppUtils; public class ItemEditorMediaPickerView extends Panel { // Data Object public var delegate:Object; private var objectPaletteItem:ObjectPaletteItemBO; private var isIconPicker:Boolean = false; private var isNPC:Boolean = false; private var uploadFormVisable:Boolean = false; // Media Data [Bindable] public var xmlData:XML; // GUI [Bindable] public var treeBrowser:TreeBrowser; [Bindable] public var closeButton:Button; [Bindable] public var selectButton:Button; // Tree Icons [Bindable] [Embed(source="assets/img/separator.png")] public var separatorIcon:Class; //If these names are changed, make sure it is also changed in AppConstants (MEDIATREEICON_*) [Bindable] [Embed(source="assets/img/upload.png")] public var uploadIcon:Class; //If these names are changed, make sure it is also changed in AppConstants (MEDIATREEICON_*) private var mediaUploader:ItemEditorMediaPickerUploadFormMX; /** * Constructor */ public function ItemEditorMediaPickerView() { super(); this.addEventListener(FlexEvent.CREATION_COMPLETE, handleInit); } private function handleInit(event:FlexEvent):void { trace("in ItemEditorMediaPickerView's handleInit"); var cf:ClassFactory = new ClassFactory(ItemEditorMediaPickerCustomEditorMX); cf.properties = {objectPaletteItem: this.objectPaletteItem}; treeBrowser.detailRenderer = cf; treeBrowser.addEventListener(TreeBrowserEvent.NODE_SELECTED, onNodeSelected); closeButton.addEventListener(MouseEvent.CLICK, handleCloseButton); selectButton.addEventListener(MouseEvent.CLICK, handleSelectButton); // Load Game's Media Into XML AppServices.getInstance().getMediaForGame(GameModel.getInstance().game.gameId, new Responder(handleLoadingOfMediaIntoXML, handleFault)); } private function printXMLData():void { trace("XML Data = '" + xmlData.toXMLString() + "'"); } public function setObjectPaletteItem(opi:ObjectPaletteItemBO):void { trace("setting objectPaletteItem with name = '" + opi.name + "' in ItemEditorPlaqueView"); objectPaletteItem = opi; } public function isInIconPickerMode():Boolean { return isIconPicker; } public function setIsIconPicker(isIconPickerMode:Boolean):void { trace("setting isIconPicker mode to: " + isIconPickerMode); this.isIconPicker = isIconPickerMode; this.updateTitleBasedOnMode(); } private function updateTitleBasedOnMode():void { if (isIconPicker) { title = "Icon Picker"; } else { title = "Media Picker"; } } private function handleCloseButton(evt:MouseEvent):void { trace("ItemEditorMediaPickerView: handleCloseButton()"); PopUpManager.removePopUp(this); } private function handleSelectButton(evt:MouseEvent):void { trace("Select Button clicked..."); var m:Media = new Media(); m.mediaId = treeBrowser.selectedItem.@mediaId; m.name = treeBrowser.selectedItem.@name; m.type = treeBrowser.selectedItem.@type; m.urlPath = treeBrowser.selectedItem.@urlPath; m.fileName = treeBrowser.selectedItem.@fileName; m.isDefault = treeBrowser.selectedItem.@isDefault; if (delegate.hasOwnProperty("didSelectMediaItem")){ delegate.didSelectMediaItem(this, m); } PopUpManager.removePopUp(this); } private function handleLoadingOfMediaIntoXML(obj:Object):void { if(this.objectPaletteItem.objectType == AppConstants.CONTENTTYPE_CHARACTER_DATABASE){ this.isNPC = true; trace("This is an NPC, so disallow Audio/Visual media"); } trace("In handleLoadingOfMediaIntoXML() Result called with obj = " + obj + "; Result = " + obj.result); if (obj.result.returnCode != 0) { trace("Bad loading of media attempt... let's see what happened. Error = '" + obj.result.returnCodeDescription + "'"); var msg:String = obj.result.returnCodeDescription; Alert.show("Error Was: " + msg, "Error While Loading Media"); return; } //Init the XML Data xmlData = new XML('<nodes label="' + AppConstants.MEDIATYPE + '"/>'); if (!this.isIconPicker && !this.isNPC) { xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_IMAGE + '"/>'); xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_AUDIO + '"/>'); xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_VIDEO + '"/>'); } this.printXMLData(); var media:Array = obj.result.data as Array; trace("Number of Media Objects returned from server = '" + media.length + "'"); //Puts media items in xml readable format var numImageDefaults:Number = 0; var numAudioDefaults:Number = 0; var numVideoDefaults:Number = 0; var numIconDefaults:Number = 0; for (var k:Number = 0; k <= 1; k++) //Iterates over list twice; once for uploaded items, again for default { //Add "Upload new" in between uploaded and default pictures if(k==0 && (!this.isIconPicker && !this.isNPC)){ xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>'); xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>'); xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>'); } else if(k == 0){ xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>'); } for (var j:Number = 0; j < media.length; j++) { var o:Object = media[j]; if((k==0 && !o.is_default) || (k==1 && o.is_default)){ var m:Media = new Media(); m.mediaId = o.media_id; m.name = o.name; m.type = o.type; m.urlPath = o.url_path; m.fileName = o.file_name; m.isDefault = o.is_default; //for both default files and uploaded files var node:String = "<node label='" + AppUtils.filterStringToXMLEscapeCharacters(m.name) + "' mediaId='" + m.mediaId + "' type='" + m.type + "' urlPath='" + m.urlPath + "' fileName='" + m.fileName + "' isDefault='" + m.isDefault + "'/>"; switch (m.type) { case AppConstants.MEDIATYPE_IMAGE: if(!this.isNPC){ if (!this.isIconPicker) { //Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from if(k > numImageDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>'); xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild(node); numImageDefaults+=k; } } else{ if (!this.isIconPicker) { if(k > numIconDefaults) xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>'); xmlData.appendChild(node); numIconDefaults+=k; } } break; case AppConstants.MEDIATYPE_AUDIO: if (!this.isIconPicker && !this.isNPC) { //Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from if(k > numAudioDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>'); xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild(node); numAudioDefaults+=k; } break; case AppConstants.MEDIATYPE_VIDEO: if (!this.isIconPicker && !this.isNPC) { //Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from if(k > numVideoDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>'); xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild(node); numVideoDefaults+=k; } break; case AppConstants.MEDIATYPE_ICON: if (this.isIconPicker) { trace("hello?:"+node); if(k > numIconDefaults) xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>'); xmlData.appendChild(node); numIconDefaults+=k; } break; default: trace("Default statement reached in load media. This SHOULD NOT HAPPEN. The offending mediaId = '" + m.mediaId + "' and type = '" + m.type + "'"); break; } } } } trace("ItemEditorMediaPickerView: handleLoadingOfMediaIntoXML: Just finished loading Media Objects into XML. Here's what the new XML looks like:"); this.printXMLData(); trace("Finished with handleLoadingOfMediaIntoXML()."); } public function handleFault(obj:Object):void { trace("Fault called: " + obj.message); Alert.show("Error occurred: " + obj.message, "Problems Loading Media"); } private function onNodeSelected(event:TreeBrowserEvent):void { if (!event.isBranch) { if (event.item.@label == AppConstants.MEDIATYPE_UPLOADNEW) { if (uploadFormVisable == false) { trace("ItemEditorMediaPickerView: onNodeSelected label == MEDIATYPE_UPLOADNEW, display form"); selectButton.enabled = false; uploadFormVisable = true; this.displayMediaUploader(); PopUpManager.removePopUp(this); } else trace("ItemEditorMediaPickerView: ignored second TreeBrowserEvent == MEDIATYPE_UPLOADNEW"); } else if(event.item.@label == AppConstants.MEDIATYPE_SEPARATOR){ //Do Nothing trace("Separator Selected"); selectButton.enabled = false; } else { trace("ItemEditorMediaPickerView: onNodeSelected is a media item"); selectButton.enabled = true; } } else { selectButton.enabled = false; } } private function displayMediaUploader():void { trace("itemEditorMediaPickerPickerView: displayMediaUploader"); mediaUploader = new ItemEditorMediaPickerUploadFormMX(); mediaUploader.isIconPicker = this.isIconPicker; mediaUploader.delegate = this; PopUpManager.addPopUp(mediaUploader, AppUtils.getInstance().getMainView(), true); PopUpManager.centerPopUp(mediaUploader); } public function didUploadMedia(uploader:ItemEditorMediaPickerUploadFormMX, m:Media):void{ trace("ItemEditorMediaPicker: didUploadMedia"); uploadFormVisable = false; if (delegate.hasOwnProperty("didSelectMediaItem")){ delegate.didSelectMediaItem(this, m); } PopUpManager.removePopUp(uploader); } } }
Put Upload New button at top of media picker list
Put Upload New button at top of media picker list
ActionScript
mit
fielddaylab/sifter-ios,fielddaylab/sifter-ios
91eded78ae40c750e20c021f4f5a4b7f595d54fe
as3/com/netease/protobuf/VarintWriter.as
as3/com/netease/protobuf/VarintWriter.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 { import flash.utils.* public final class VarintWriter extends ByteArray { private var bitsLeft:uint = 0 public function end():void { if (length == 1) { this[0] &= 0x7F } else { for (var i:uint = length; i > 0; i--) { const byte:uint = this[i - 1] if (byte != 0x80) { this[i - 1] = 0x7F & byte length = i return } } } } public function write(number:uint, bits:uint):void { if (bits <= bitsLeft) { this[length - 1] |= number << (7 - bitsLeft) bitsLeft -= bits } else { if (bitsLeft != 0) { this[length - 1] |= number << (7 - bitsLeft) bits -= bitsLeft number >>>= bitsLeft } while (bits >= 7) { writeByte(0x80 | number) number >>>= 7 bits -= 7 } writeByte(0x80 | number) bitsLeft = 7 - bits } } } }
// 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 { import flash.utils.*; public final class VarintWriter extends ByteArray { private var bitsLeft:uint = 0 public function end():void { if (length == 1) { this[0] &= 0x7F } else { for (var i:uint = length; i > 0;) { const l:uint = i - 1 const byte:uint = this[l] if (byte != 0x80) { this[l] = byte & 0x7F length = i return } i = l } this[0] = 0 length = 1 } } public function write(number:uint, bits:uint):void { if (bits <= bitsLeft) { this[length - 1] |= number << (7 - bitsLeft) bitsLeft -= bits } else { if (bitsLeft != 0) { this[length - 1] |= number << (7 - bitsLeft) bits -= bitsLeft number >>>= bitsLeft } while (bits >= 7) { writeByte(0x80 | number) number >>>= 7 bits -= 7 } writeByte(0x80 | number) bitsLeft = 7 - bits } } } }
修复 Varint 大于 127 时组包错误的问题
修复 Varint 大于 127 时组包错误的问题
ActionScript
bsd-2-clause
tconkling/protoc-gen-as3
3fa970810690c6a28fd4d6a0b0bc76fb1173c8f4
HLSPlugin/src/com/kaltura/hls/m2ts/M2TSNetLoader.as
HLSPlugin/src/com/kaltura/hls/m2ts/M2TSNetLoader.as
package com.kaltura.hls.m2ts { import com.kaltura.hls.HLSDVRTimeTrait; import com.kaltura.hls.HLSDVRTrait; import com.kaltura.hls.HLSMetadataNamespaces; import flash.net.NetConnection; import flash.net.NetStream; import flash.events.NetStatusEvent; import org.osmf.events.DVRStreamInfoEvent; import org.osmf.media.MediaResourceBase; import org.osmf.media.URLResource; import org.osmf.metadata.Metadata; import org.osmf.metadata.MetadataNamespaces; import org.osmf.net.NetStreamLoadTrait; import org.osmf.net.NetStreamCodes; import org.osmf.net.httpstreaming.HLSHTTPNetStream; import org.osmf.net.httpstreaming.HTTPStreamingFactory; import org.osmf.net.httpstreaming.HTTPStreamingNetLoader; import org.osmf.net.httpstreaming.dvr.DVRInfo; import org.osmf.traits.LoadState; /** * Factory to identify and process MPEG2 TS via OSMF. */ public class M2TSNetLoader extends HTTPStreamingNetLoader { private var netStream:HLSHTTPNetStream; override public function canHandleResource( resource:MediaResourceBase ):Boolean { var metadata:Object = resource.getMetadataValue( HLSMetadataNamespaces.PLAYABLE_RESOURCE_METADATA ); if ( metadata != null && metadata == true ) return true; return false; } override protected function createNetStream(connection:NetConnection, resource:URLResource):NetStream { var factory:HTTPStreamingFactory = new M2TSStreamingFactory(); var httpNetStream:HLSHTTPNetStream = new HLSHTTPNetStream(connection, factory, resource); return httpNetStream; } override protected function processFinishLoading(loadTrait:NetStreamLoadTrait):void { var resource:URLResource = loadTrait.resource as URLResource; if (!dvrMetadataPresent(resource)) { updateLoadTrait(loadTrait, LoadState.READY); return; } netStream = loadTrait.netStream as HLSHTTPNetStream; netStream.addEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo); netStream.DVRGetStreamInfo(null); function onDVRStreamInfo(event:DVRStreamInfoEvent):void { netStream.removeEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo); loadTrait.setTrait(new HLSDVRTrait(loadTrait.connection, netStream, event.info as DVRInfo)); loadTrait.setTrait(new HLSDVRTimeTrait(loadTrait.connection, netStream, event.info as DVRInfo)); updateLoadTrait(loadTrait, LoadState.READY); } } private function dvrMetadataPresent(resource:URLResource):Boolean { var metadata:Metadata = resource.getMetadataValue(MetadataNamespaces.DVR_METADATA) as Metadata; return (metadata != null); } } }
package com.kaltura.hls.m2ts { import com.kaltura.hls.HLSDVRTimeTrait; import com.kaltura.hls.HLSDVRTrait; import com.kaltura.hls.HLSMetadataNamespaces; import flash.net.NetConnection; import flash.net.NetStream; import flash.events.NetStatusEvent; import org.osmf.events.DVRStreamInfoEvent; import org.osmf.media.MediaResourceBase; import org.osmf.media.URLResource; import org.osmf.metadata.Metadata; import org.osmf.metadata.MetadataNamespaces; import org.osmf.net.NetStreamLoadTrait; import org.osmf.net.NetStreamCodes; import org.osmf.net.httpstreaming.HLSHTTPNetStream; import org.osmf.net.httpstreaming.HTTPStreamingFactory; import org.osmf.net.httpstreaming.HTTPStreamingNetLoader; import org.osmf.net.httpstreaming.dvr.DVRInfo; import org.osmf.traits.LoadState; import org.osmf.net.NetStreamSwitchManagerBase import org.osmf.net.metrics.BandwidthMetric; import org.osmf.net.DynamicStreamingResource; import org.osmf.net.httpstreaming.DefaultHTTPStreamingSwitchManager; import org.osmf.net.metrics.MetricType; import org.osmf.net.rules.BandwidthRule; /** * Factory to identify and process MPEG2 TS via OSMF. */ public class M2TSNetLoader extends HTTPStreamingNetLoader { private var netStream:HLSHTTPNetStream; override public function canHandleResource( resource:MediaResourceBase ):Boolean { var metadata:Object = resource.getMetadataValue( HLSMetadataNamespaces.PLAYABLE_RESOURCE_METADATA ); if ( metadata != null && metadata == true ) return true; return false; } override protected function createNetStream(connection:NetConnection, resource:URLResource):NetStream { var factory:HTTPStreamingFactory = new M2TSStreamingFactory(); var httpNetStream:HLSHTTPNetStream = new HLSHTTPNetStream(connection, factory, resource); return httpNetStream; } override protected function createNetStreamSwitchManager(connection:NetConnection, netStream:NetStream, dsResource:DynamicStreamingResource):NetStreamSwitchManagerBase { var switcher:DefaultHTTPStreamingSwitchManager = super.createNetStreamSwitchManager(connection, netStream, dsResource) as DefaultHTTPStreamingSwitchManager; // Since our segments are large, switch rapidly. // First, try to bias the bandwidth metric itself. var weights:Vector.<Number> = new Vector.<Number>; weights.push(1.0); weights.push(0.0); weights.push(0.0); var bw:BandwidthMetric = switcher.metricRepository.getMetric(MetricType.BANDWIDTH, weights) as BandwidthMetric; trace("Tried to override BandwidthMetric to N=1, and N=" + bw.weights.length); // Second, bias the bandwidthrule. for(var i:int=0; i<switcher.normalRules.length; i++) { var bwr:BandwidthRule = switcher.normalRules[i] as BandwidthRule; if(!bwr) continue; bwr.weights.length = 3; bwr.weights[0] = 1.0; bwr.weights[1] = 0.0; bwr.weights[2] = 0.0; trace("Adjusted BandwidthRule"); } return switcher; } override protected function processFinishLoading(loadTrait:NetStreamLoadTrait):void { // Set up DVR state updating. var resource:URLResource = loadTrait.resource as URLResource; if (!dvrMetadataPresent(resource)) { updateLoadTrait(loadTrait, LoadState.READY); return; } netStream = loadTrait.netStream as HLSHTTPNetStream; netStream.addEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo); netStream.DVRGetStreamInfo(null); function onDVRStreamInfo(event:DVRStreamInfoEvent):void { netStream.removeEventListener(DVRStreamInfoEvent.DVRSTREAMINFO, onDVRStreamInfo); loadTrait.setTrait(new HLSDVRTrait(loadTrait.connection, netStream, event.info as DVRInfo)); loadTrait.setTrait(new HLSDVRTimeTrait(loadTrait.connection, netStream, event.info as DVRInfo)); updateLoadTrait(loadTrait, LoadState.READY); } } private function dvrMetadataPresent(resource:URLResource):Boolean { var metadata:Metadata = resource.getMetadataValue(MetadataNamespaces.DVR_METADATA) as Metadata; return (metadata != null); } } }
Adjust weighting to react to latest segment speed exclusively.
Adjust weighting to react to latest segment speed exclusively.
ActionScript
agpl-3.0
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
0a0567dbcaa9c9d35aa057cccb307db8f91684f2
ImpetusSound.as
ImpetusSound.as
package io.github.jwhile.impetus { import flash.media.Sound; import flash.media.SoundChannel; import flash.net.URLRequest; public class ImpetusSound { private var sound:Sound; private var channels:Vector.<SoundChannel>; public function ImpetusSound(url:String):void { this.sound = new Sound(); this.channels = new Vector.<SoundChannel>; this.sound.load(new URLRequest(url)); } public function playNew():SoundChannel { var c:SoundChannel = this.sound.play(0); channels.push(c); return c; } } }
package io.github.jwhile.impetus { import flash.media.Sound; import flash.net.URLRequest; public class ImpetusSound { private var sound:Sound; private var channels:Vector.<ImpetusChannel>; public function ImpetusSound(url:String):void { this.sound = new Sound(); this.channels = new Vector.<ImpetusChannel>; this.sound.load(new URLRequest(url)); } public function playNew():ImpetusChannel { var c:ImpetusChannel = new ImpetusChannel(this.sound.play(0)); channels.push(c); return c; } } }
Use ImpetusChannel instead SoundChannel
Use ImpetusChannel instead SoundChannel
ActionScript
mit
Julow/Impetus
fff3e47ef0cf51360c9aef73e3b445174caa77b4
src/aerys/minko/scene/node/camera/AbstractCamera.as
src/aerys/minko/scene/node/camera/AbstractCamera.as
package aerys.minko.scene.node.camera { import flash.geom.Point; import aerys.minko.ns.minko_camera; import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.data.CameraDataProvider; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.type.Signal; import aerys.minko.type.math.Frustum; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Ray; import aerys.minko.type.math.Vector4; public class AbstractCamera extends AbstractSceneNode { use namespace minko_camera; public static const DEFAULT_ZNEAR : Number = .1; public static const DEFAULT_ZFAR : Number = 500.; minko_camera var _cameraCtrl : CameraController; minko_camera var _cameraData : CameraDataProvider; protected var _enabled : Boolean; protected var _activated : Signal; protected var _deactivated : Signal; 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 frustum() : Frustum { return _cameraData.frustum; } protected function get cameraController() : CameraController { return _cameraCtrl; } protected function get cameraData() : CameraDataProvider { return _cameraData; } public function AbstractCamera(zNear : Number = DEFAULT_ZNEAR, zFar : Number = DEFAULT_ZFAR) { super(); initializeCameraData(zNear, zFar); } override protected function initialize() : void { _enabled = true; super.initialize(); } override protected function initializeSignals():void { super.initializeSignals(); _activated = new Signal('Camera.activated'); _deactivated = new Signal('Camera.deactivated'); } override protected function initializeContollers():void { super.initializeContollers(); _cameraCtrl = new CameraController(); addController(_cameraCtrl); } override protected function initializeDataProviders():void { super.initializeDataProviders(); _cameraData = _cameraCtrl.cameraData; } protected function initializeCameraData(zNear : Number, zFar : Number) : void { _cameraData.zNear = zNear; _cameraData.zFar = zFar; } public function unproject(x : Number, y : Number, out : Ray = null) : Ray { throw new Error('Must be overriden.'); } public function project(worldPosition : Vector4, output : Point = null) : Point { throw new Error('Must be overriden.'); } /** * Return a copy of the world to view matrix. This method is an alias on the * getWorldToLocalTransform() method. * * @param output * @return * */ public function getWorldToViewTransform(forceUpdate : Boolean = false, output : Matrix4x4 = null) : Matrix4x4 { return getWorldToLocalTransform(forceUpdate, output); } /** * Return a copy of the view to world matrix. This method is an alias on the * getLocalToWorldTransform() method. * * @param output * @return * */ public function getViewToWorldTransform(forceUpdate : Boolean = false, output : Matrix4x4 = null) : Matrix4x4 { return getLocalToWorldTransform(forceUpdate, output); } /** * Return a copy of the projection matrix. * * @param output * @return * */ public function getProjection(output : Matrix4x4) : Matrix4x4 { output ||= new Matrix4x4(); return output.copyFrom(_cameraData.projection); } } }
package aerys.minko.scene.node.camera { import flash.geom.Point; import aerys.minko.ns.minko_camera; import aerys.minko.scene.controller.camera.CameraController; import aerys.minko.scene.data.CameraDataProvider; import aerys.minko.scene.node.AbstractSceneNode; import aerys.minko.type.Signal; import aerys.minko.type.math.Frustum; import aerys.minko.type.math.Matrix4x4; import aerys.minko.type.math.Ray; import aerys.minko.type.math.Vector4; public class AbstractCamera extends AbstractSceneNode { use namespace minko_camera; public static const DEFAULT_ZNEAR : Number = .1; public static const DEFAULT_ZFAR : Number = 500.; minko_camera var _cameraCtrl : CameraController; minko_camera var _cameraData : CameraDataProvider; protected var _enabled : Boolean; protected var _activated : Signal; protected var _deactivated : Signal; 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 frustum() : Frustum { return _cameraData.frustum; } protected function get cameraController() : CameraController { return _cameraCtrl; } protected function get cameraData() : CameraDataProvider { return _cameraData; } public function AbstractCamera(zNear : Number = DEFAULT_ZNEAR, zFar : Number = DEFAULT_ZFAR) { super(); initializeCameraData(zNear, zFar); } override protected function initialize() : void { _enabled = true; super.initialize(); } override protected function initializeSignals():void { super.initializeSignals(); _activated = new Signal('Camera.activated'); _deactivated = new Signal('Camera.deactivated'); } override protected function initializeContollers():void { super.initializeContollers(); _cameraCtrl = new CameraController(); addController(_cameraCtrl); } override protected function initializeDataProviders():void { super.initializeDataProviders(); _cameraData = _cameraCtrl.cameraData; } protected function initializeCameraData(zNear : Number, zFar : Number) : void { _cameraData.zNear = zNear; _cameraData.zFar = zFar; } public function unproject(x : Number, y : Number, out : Ray = null) : Ray { throw new Error('Must be overriden.'); } public function project(worldPosition : Vector4, output : Point = null) : Point { throw new Error('Must be overriden.'); } /** * Return a copy of the world to view matrix. This method is an alias on the * getWorldToLocalTransform() method. * * @param output * @return * */ public function getWorldToViewTransform(forceUpdate : Boolean = false, output : Matrix4x4 = null) : Matrix4x4 { return getWorldToLocalTransform(forceUpdate, output); } /** * Return a copy of the view to world matrix. This method is an alias on the * getLocalToWorldTransform() method. * * @param output * @return * */ public function getViewToWorldTransform(forceUpdate : Boolean = false, output : Matrix4x4 = null) : Matrix4x4 { return getLocalToWorldTransform(forceUpdate, output); } /** * Return a copy of the projection matrix. * * @param output * @return * */ public function getProjection(output : Matrix4x4 = null) : Matrix4x4 { output ||= new Matrix4x4(); return output.copyFrom(_cameraData.projection); } } }
Fix missing default argument.
Fix missing default argument.
ActionScript
mit
aerys/minko-as3
5e0eb1d97016e3169ea2cc8ac6722bbb02bbcfff
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-2009 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.Log; import com.threerings.util.Maps; import com.threerings.util.maps.ForwardingMap; /** * A {@link HashMap} that can be sent over the wire, bearing in mind that all keys and values must * be primitives or implement {@link Streamable}. */ public class StreamableHashMap extends ForwardingMap implements Streamable { public function StreamableHashMap (keyClazz :Class = null) { if (keyClazz != null) { super(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 { // shit! Log.getLog(this).warning("Empty StreamableHashMap read, guessing DictionaryMap."); _source = Maps.newMapOf(Object); } } } }
// // $Id$ // // Narya library - tools for developing networked games // Copyright (C) 2002-2009 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.Log; import com.threerings.util.Maps; import com.threerings.util.maps.ForwardingMap; /** * A @see com.threerings.util.Map that can be sent over the wire, * bearing in mind that all keys and values must * be primitives or implement @see com.threerings.io.Streamable */ public class StreamableHashMap extends ForwardingMap implements Streamable { public function StreamableHashMap (keyClazz :Class = null) { if (keyClazz != null) { super(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 { // shit! Log.getLog(this).warning("Empty StreamableHashMap read, guessing DictionaryMap."); _source = Maps.newMapOf(Object); } } } }
Fix the asdocs here. But wait, why is this even showing up in the SDK docs?
Fix the asdocs here. But wait, why is this even showing up in the SDK docs? git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5930 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
b9d05ab7c28d46cd78ed67539719266e6a2be545
collect-client/src/generated/flex/org/openforis/collect/metamodel/proxy/UITabSetProxy.as
collect-client/src/generated/flex/org/openforis/collect/metamodel/proxy/UITabSetProxy.as
/** * Generated by Gas3 v2.3.0 (Granite Data Services). * * NOTE: this file is only generated if it does not exist. You may safely put * your custom code here. */ package org.openforis.collect.metamodel.proxy { import mx.collections.IList; import org.openforis.collect.util.CollectionUtil; [Bindable] [RemoteClass(alias="org.openforis.collect.metamodel.proxy.UITabSetProxy")] public class UITabSetProxy extends UITabSetProxyBase { public function getTab(name:String):UITabProxy { var stack:Array = new Array(); stack.push(tabs); while (stack.length > 0) { var tabs:IList = stack.pop(); for each(var tab:UITabProxy in tabs) { if(tab.name == name) { return tab; } if ( CollectionUtil.isNotEmpty(tab.tabs) ) { stack.push(tab.tabs); } } } return null; } } }
/** * Generated by Gas3 v2.3.0 (Granite Data Services). * * NOTE: this file is only generated if it does not exist. You may safely put * your custom code here. */ package org.openforis.collect.metamodel.proxy { import mx.collections.IList; import org.openforis.collect.util.CollectionUtil; [Bindable] [RemoteClass(alias="org.openforis.collect.metamodel.proxy.UITabSetProxy")] public class UITabSetProxy extends UITabSetProxyBase { public function getTab(name:String):UITabProxy { var stack:Array = new Array(); stack.push(this.tabs); while (stack.length > 0) { var currentTabs:IList = stack.pop(); for each(var tab:UITabProxy in currentTabs) { if(tab.name == name) { return tab; } if ( CollectionUtil.isNotEmpty(tab.tabs) ) { stack.push(tab.tabs); } } } return null; } } }
Fix unexpected behavior with nested tabs
Fix unexpected behavior with nested tabs
ActionScript
mit
openforis/collect,openforis/collect,openforis/collect,openforis/collect
d208a2aefc5ef9c027e3372d24158aece16255f1
source/com/thebannerboss/utils/BossClick.as
source/com/thebannerboss/utils/BossClick.as
/** * BossClick.as * @author Christopher Long at The Banner Boss - @clong * @description Creates and adds an invisible hitArea over the entirety * of the banner. It also filters a basic clickTAG request * sent from a web browser into the banner swf file. * Finally, there is a method to add a border * around the edge of the banner which is required by * most websites that host ads. */ package com.thebannerboss.utils{ import flash.events.MouseEvent; import flash.display.Stage; import flash.display.Sprite; import flash.display.Shape; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.external.ExternalInterface; public class BossClick extends Sprite{ private var url:String; private var hitAreaWidth:uint; private var hitAreaHeight:uint; public function BossClick(loaderInfo:Object,stage:Stage) { // trace('BossClick : Add clickTag button? Add a border?'); // } public function addClickTagBtn():void{ //Invisible hit area hitAreaWidth = stage.stageWidth; hitAreaHeight = stage.stageHeight; this.graphics.beginFill(0xFF0000, 0); this.graphics.drawRect( 0, 0, hitAreaWidth, hitAreaHeight ); this.graphics.endFill(); //Check for various iterations of clickTAG if(loaderInfo.parameters.clicktag != null) { url = loaderInfo.parameters.clicktag; } else if(loaderInfo.parameters.clickTag != null) { url = loaderInfo.parameters.clickTag; }else if(loaderInfo.parameters.clickTag1 != null) { url = loaderInfo.parameters.clickTag1; }else if(loaderInfo.parameters.clickTAG != null) { url = loaderInfo.parameters.clickTAG; } //Add Click event listener to trigger actions when the banner is clicked on addEventListener(MouseEvent.CLICK, clickHandler); buttonMode = true; // trace('BossClick : clickTag button added.'); } //CLICKTAG MANNIPULATION BEGIN ---!!!!!! private function clickHandler(e:MouseEvent):void { if (! url) { trace("BossClick : clickTag button pressed."); }else{ openWindow( url ); } } private function getBrowserName():String { var browser:String; //Uses external interface to reach out to browser and grab browser useragent info. var browserAgent:String = ExternalInterface.call("function getBrowser(){return navigator.userAgent;}"); //Determines brand of browser using a find index. If not found indexOf returns (-1). if (browserAgent != null && browserAgent.indexOf("Firefox")>= 0) { browser = "Firefox"; } else if (browserAgent != null && browserAgent.indexOf("Safari")>= 0) { browser = "Safari"; } else if (browserAgent != null && browserAgent.indexOf("MSIE")>= 0) { browser = "IE"; } else if (browserAgent != null && browserAgent.indexOf("Opera")>= 0) { browser = "Opera"; } else { browser = "Undefined"; } return (browser); } //Try to avoid pop-blockers by using ExternalInterface call to load url private function openWindow(url:String, target:String = '_blank', features:String=""):void { var WINDOW_OPEN_FUNCTION:String = "window.open"; var myURL:URLRequest = new URLRequest(url); var browserName:String = getBrowserName(); switch (browserName) { //If browser is Firefox, use ExternalInterface to call out to browser //and launch window via browser's window.open method. case "Firefox" : ExternalInterface.call(WINDOW_OPEN_FUNCTION, url, target, features); break; //If IE, case "IE" : ExternalInterface.call("function setWMWindow() {window.open('" + url + "', '"+target+"', '"+features+"');}"); break; // If Safari or Opera or any other; case "Safari" : navigateToURL(myURL, target); break; case "Opera" : navigateToURL(myURL, target); break; default : navigateToURL(myURL, target); break; } } //CLICKTAG MANNIPULATION END ---!!!!!! //BORDER BEGIN ---!!!!!! //addBorder - if no properties are set on method call, give the banner a black border that is 2 pxls thick public function addBorder(borderThickness:uint=2,borderColor:uint=0x000000):void{ //rect visual properties var borderRectHeight:uint = hitAreaHeight; var borderRectWidth:uint = hitAreaWidth; var borderRect:Shape = new Shape(); borderRect.graphics.lineStyle(borderThickness, borderColor, 1); // rect starting at point 0, 0 borderRect.graphics.moveTo(0, 0); borderRect.graphics.lineTo(borderRectWidth - 1, 0); borderRect.graphics.lineTo(borderRectWidth - 1, borderRectHeight - 1); borderRect.graphics.lineTo(0, borderRectHeight - 1); borderRect.graphics.lineTo(0, 0); addChild(borderRect); // trace('BossClick : border added.'); } //BORDER END ---!!!!!! } }
/** * BossClick.as * @author Christopher Long at The Banner Boss - @clong * @description Creates and adds an invisible hitArea over the entirety * of the banner. It also filters a basic clickTAG request * sent from a web browser into the banner swf file. * Finally, there is a method to add a border * around the edge of the banner which is required by * most websites that host ads. */ package com.thebannerboss.utils{ import flash.events.MouseEvent; import flash.display.Stage; import flash.display.Sprite; import flash.display.Shape; import flash.net.URLRequest; import flash.net.navigateToURL; import flash.external.ExternalInterface; import flash.system.Capabilities; public class BossClick extends Sprite{ private var url:String; private var hitAreaWidth:uint; private var hitAreaHeight:uint; public function BossClick(loaderInfo:Object,stage:Stage) { // trace('BossClick : Add clickTag button? Add a border?'); // } public function addClickTagBtn():void{ //Invisible hit area hitAreaWidth = stage.stageWidth; hitAreaHeight = stage.stageHeight; this.graphics.beginFill(0xFF0000, 0); this.graphics.drawRect( 0, 0, hitAreaWidth, hitAreaHeight ); this.graphics.endFill(); //Check for various iterations of clickTAG if(loaderInfo.parameters.clicktag != null) { url = loaderInfo.parameters.clicktag; } else if(loaderInfo.parameters.clickTag != null) { url = loaderInfo.parameters.clickTag; }else if(loaderInfo.parameters.clickTag1 != null) { url = loaderInfo.parameters.clickTag1; }else if(loaderInfo.parameters.clickTAG != null) { url = loaderInfo.parameters.clickTAG; } //Add Click event listener to trigger actions when the banner is clicked on addEventListener(MouseEvent.CLICK, clickHandler); buttonMode = true; // trace('BossClick : clickTag button added.'); } //CLICKTAG MANNIPULATION BEGIN ---!!!!!! private function clickHandler(e:MouseEvent):void { if (! url) { trace("BossClick : clickTag button pressed."); }else{ //Try to avoid pop-blockers by using ExternalInterface call to load url if(Capabilities.playerType == "ActiveX" && Capabilities.os != "Mac" && ExternalInterface.available) { ExternalInterface.call("window.open", url, "_blank", ""); } else { navigateToURL(new URLRequest(url), "_blank"); } } } //Try to avoid pop-blockers by using ExternalInterface call to load url //CLICKTAG MANNIPULATION END ---!!!!!! //BORDER BEGIN ---!!!!!! //addBorder - if no properties are set on method call, give the banner a black border that is 2 pxls thick public function addBorder(borderThickness:uint=2,borderColor:uint=0x000000):void{ //rect visual properties var borderRectHeight:uint = hitAreaHeight; var borderRectWidth:uint = hitAreaWidth; var borderRect:Shape = new Shape(); borderRect.graphics.lineStyle(borderThickness, borderColor, 1); // rect starting at point 0, 0 borderRect.graphics.moveTo(0, 0); borderRect.graphics.lineTo(borderRectWidth - 1, 0); borderRect.graphics.lineTo(borderRectWidth - 1, borderRectHeight - 1); borderRect.graphics.lineTo(0, borderRectHeight - 1); borderRect.graphics.lineTo(0, 0); addChild(borderRect); // trace('BossClick : border added.'); } //BORDER END ---!!!!!! } }
Update BossClick.as
Update BossClick.as I updated how BossClick attempts to avoid pop-up blockers. Instead of looking for various browsers by name, BossClick now looks for the Flash "player type" to see if it is ActiveX or Mac. If the "player type" is ActiveX, BossClick opens the clickThrough link in a window by making a Javascript call from the browser instead of using the inherit Flash method of opening a browser window.
ActionScript
mit
TheBannerBoss/BossClick
7a3b86807e64a3379fc84635ba4b4bcb525520c7
src/aerys/minko/render/effect/basic/BasicEffect.as
src/aerys/minko/render/effect/basic/BasicEffect.as
package aerys.minko.render.effect.basic { import aerys.minko.render.RenderTarget; import aerys.minko.render.effect.IEffect; import aerys.minko.render.effect.IEffectPass; import aerys.minko.render.effect.fog.FogStyle; import aerys.minko.render.renderer.state.Blending; import aerys.minko.render.renderer.state.CompareMode; import aerys.minko.render.renderer.state.RendererState; import aerys.minko.render.renderer.state.TriangleCulling; import aerys.minko.render.shader.ActionScriptShader; import aerys.minko.render.shader.SValue; import aerys.minko.render.shader.node.Components; import aerys.minko.render.shader.node.INode; import aerys.minko.scene.visitor.data.CameraData; import aerys.minko.scene.visitor.data.LocalData; import aerys.minko.scene.visitor.data.StyleStack; import aerys.minko.scene.visitor.data.ViewportData; import aerys.minko.type.math.ConstVector4; import flash.utils.Dictionary; [StyleParameter(name="basic diffuse map",type="texture")] [StyleParameter(name="fog enabled",type="boolean")] [StyleParameter(name="fog color",type="color")] [StyleParameter(name="fog start",type="number")] [StyleParameter(name="fog distance",type="number")] public class BasicEffect extends ActionScriptShader implements IEffect, IEffectPass { protected var _priority : Number; protected var _renderTarget : RenderTarget; protected var _passes : Vector.<IEffectPass> = Vector.<IEffectPass>([this]); public function BasicEffect(priority : Number = 0, renderTarget : RenderTarget = null) { _priority = priority; _renderTarget = renderTarget; } public function getPasses(styleStack : StyleStack, local : LocalData, world : Dictionary) : Vector.<IEffectPass> { return _passes; } override public function fillRenderState(state : RendererState, style : StyleStack, local : LocalData, world : Dictionary) : Boolean { super.fillRenderState(state, style, local, world); var blending : uint = style.get(BasicStyle.BLENDING, Blending.NORMAL) as uint; state.depthTest = CompareMode.LESS; state.blending = blending; state.triangleCulling = style.get(BasicStyle.TRIANGLE_CULLING, TriangleCulling.BACK) as uint; state.priority = _priority + .5; state.rectangle = null; state.renderTarget = _renderTarget || world[ViewportData].renderTarget; if (state.blending != Blending.NORMAL) state.priority -= .5; return true; } override protected function getOutputPosition() : SValue { return vertexClipspacePosition; } override protected function getOutputColor() : SValue { var diffuse : SValue = null; if (styleIsSet(BasicStyle.DIFFUSE_MAP)) diffuse = sampleTexture(BasicStyle.DIFFUSE_MAP, interpolate(vertexUV)); else diffuse = combine(interpolate(vertexRGBColor).rgb, 1.); // fog if (getStyleConstant(FogStyle.FOG_ENABLED, false)) { var zFar : SValue = styleIsSet(FogStyle.DISTANCE) ? getStyleParameter(1, FogStyle.DISTANCE) : getWorldParameter(1, CameraData, CameraData.Z_FAR); var fogColor : * = styleIsSet(FogStyle.COLOR) ? getStyleParameter(3, FogStyle.COLOR) : vector3(0., 0., 0.); var fogStart : * = styleIsSet(FogStyle.START) ? getStyleParameter(1, FogStyle.START) : 0.; fogColor = getFogColor(fogStart, zFar, fogColor); diffuse = blend(fogColor, diffuse, Blending.ALPHA); } return diffuse; } override protected function getDataHash(style : StyleStack, local : LocalData, world : Dictionary) : String { var hash : String = "basic"; hash += style.get(BasicStyle.DIFFUSE_MAP, false) ? "_diffuse" : "_color"; if (style.get(FogStyle.FOG_ENABLED, false)) { hash += "_fog("; hash += "start=" + style.get(FogStyle.START, 0.); hash += ",distance=" + style.get(FogStyle.DISTANCE, 0.); hash += ",color=" + style.get(FogStyle.COLOR, 0); hash += ");" } return hash; } } }
package aerys.minko.render.effect.basic { import aerys.minko.render.RenderTarget; import aerys.minko.render.effect.IEffect; import aerys.minko.render.effect.IEffectPass; import aerys.minko.render.effect.fog.FogStyle; import aerys.minko.render.renderer.state.Blending; import aerys.minko.render.renderer.state.CompareMode; import aerys.minko.render.renderer.state.RendererState; import aerys.minko.render.renderer.state.TriangleCulling; import aerys.minko.render.shader.ActionScriptShader; import aerys.minko.render.shader.SValue; import aerys.minko.render.shader.node.Components; import aerys.minko.render.shader.node.INode; import aerys.minko.scene.visitor.data.CameraData; import aerys.minko.scene.visitor.data.LocalData; import aerys.minko.scene.visitor.data.StyleStack; import aerys.minko.scene.visitor.data.ViewportData; import aerys.minko.type.math.ConstVector4; import flash.utils.Dictionary; [StyleParameter(name="basic diffuse map",type="texture")] [StyleParameter(name="fog enabled",type="boolean")] [StyleParameter(name="fog color",type="color")] [StyleParameter(name="fog start",type="number")] [StyleParameter(name="fog distance",type="number")] public class BasicEffect extends ActionScriptShader implements IEffect, IEffectPass { protected var _priority : Number; protected var _renderTarget : RenderTarget; protected var _passes : Vector.<IEffectPass> = Vector.<IEffectPass>([this]); public function BasicEffect(priority : Number = 0, renderTarget : RenderTarget = null) { _priority = priority; _renderTarget = renderTarget; } public function getPasses(styleStack : StyleStack, local : LocalData, world : Dictionary) : Vector.<IEffectPass> { return _passes; } override public function fillRenderState(state : RendererState, style : StyleStack, local : LocalData, world : Dictionary) : Boolean { super.fillRenderState(state, style, local, world); var blending : uint = style.get(BasicStyle.BLENDING, Blending.NORMAL) as uint; state.depthTest = CompareMode.LESS; state.blending = blending; state.triangleCulling = style.get(BasicStyle.TRIANGLE_CULLING, TriangleCulling.BACK) as uint; state.priority = _priority + .5; state.rectangle = null; state.renderTarget = _renderTarget || world[ViewportData].renderTarget; if (state.blending != Blending.NORMAL) state.priority -= .5; return true; } override protected function getOutputPosition() : SValue { return vertexClipspacePosition; } override protected function getOutputColor() : SValue { var diffuse : SValue = null; if (styleIsSet(BasicStyle.DIFFUSE_MAP)) diffuse = sampleTexture(BasicStyle.DIFFUSE_MAP, interpolate(vertexUV)); else if (styleIsSet(BasicStyle.DIFFUSE_COLOR)) diffuse = getStyleParameter(4, BasicStyle.DIFFUSE_COLOR); else diffuse = combine(interpolate(vertexRGBColor).rgb, 1.); // fog if (getStyleConstant(FogStyle.FOG_ENABLED, false)) { var zFar : SValue = styleIsSet(FogStyle.DISTANCE) ? getStyleParameter(1, FogStyle.DISTANCE) : getWorldParameter(1, CameraData, CameraData.Z_FAR); var fogColor : * = styleIsSet(FogStyle.COLOR) ? getStyleParameter(3, FogStyle.COLOR) : vector3(0., 0., 0.); var fogStart : * = styleIsSet(FogStyle.START) ? getStyleParameter(1, FogStyle.START) : 0.; fogColor = getFogColor(fogStart, zFar, fogColor); diffuse = blend(fogColor, diffuse, Blending.ALPHA); } return diffuse; } override protected function getDataHash(style : StyleStack, local : LocalData, world : Dictionary) : String { var hash : String = "basic"; hash += style.get(BasicStyle.DIFFUSE_MAP, false) ? "_diffuse" : "_color"; if (style.get(FogStyle.FOG_ENABLED, false)) { hash += "_fog("; hash += "start=" + style.get(FogStyle.START, 0.); hash += ",distance=" + style.get(FogStyle.DISTANCE, 0.); hash += ",color=" + style.get(FogStyle.COLOR, 0); hash += ");" } return hash; } } }
Add the possibility to set the diffuse color from BasicStyle.DIFFUSE_COLOR before searching for them into vertex attributes
Add the possibility to set the diffuse color from BasicStyle.DIFFUSE_COLOR before searching for them into vertex attributes
ActionScript
mit
aerys/minko-as3
f1fd2fcee0680d0079f19d6a2eeb21016e56b3b2
frameworks/as/projects/FlexJSUI/src/mx/states/State.as
frameworks/as/projects/FlexJSUI/src/mx/states/State.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. // //////////////////////////////////////////////////////////////////////////////// // shim the mx classes for states package mx.states { /** * The State class is one of the classes in the * view states subsystem. It is used to declare a * view state in an MXML document. This is one of the * few classes in FlexJS that use the same name as * a Flex SDK class because some of the IDEs and * compilers are hard-coded to assume this name. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class State { /** * Constructor. * * @param properties This parameter is not used in FlexJS and exists to make legacy compilers happy. * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function State(properties:Object = null) { super(); } /** * The name of the state. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var name:String; /** * The array of overrides. This is normally set by the compiler. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var overrides:Array; } }
//////////////////////////////////////////////////////////////////////////////// // // 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. // //////////////////////////////////////////////////////////////////////////////// // shim the mx classes for states package mx.states { /** * The State class is one of the classes in the * view states subsystem. It is used to declare a * view state in an MXML document. This is one of the * few classes in FlexJS that use the same name as * a Flex SDK class because some of the IDEs and * compilers are hard-coded to assume this name. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion FlexJS 0.0 */ public class State { /** * Constructor. * * @param properties This parameter is not used in FlexJS and exists to make legacy compilers happy. * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public function State(properties:Object = null) { super(); } /** * The name of the state. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var name:String; /** * Comma-delimited list of state groups of the state. * It is not an array so don't use square brackets []. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var stateGroups:String; /** * The array of overrides. This is normally set by the compiler. * * @langversion 3.0 * @playerversion Flash 9 * @playerversion AIR 1.1 * @productversion Flex 3 */ public var overrides:Array; } }
handle stateGroups
handle stateGroups
ActionScript
apache-2.0
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
ae5b5552177ec44ee7d4e552ded6dbd9f97c4a94
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
WEB-INF/lps/lfc/kernel/swf9/LzMouseKernel.as
/** * LzMouseKernel.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 */ // Receives mouse events from the runtime class LzMouseKernel { #passthrough (toplevel:true) { import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.ui.Mouse; }# // sends mouse events to the callback static function __sendEvent(view:*, eventname:String) :void { if (__callback) __scope[__callback](eventname, view); //Debug.write('LzMouseKernel event', eventname); } static var __callback:String = null; static var __scope:* = null; static var __lastMouseDown:LzSprite = null; static var __mouseLeft:Boolean = false; static var __listeneradded:Boolean = false; /** * Shows or hides the hand cursor for all clickable views. */ static var showhandcursor:Boolean = true; static function setCallback (scope:*, funcname:String) :void { __scope = scope; __callback = funcname; if (__listeneradded == false) { /* TODO [hqm 2008-01] Do we want to do anything with other * events, like click? stage.addEventListener(MouseEvent.CLICK, reportClick); */ LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_WHEEL, __mouseWheelHandler); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeaveHandler); __listeneradded = true; } } // Handles global mouse events static function __mouseHandler(event:MouseEvent):void { var eventname:String = 'on' + event.type.toLowerCase(); if (eventname == 'onmouseup' && __lastMouseDown != null) { // call mouseup on the sprite that got the last mouse down __lastMouseDown.__globalmouseup(event); __lastMouseDown = null; } else { if (__mouseLeft) { __mouseLeft = false; if (event.buttonDown) __mouseUpOutsideHandler(); } __sendEvent(null, eventname); } } // sends mouseup and calls __globalmouseup when the mouse goes up outside the app - see LPP-7724 static function __mouseUpOutsideHandler():void { if (__lastMouseDown != null) { var ev:MouseEvent = new MouseEvent('mouseup'); __lastMouseDown.__globalmouseup(ev); __lastMouseDown = null; } } // handles MOUSE_LEAVE event static function __mouseLeaveHandler(event:Event = null):void { __mouseLeft = true; __sendEvent(null, 'onmouseleave'); } static function __mouseWheelHandler(event:MouseEvent):void { lz.Keys.__mousewheelEvent(event.delta); } /** * Shows or hides the hand cursor for all clickable views. * @param Boolean show: true shows the hand cursor for buttons, false hides it */ static function showHandCursor (show:Boolean) :void { showhandcursor = show; } static var __amLocked:Boolean = false; static var cursorSprite:Sprite = null; static var globalCursorResource:String = null; static var lastCursorResource:String = null; /** * Sets the cursor to a resource * @param String what: The resource to use as the cursor. */ static function setCursorGlobal (what:String) :void { globalCursorResource = what; setCursorLocal(what); } static function setCursorLocal (what:String) :void { if ( __amLocked ) { return; } Mouse.hide(); cursorSprite.x = LFCApplication.stage.mouseX; cursorSprite.y = LFCApplication.stage.mouseY; LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1); if (lastCursorResource != what) { if (cursorSprite.numChildren > 0) { cursorSprite.removeChildAt(0); } var resourceSprite:Sprite = getCursorResource(what); cursorSprite.addChild( resourceSprite ); lastCursorResource = what; } // respond to mouse move events cursorSprite.startDrag(); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); cursorSprite.visible = true; } static function mouseLeaveHandler(evt:Event):void { cursorSprite.visible = false; } static function getCursorResource (resource:String):Sprite { var resinfo:Object = LzResourceLibrary[resource]; var assetclass:Class; var frames:Array = resinfo.frames; var asset:Sprite; // single frame resources get an entry in LzResourceLibrary which has // 'assetclass' pointing to the resource Class object. if (resinfo.assetclass is Class) { assetclass = resinfo.assetclass; } else { // Multiframe resources have an array of Class objects in frames[] assetclass = frames[0]; } if (! assetclass) return null; asset = new assetclass(); asset.scaleX = 1.0; asset.scaleY = 1.0; //Debug.write('cursor asset', asset); return asset; } /** * This function restores the default cursor if there is no locked cursor on * the screen. * * @access private */ static function restoreCursor () :void { if ( __amLocked ) { return; } cursorSprite.stopDrag(); cursorSprite.visible = false; globalCursorResource = null; Mouse.show(); } /** Called by LzSprite to restore cursor to global value. */ static function restoreCursorLocal () :void { if ( __amLocked ) { return; } if (globalCursorResource == null) { // Restore to system default pointer restoreCursor(); } else { // Restore to the last value set by setCursorGlobal setCursorLocal(globalCursorResource); } } /** * Prevents the cursor from being changed until unlock is called. * */ static function lock () :void { __amLocked = true; } /** * Restores the default cursor. * */ static function unlock () :void { __amLocked = false; restoreCursor(); } static function initCursor () :void { cursorSprite = new Sprite(); cursorSprite.mouseChildren = false; cursorSprite.mouseEnabled = false; // Add the cursor DisplayObject to the root sprite LFCApplication.addChild(cursorSprite); cursorSprite.x = -10000; cursorSprite.y = -10000; } }
/** * LzMouseKernel.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 */ // Receives mouse events from the runtime class LzMouseKernel { #passthrough (toplevel:true) { import flash.display.Sprite; import flash.events.Event; import flash.events.MouseEvent; import flash.ui.Mouse; import flash.ui.MouseCursor; }# // sends mouse events to the callback static function __sendEvent(view:*, eventname:String) :void { if (__callback) __scope[__callback](eventname, view); //Debug.write('LzMouseKernel event', eventname); } static var __callback:String = null; static var __scope:* = null; static var __lastMouseDown:LzSprite = null; static var __mouseLeft:Boolean = false; static var __listeneradded:Boolean = false; /** * Shows or hides the hand cursor for all clickable views. */ static var showhandcursor:Boolean = true; static function setCallback (scope:*, funcname:String) :void { __scope = scope; __callback = funcname; if (__listeneradded == false) { /* TODO [hqm 2008-01] Do we want to do anything with other * events, like click? stage.addEventListener(MouseEvent.CLICK, reportClick); */ LFCApplication.stage.addEventListener(MouseEvent.MOUSE_MOVE, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_UP, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_DOWN, __mouseHandler); LFCApplication.stage.addEventListener(MouseEvent.MOUSE_WHEEL, __mouseWheelHandler); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, __mouseLeaveHandler); __listeneradded = true; } } // Handles global mouse events static function __mouseHandler(event:MouseEvent):void { var eventname:String = 'on' + event.type.toLowerCase(); if (eventname == 'onmouseup' && __lastMouseDown != null) { // call mouseup on the sprite that got the last mouse down __lastMouseDown.__globalmouseup(event); __lastMouseDown = null; } else { if (__mouseLeft) { __mouseLeft = false; if (event.buttonDown) __mouseUpOutsideHandler(); } __sendEvent(null, eventname); } } // sends mouseup and calls __globalmouseup when the mouse goes up outside the app - see LPP-7724 static function __mouseUpOutsideHandler():void { if (__lastMouseDown != null) { var ev:MouseEvent = new MouseEvent('mouseup'); __lastMouseDown.__globalmouseup(ev); __lastMouseDown = null; } } // handles MOUSE_LEAVE event static function __mouseLeaveHandler(event:Event = null):void { __mouseLeft = true; __sendEvent(null, 'onmouseleave'); } static function __mouseWheelHandler(event:MouseEvent):void { lz.Keys.__mousewheelEvent(event.delta); } /** * Shows or hides the hand cursor for all clickable views. * @param Boolean show: true shows the hand cursor for buttons, false hides it */ static function showHandCursor (show:Boolean) :void { showhandcursor = show; } static var __amLocked:Boolean = false; static var useBuiltinCursor:Boolean = false; static var cursorSprite:Sprite = null; static var globalCursorResource:String = null; static var lastCursorResource:String = null; #passthrough { private static var __builtinCursors:Object = null; static function get builtinCursors () :Object { if (__builtinCursors == null) { var cursors:Object = {}; cursors[MouseCursor.ARROW] = true; cursors[MouseCursor.AUTO] = true; cursors[MouseCursor.BUTTON] = true; cursors[MouseCursor.HAND] = true; cursors[MouseCursor.IBEAM] = true; __builtinCursors = cursors; } return __builtinCursors; } }# /** * Sets the cursor to a resource * @param String what: The resource to use as the cursor. */ static function setCursorGlobal (what:String) :void { globalCursorResource = what; setCursorLocal(what); } static function setCursorLocal (what:String) :void { if ( __amLocked ) { return; } if (what == null) { // null is invalid, maybe call restoreCursor()? return; } else if (lastCursorResource != what) { var resourceSprite:Sprite = getCursorResource(what); if (resourceSprite != null) { if (cursorSprite.numChildren > 0) { cursorSprite.removeChildAt(0); } cursorSprite.addChild( resourceSprite ); useBuiltinCursor = false; } else if (builtinCursors[what] != null) { useBuiltinCursor = true; } else { // invalid cursor? return; } lastCursorResource = what; } if (useBuiltinCursor) { Mouse.cursor = what; cursorSprite.stopDrag(); cursorSprite.visible = false; LFCApplication.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); Mouse.show(); } else { Mouse.hide(); cursorSprite.x = LFCApplication.stage.mouseX; cursorSprite.y = LFCApplication.stage.mouseY; LFCApplication.setChildIndex(cursorSprite, LFCApplication._sprite.numChildren-1); // respond to mouse move events cursorSprite.startDrag(); LFCApplication.stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); cursorSprite.visible = true; } } static function mouseLeaveHandler(evt:Event):void { cursorSprite.visible = false; } static function getCursorResource (resource:String):Sprite { if (! (LzAsset.isMovieClipAsset(resource) || LzAsset.isMovieClipLoaderAsset(resource))) { // only swf cursors are supported return null; } var resinfo:Object = LzResourceLibrary[resource]; var assetclass:Class; // single frame resources get an entry in LzResourceLibrary which has // 'assetclass' pointing to the resource Class object. if (resinfo.assetclass is Class) { assetclass = resinfo.assetclass; } else { // Multiframe resources have an array of Class objects in frames[] var frames:Array = resinfo.frames; assetclass = frames[0]; } var asset:Sprite = new assetclass(); asset.scaleX = 1.0; asset.scaleY = 1.0; //Debug.write('cursor asset', asset); return asset; } /** * This function restores the default cursor if there is no locked cursor on * the screen. * * @access private */ static function restoreCursor () :void { if ( __amLocked ) { return; } cursorSprite.stopDrag(); cursorSprite.visible = false; LFCApplication.stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler); globalCursorResource = null; Mouse.cursor = MouseCursor.AUTO; Mouse.show(); } /** Called by LzSprite to restore cursor to global value. */ static function restoreCursorLocal () :void { if ( __amLocked ) { return; } if (globalCursorResource == null) { // Restore to system default pointer restoreCursor(); } else { // Restore to the last value set by setCursorGlobal setCursorLocal(globalCursorResource); } } /** * Prevents the cursor from being changed until unlock is called. * */ static function lock () :void { __amLocked = true; } /** * Restores the default cursor. * */ static function unlock () :void { __amLocked = false; restoreCursor(); } static function initCursor () :void { cursorSprite = new Sprite(); cursorSprite.mouseChildren = false; cursorSprite.mouseEnabled = false; // Add the cursor DisplayObject to the root sprite LFCApplication.addChild(cursorSprite); cursorSprite.x = -10000; cursorSprite.y = -10000; } }
Change 20090314-bargull-GHI by bargull@dell--p4--2-53 on 2009-03-14 19:31:57 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20090314-bargull-GHI by bargull@dell--p4--2-53 on 2009-03-14 19:31:57 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk Summary: add support for 'native' swf9 cursors New Features: LPP-7912 (SWF9: support for default cursors) Bugs Fixed: Technical Reviewer: hminsky QA Reviewer: (pending) Doc Reviewer: (pending) Documentation: Release Notes: Details: With this change the 'native' swf9 cursors (eg. hand- and ibeam-cursor) can be used for lz.Cursor.setCursorGlobal() and lz.view#cursor. Tests: testcase at bugreport git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@13289 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
4038353ab7b0d052db9f34c89d12cd46d8cfbefb
runtime/src/main/as/flump/display/LibraryLoader.as
runtime/src/main/as/flump/display/LibraryLoader.as
// // Flump - Copyright 2013 Flump Authors package flump.display { import flash.utils.ByteArray; import flump.executor.Executor; import flump.executor.Future; /** * Loads zip files created by the flump exporter and parses them into Library instances. */ public class LibraryLoader { /** * Loads a Library from the zip in the given bytes. * * @param bytes The bytes containing the zip * * @param executor The executor on which the loading should run. If not specified, it'll run on * a new single-use executor. * * @param scaleFactor the desired scale factor of the textures to load. If the Library contains * textures with multiple scale factors, loader will load the textures with the scale factor * closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be * used. * @param generateMipMaps If true (defaults to false), flump will instruct Starling to generate * mip maps for all loaded textures. Scaling will look better if mipmaps are enabled, but there * is a loading time and memory usage penalty. * * @return a Future to use to track the success or failure of loading the resources out of the * bytes. If the loading succeeds, the Future's onSuccess will fire with an instance of * Library. If it fails, the Future's onFail will fire with the Error that caused the * loading failure. */ public static function loadBytes (bytes :ByteArray, executor :Executor=null, scaleFactor :Number=-1, generateMipMaps :Boolean=false) :Future { return (executor || new Executor(1)).submit( new Loader(bytes, scaleFactor, generateMipMaps).load); } /** * Loads a Library from the zip at the given url. * * @param bytes The url where the zip can be found * * @param executor The executor on which the loading should run. If not specified, it'll run on * a new single-use executor. * * @param scaleFactor the desired scale factor of the textures to load. If the Library contains * textures with multiple scale factors, loader will load the textures with the scale factor * closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be * used. * @param generateMipMaps If true (defaults to false), flump will instruct Starling to generate * mip maps for all loaded textures. Scaling will look better if mipmaps are enabled, but there * is a loading time and memory usage penalty. * * @return a Future to use to track the success or failure of loading the resources from the * url. If the loading succeeds, the Future's onSuccess will fire with an instance of * Library. If it fails, the Future's onFail will fire with the Error that caused the * loading failure. */ public static function loadURL (url :String, executor :Executor=null, scaleFactor :Number=-1, generateMipMaps :Boolean=false) :Future { return (executor || new Executor(1)).submit( new Loader(url, scaleFactor, generateMipMaps).load); } /** @private */ public static const LIBRARY_LOCATION :String = "library.json"; /** @private */ public static const MD5_LOCATION :String = "md5"; /** @private */ public static const VERSION_LOCATION :String = "version"; /** * @private * The version produced and parsable by this version of the code. The version in a resources * zip must equal the version compiled into the parsing code for parsing to succeed. */ public static const VERSION :String = "2"; } } import deng.fzip.FZip; import deng.fzip.FZipErrorEvent; import deng.fzip.FZipEvent; import deng.fzip.FZipFile; import flash.events.Event; import flash.events.IOErrorEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.Dictionary; import flump.display.Library; import flump.display.LibraryLoader; import flump.display.Movie; import flump.executor.Executor; import flump.executor.Future; import flump.executor.FutureTask; import flump.executor.load.ImageLoader; import flump.executor.load.LoadedImage; import flump.mold.AtlasMold; import flump.mold.AtlasTextureMold; import flump.mold.LibraryMold; import flump.mold.MovieMold; import flump.mold.TextureGroupMold; import starling.core.Starling; import starling.display.DisplayObject; import starling.display.Image; import starling.textures.Texture; interface SymbolCreator { function create (library :Library) :DisplayObject; } class LibraryImpl implements Library { public function LibraryImpl (baseTextures :Vector.<Texture>, creators :Dictionary) { _baseTextures = baseTextures; _creators = creators; } public function createMovie (symbol :String) :Movie { return Movie(createDisplayObject(symbol)); } public function createImage (symbol :String) :Image { const disp :DisplayObject = createDisplayObject(symbol); if (disp is Movie) throw new Error(symbol + " is not an Image"); return Image(disp); } public function getImageTexture (symbol :String) :Texture { checkNotDisposed(); var creator :SymbolCreator = requireSymbolCreator(symbol); if (!(creator is ImageCreator)) throw new Error(symbol + " is not an Image"); return ImageCreator(creator).texture; } public function get movieSymbols () :Vector.<String> { checkNotDisposed(); const names :Vector.<String> = new <String>[]; for (var creatorName :String in _creators) { if (_creators[creatorName] is MovieCreator) names.push(creatorName); } return names; } public function get imageSymbols () :Vector.<String> { checkNotDisposed(); const names :Vector.<String> = new <String>[]; for (var creatorName :String in _creators) { if (_creators[creatorName] is ImageCreator) names.push(creatorName); } return names; } public function createDisplayObject (name :String) :DisplayObject { checkNotDisposed(); return requireSymbolCreator(name).create(this); } public function dispose () :void { checkNotDisposed(); for each (var tex :Texture in _baseTextures) { tex.dispose(); } _baseTextures = null; _creators = null; } protected function requireSymbolCreator (name :String) :SymbolCreator { var creator :SymbolCreator = _creators[name]; if (creator == null) throw new Error("No such id '" + name + "'"); return creator; } protected function checkNotDisposed () :void { if (_baseTextures == null) { throw new Error("This Library has been disposed"); } } protected var _creators :Dictionary; protected var _baseTextures :Vector.<Texture>; } class Loader { public function Loader (toLoad :Object, scaleFactor :Number, generateMipMaps :Boolean) { _scaleFactor = (scaleFactor > 0 ? scaleFactor : Starling.contentScaleFactor); _generateMipMaps = generateMipMaps; _toLoad = toLoad; } public function load (future :FutureTask) :void { _future = future; _zip.addEventListener(Event.COMPLETE, _future.monitoredCallback(onZipLoadingComplete)); _zip.addEventListener(IOErrorEvent.IO_ERROR, _future.fail); _zip.addEventListener(FZipErrorEvent.PARSE_ERROR, _future.fail); _zip.addEventListener(FZipEvent.FILE_LOADED, _future.monitoredCallback(onFileLoaded)); if (_toLoad is String) _zip.load(new URLRequest(String(_toLoad))); else _zip.loadBytes(ByteArray(_toLoad)); } protected function onFileLoaded (e :FZipEvent) :void { const loaded :FZipFile = _zip.removeFileAt(_zip.getFileCount() - 1); const name :String = loaded.filename; if (name == LibraryLoader.LIBRARY_LOCATION) { const jsonString :String = loaded.content.readUTFBytes(loaded.content.length); _lib = LibraryMold.fromJSON(JSON.parse(jsonString)); } else if (name.indexOf(PNG, name.length - PNG.length) != -1) { _atlasBytes[name] = loaded.content; } else if (name.indexOf(ATF, name.length - ATF.length) != -1) { _atlasBytes[name] = loaded.content; } else if (name == LibraryLoader.VERSION_LOCATION) { const zipVersion :String = loaded.content.readUTFBytes(loaded.content.length) if (zipVersion != LibraryLoader.VERSION) { throw new Error("Zip is version " + zipVersion + " but the code needs " + LibraryLoader.VERSION); } _versionChecked = true; } else if (name == LibraryLoader.MD5_LOCATION ) { // Nothing to verify } else {} // ignore unknown files } protected function onZipLoadingComplete (..._) :void { _zip = null; if (_lib == null) throw new Error(LibraryLoader.LIBRARY_LOCATION + " missing from zip"); if (!_versionChecked) throw new Error(LibraryLoader.VERSION_LOCATION + " missing from zip"); const loader :ImageLoader = _lib.textureFormat == "atf" ? null : new ImageLoader(); _pngLoaders.terminated.add(_future.monitoredCallback(onPngLoadingComplete)); // Determine the scale factor we want to use var textureGroup :TextureGroupMold = _lib.bestTextureGroupForScaleFactor(_scaleFactor); if (textureGroup != null) { for each (var atlas :AtlasMold in textureGroup.atlases) { loadAtlas(loader, atlas); } } _pngLoaders.shutdown(); } protected function loadAtlas (loader :ImageLoader, atlas :AtlasMold) :void { const bytes :* = _atlasBytes[atlas.file]; if (bytes === undefined) { throw new Error("Expected an atlas '" + atlas.file + "', but it wasn't in the zip"); } var scale :Number = atlas.scaleFactor; if (_lib.textureFormat == "atf") { baseTextureLoaded(Texture.fromAtfData(bytes, scale), atlas); } else { const atlasFuture :Future = loader.loadFromBytes(bytes, _pngLoaders); atlasFuture.failed.add(onPngLoadingFailed); atlasFuture.succeeded.add(function (img :LoadedImage) :void { baseTextureLoaded(Texture.fromBitmapData( img.bitmapData, _generateMipMaps, false, // optimizeForRenderToTexture scale), atlas); if (!Starling.handleLostContext) { img.bitmapData.dispose(); } }); } } protected function baseTextureLoaded (baseTexture :Texture, atlas :AtlasMold) :void { _baseTextures.push(baseTexture); var scale :Number = atlas.scaleFactor; for each (var atlasTexture :AtlasTextureMold in atlas.textures) { var bounds :Rectangle = atlasTexture.bounds; var offset :Point = atlasTexture.origin; // Starling expects subtexture bounds to be unscaled if (scale != 1) { bounds = bounds.clone(); bounds.x /= scale; bounds.y /= scale; bounds.width /= scale; bounds.height /= scale; offset = offset.clone(); offset.x /= scale; offset.y /= scale; } _creators[atlasTexture.symbol] = new ImageCreator( Texture.fromTexture(baseTexture, bounds), offset, atlasTexture.symbol); } } protected function onPngLoadingComplete (..._) :void { for each (var movie :MovieMold in _lib.movies) { movie.fillLabels(); _creators[movie.id] = new MovieCreator(movie, _lib.frameRate); } _future.succeed(new LibraryImpl(_baseTextures, _creators)); } protected function onPngLoadingFailed (e :*) :void { if (_future.isComplete) return; _future.fail(e); _pngLoaders.shutdownNow(); } protected var _toLoad :Object; protected var _scaleFactor :Number; protected var _generateMipMaps :Boolean; protected var _future :FutureTask; protected var _versionChecked :Boolean; protected var _zip :FZip = new FZip(); protected var _lib :LibraryMold; protected const _baseTextures :Vector.<Texture> = new <Texture>[]; protected const _creators :Dictionary = new Dictionary();//<name, ImageCreator/MovieCreator> protected const _atlasBytes :Dictionary = new Dictionary();//<String name, ByteArray> protected const _pngLoaders :Executor = new Executor(1); protected static const PNG :String = ".png"; protected static const ATF :String = ".atf" } class ImageCreator implements SymbolCreator { public var texture :Texture; public var origin :Point; public var symbol :String; public function ImageCreator (texture :Texture, origin :Point, symbol :String) { this.texture = texture; this.origin = origin; this.symbol = symbol; } public function create (library :Library) :DisplayObject { const image :Image = new Image(texture); image.pivotX = origin.x; image.pivotY = origin.y; image.name = symbol; return image; } } class MovieCreator implements SymbolCreator { public var mold :MovieMold; public var frameRate :Number; public function MovieCreator (mold :MovieMold, frameRate :Number) { this.mold = mold; this.frameRate = frameRate; } public function create (library :Library) :DisplayObject { return new Movie(mold, frameRate, library); } }
// // Flump - Copyright 2013 Flump Authors package flump.display { import flash.utils.ByteArray; import flump.executor.Executor; import flump.executor.Future; /** * Loads zip files created by the flump exporter and parses them into Library instances. */ public class LibraryLoader { /** * Loads a Library from the zip in the given bytes. * * @deprecated Use a new LibraryLoader with the builder pattern instead. * * @param bytes The bytes containing the zip * * @param executor The executor on which the loading should run. If not specified, it'll run on * a new single-use executor. * * @param scaleFactor the desired scale factor of the textures to load. If the Library contains * textures with multiple scale factors, loader will load the textures with the scale factor * closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be * used. * * @return a Future to use to track the success or failure of loading the resources out of the * bytes. If the loading succeeds, the Future's onSuccess will fire with an instance of * Library. If it fails, the Future's onFail will fire with the Error that caused the * loading failure. */ public static function loadBytes (bytes :ByteArray, executor :Executor=null, scaleFactor :Number=-1) :Future { return new LibraryLoader().setExecutor(executor).setScaleFactor(scaleFactor) .loadBytes(bytes); } /** * Loads a Library from the zip at the given url. * * @deprecated Use a new LibraryLoader with the builder pattern instead. * * @param url The url where the zip can be found * * @param executor The executor on which the loading should run. If not specified, it'll run on * a new single-use executor. * * @param scaleFactor the desired scale factor of the textures to load. If the Library contains * textures with multiple scale factors, loader will load the textures with the scale factor * closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be * used. * * @return a Future to use to track the success or failure of loading the resources from the * url. If the loading succeeds, the Future's onSuccess will fire with an instance of * Library. If it fails, the Future's onFail will fire with the Error that caused the * loading failure. */ public static function loadURL (url :String, executor :Executor=null, scaleFactor :Number=-1) :Future { return new LibraryLoader().setExecutor(executor).setScaleFactor(scaleFactor) .loadURL(url); } /** * Sets the executor instance to use with this loader. * * @param executor The executor on which the loading should run. If left null (the default), * it'll run on a new single-use executor. */ public function setExecutor (executor :Executor) :LibraryLoader { _executor = executor; return this; } /** * Sets the scale factor value to use with this loader. * * @param scaleFactor the desired scale factor of the textures to load. If the Library contains * textures with multiple scale factors, loader will load the textures with the scale factor * closest to this value. If scaleFactor <= 0 (the default), Starling.contentScaleFactor will be * used. */ public function setScaleFactor (scaleFactor :Number) :LibraryLoader { _scaleFactor = scaleFactor; return this; } /** * Sets the mip map generation for this loader. * * @param generateMipMaps If true (defaults to false), flump will instruct Starling to generate * mip maps for all loaded textures. Scaling will look better if mipmaps are enabled, but there * is a loading time and memory usage penalty. */ public function setGenerateMipMaps (generateMipMaps :Boolean) :LibraryLoader { _generateMipMaps = generateMipMaps; return this; } /** * Loads a Library from the zip in the given bytes, using the settings configured in this * loader. * * @param bytes The bytes containing the zip */ public function loadBytes (bytes :ByteArray) :Future { return (_executor || new Executor(1)).submit( new Loader(bytes, _scaleFactor, _generateMipMaps).load); } /** * Loads a Library from the zip at the given url, using the settings configured in this * loader. * * @param url The url where the zip can be found */ public function loadURL (url :String) :Future { return (_executor || new Executor(1)).submit( new Loader(url, _scaleFactor, _generateMipMaps).load); } /** @private */ public static const LIBRARY_LOCATION :String = "library.json"; /** @private */ public static const MD5_LOCATION :String = "md5"; /** @private */ public static const VERSION_LOCATION :String = "version"; /** * @private * The version produced and parsable by this version of the code. The version in a resources * zip must equal the version compiled into the parsing code for parsing to succeed. */ public static const VERSION :String = "2"; protected var _executor :Executor; protected var _scaleFactor :Number = -1; protected var _generateMipMaps :Boolean = false; } } import deng.fzip.FZip; import deng.fzip.FZipErrorEvent; import deng.fzip.FZipEvent; import deng.fzip.FZipFile; import flash.events.Event; import flash.events.IOErrorEvent; import flash.geom.Point; import flash.geom.Rectangle; import flash.net.URLRequest; import flash.utils.ByteArray; import flash.utils.Dictionary; import flump.display.Library; import flump.display.LibraryLoader; import flump.display.Movie; import flump.executor.Executor; import flump.executor.Future; import flump.executor.FutureTask; import flump.executor.load.ImageLoader; import flump.executor.load.LoadedImage; import flump.mold.AtlasMold; import flump.mold.AtlasTextureMold; import flump.mold.LibraryMold; import flump.mold.MovieMold; import flump.mold.TextureGroupMold; import starling.core.Starling; import starling.display.DisplayObject; import starling.display.Image; import starling.textures.Texture; interface SymbolCreator { function create (library :Library) :DisplayObject; } class LibraryImpl implements Library { public function LibraryImpl (baseTextures :Vector.<Texture>, creators :Dictionary) { _baseTextures = baseTextures; _creators = creators; } public function createMovie (symbol :String) :Movie { return Movie(createDisplayObject(symbol)); } public function createImage (symbol :String) :Image { const disp :DisplayObject = createDisplayObject(symbol); if (disp is Movie) throw new Error(symbol + " is not an Image"); return Image(disp); } public function getImageTexture (symbol :String) :Texture { checkNotDisposed(); var creator :SymbolCreator = requireSymbolCreator(symbol); if (!(creator is ImageCreator)) throw new Error(symbol + " is not an Image"); return ImageCreator(creator).texture; } public function get movieSymbols () :Vector.<String> { checkNotDisposed(); const names :Vector.<String> = new <String>[]; for (var creatorName :String in _creators) { if (_creators[creatorName] is MovieCreator) names.push(creatorName); } return names; } public function get imageSymbols () :Vector.<String> { checkNotDisposed(); const names :Vector.<String> = new <String>[]; for (var creatorName :String in _creators) { if (_creators[creatorName] is ImageCreator) names.push(creatorName); } return names; } public function createDisplayObject (name :String) :DisplayObject { checkNotDisposed(); return requireSymbolCreator(name).create(this); } public function dispose () :void { checkNotDisposed(); for each (var tex :Texture in _baseTextures) { tex.dispose(); } _baseTextures = null; _creators = null; } protected function requireSymbolCreator (name :String) :SymbolCreator { var creator :SymbolCreator = _creators[name]; if (creator == null) throw new Error("No such id '" + name + "'"); return creator; } protected function checkNotDisposed () :void { if (_baseTextures == null) { throw new Error("This Library has been disposed"); } } protected var _creators :Dictionary; protected var _baseTextures :Vector.<Texture>; } class Loader { public function Loader (toLoad :Object, scaleFactor :Number, generateMipMaps :Boolean) { _scaleFactor = (scaleFactor > 0 ? scaleFactor : Starling.contentScaleFactor); _generateMipMaps = generateMipMaps; _toLoad = toLoad; } public function load (future :FutureTask) :void { _future = future; _zip.addEventListener(Event.COMPLETE, _future.monitoredCallback(onZipLoadingComplete)); _zip.addEventListener(IOErrorEvent.IO_ERROR, _future.fail); _zip.addEventListener(FZipErrorEvent.PARSE_ERROR, _future.fail); _zip.addEventListener(FZipEvent.FILE_LOADED, _future.monitoredCallback(onFileLoaded)); if (_toLoad is String) _zip.load(new URLRequest(String(_toLoad))); else _zip.loadBytes(ByteArray(_toLoad)); } protected function onFileLoaded (e :FZipEvent) :void { const loaded :FZipFile = _zip.removeFileAt(_zip.getFileCount() - 1); const name :String = loaded.filename; if (name == LibraryLoader.LIBRARY_LOCATION) { const jsonString :String = loaded.content.readUTFBytes(loaded.content.length); _lib = LibraryMold.fromJSON(JSON.parse(jsonString)); } else if (name.indexOf(PNG, name.length - PNG.length) != -1) { _atlasBytes[name] = loaded.content; } else if (name.indexOf(ATF, name.length - ATF.length) != -1) { _atlasBytes[name] = loaded.content; } else if (name == LibraryLoader.VERSION_LOCATION) { const zipVersion :String = loaded.content.readUTFBytes(loaded.content.length) if (zipVersion != LibraryLoader.VERSION) { throw new Error("Zip is version " + zipVersion + " but the code needs " + LibraryLoader.VERSION); } _versionChecked = true; } else if (name == LibraryLoader.MD5_LOCATION ) { // Nothing to verify } else {} // ignore unknown files } protected function onZipLoadingComplete (..._) :void { _zip = null; if (_lib == null) throw new Error(LibraryLoader.LIBRARY_LOCATION + " missing from zip"); if (!_versionChecked) throw new Error(LibraryLoader.VERSION_LOCATION + " missing from zip"); const loader :ImageLoader = _lib.textureFormat == "atf" ? null : new ImageLoader(); _pngLoaders.terminated.add(_future.monitoredCallback(onPngLoadingComplete)); // Determine the scale factor we want to use var textureGroup :TextureGroupMold = _lib.bestTextureGroupForScaleFactor(_scaleFactor); if (textureGroup != null) { for each (var atlas :AtlasMold in textureGroup.atlases) { loadAtlas(loader, atlas); } } _pngLoaders.shutdown(); } protected function loadAtlas (loader :ImageLoader, atlas :AtlasMold) :void { const bytes :* = _atlasBytes[atlas.file]; if (bytes === undefined) { throw new Error("Expected an atlas '" + atlas.file + "', but it wasn't in the zip"); } var scale :Number = atlas.scaleFactor; if (_lib.textureFormat == "atf") { baseTextureLoaded(Texture.fromAtfData(bytes, scale), atlas); } else { const atlasFuture :Future = loader.loadFromBytes(bytes, _pngLoaders); atlasFuture.failed.add(onPngLoadingFailed); atlasFuture.succeeded.add(function (img :LoadedImage) :void { baseTextureLoaded(Texture.fromBitmapData( img.bitmapData, _generateMipMaps, false, // optimizeForRenderToTexture scale), atlas); if (!Starling.handleLostContext) { img.bitmapData.dispose(); } }); } } protected function baseTextureLoaded (baseTexture :Texture, atlas :AtlasMold) :void { _baseTextures.push(baseTexture); var scale :Number = atlas.scaleFactor; for each (var atlasTexture :AtlasTextureMold in atlas.textures) { var bounds :Rectangle = atlasTexture.bounds; var offset :Point = atlasTexture.origin; // Starling expects subtexture bounds to be unscaled if (scale != 1) { bounds = bounds.clone(); bounds.x /= scale; bounds.y /= scale; bounds.width /= scale; bounds.height /= scale; offset = offset.clone(); offset.x /= scale; offset.y /= scale; } _creators[atlasTexture.symbol] = new ImageCreator( Texture.fromTexture(baseTexture, bounds), offset, atlasTexture.symbol); } } protected function onPngLoadingComplete (..._) :void { for each (var movie :MovieMold in _lib.movies) { movie.fillLabels(); _creators[movie.id] = new MovieCreator(movie, _lib.frameRate); } _future.succeed(new LibraryImpl(_baseTextures, _creators)); } protected function onPngLoadingFailed (e :*) :void { if (_future.isComplete) return; _future.fail(e); _pngLoaders.shutdownNow(); } protected var _toLoad :Object; protected var _scaleFactor :Number; protected var _generateMipMaps :Boolean; protected var _future :FutureTask; protected var _versionChecked :Boolean; protected var _zip :FZip = new FZip(); protected var _lib :LibraryMold; protected const _baseTextures :Vector.<Texture> = new <Texture>[]; protected const _creators :Dictionary = new Dictionary();//<name, ImageCreator/MovieCreator> protected const _atlasBytes :Dictionary = new Dictionary();//<String name, ByteArray> protected const _pngLoaders :Executor = new Executor(1); protected static const PNG :String = ".png"; protected static const ATF :String = ".atf" } class ImageCreator implements SymbolCreator { public var texture :Texture; public var origin :Point; public var symbol :String; public function ImageCreator (texture :Texture, origin :Point, symbol :String) { this.texture = texture; this.origin = origin; this.symbol = symbol; } public function create (library :Library) :DisplayObject { const image :Image = new Image(texture); image.pivotX = origin.x; image.pivotY = origin.y; image.name = symbol; return image; } } class MovieCreator implements SymbolCreator { public var mold :MovieMold; public var frameRate :Number; public function MovieCreator (mold :MovieMold, frameRate :Number) { this.mold = mold; this.frameRate = frameRate; } public function create (library :Library) :DisplayObject { return new Movie(mold, frameRate, library); } }
Move LibraryLoader to a builder pattern.
Move LibraryLoader to a builder pattern. I made the old static methods deprecated and removed the new generateMipMaps parameter from them. Presumably if anybody other than me is already using it, they're paying enough attention to adapt to this change too.
ActionScript
mit
funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump
51a40c5f4fccb78917fd00a30d3b6d7295d15fae
src/as/com/threerings/crowd/client/PlaceViewUtil.as
src/as/com/threerings/crowd/client/PlaceViewUtil.as
// // $Id: PlaceViewUtil.java 3098 2004-08-27 02:12:55Z mdb $ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 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.crowd.client { import flash.display.DisplayObjectContainer; import com.threerings.crowd.data.PlaceObject; /** * Provides a mechanism for dispatching notifications to all user * interface elements in a hierarchy that implement the {@link PlaceView} * interface. Look at the documentation for {@link PlaceView} for more * explanation. */ public class PlaceViewUtil { /** * Dispatches a call to {@link PlaceView#willEnterPlace} to all UI * elements in the hierarchy rooted at the component provided via the * <code>root</code> parameter. * * @param root the component at which to start traversing the UI * hierarchy. * @param plobj the place object that is about to be entered. */ public static function dispatchWillEnterPlace ( root :Object, plobj :PlaceObject) :void { dispatch(root, plobj, "willEnterPlace"); } /** * Dispatches a call to {@link PlaceView#didLeavePlace} to all UI * elements in the hierarchy rooted at the component provided via the * <code>root</code> parameter. * * @param root the component at which to start traversing the UI * hierarchy. * @param plobj the place object that is about to be entered. */ public static function dispatchDidLeavePlace ( root :Object, plobj :PlaceObject) :void { dispatch(root, plobj, "didLeavePlace"); } private static function dispatch ( root :Object, plobj :PlaceObject, funct :String) :void { // dispatch the call on this component if it implements PlaceView if (root is PlaceView) { try { (root as PlaceView)[funct](plobj); } catch (e :Error) { var log :Log = Log.getLog(PlaceViewUtil); log.warning("Component choked on " + funct + "() " + "[component=" + root + ", plobj=" + plobj + "]."); log.logStackTrace(e); } } // now traverse all of this component's children if (root is DisplayObjectContainer) { var cont :DisplayObjectContainer = (root as DisplayObjectContainer); for (var ii :int = 0; ii < cont.numChildren; ii++) { dispatch(cont.getChildAt(ii), plobj, funct); } } } } }
// // $Id: PlaceViewUtil.java 3098 2004-08-27 02:12:55Z mdb $ // // Narya library - tools for developing networked games // Copyright (C) 2002-2004 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.crowd.client { import flash.display.DisplayObject; import mx.utils.DisplayUtil; import com.threerings.crowd.data.PlaceObject; /** * Provides a mechanism for dispatching notifications to all user * interface elements in a hierarchy that implement the {@link PlaceView} * interface. Look at the documentation for {@link PlaceView} for more * explanation. */ public class PlaceViewUtil { /** * Dispatches a call to {@link PlaceView#willEnterPlace} to all UI * elements in the hierarchy rooted at the component provided via the * <code>root</code> parameter. * * @param root the component at which to start traversing the UI * hierarchy. * @param plobj the place object that is about to be entered. */ public static function dispatchWillEnterPlace ( root :Object, plobj :PlaceObject) :void { dispatch(root, plobj, "willEnterPlace"); } /** * Dispatches a call to {@link PlaceView#didLeavePlace} to all UI * elements in the hierarchy rooted at the component provided via the * <code>root</code> parameter. * * @param root the component at which to start traversing the UI * hierarchy. * @param plobj the place object that is about to be entered. */ public static function dispatchDidLeavePlace ( root :Object, plobj :PlaceObject) :void { dispatch(root, plobj, "didLeavePlace"); } private static function dispatch ( root :Object, plobj :PlaceObject, funct :String) :void { if (!(root is DisplayObject)) { return; } DisplayUtil.walkDisplayObjects(root as DisplayObject, function (disp :DisplayObject) :void { if (disp is PlaceView) { try { (root as PlaceView)[funct](plobj); } catch (e :Error) { var log :Log = Log.getLog(PlaceViewUtil); log.warning("Component choked on " + funct + "() " + "[component=" + root + ", plobj=" + plobj + "]."); log.logStackTrace(e); } } }); } } }
Use mx.utils.DisplayUtil.
Use mx.utils.DisplayUtil. git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4320 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
71e0ced8a1fdc84e5d504c91db06f2769e1fa12b
WeaveJS/src/weavejs/core/EventCallbackCollection.as
WeaveJS/src/weavejs/core/EventCallbackCollection.as
/* ***** BEGIN LICENSE BLOCK ***** * * This file is part of Weave. * * The Initial Developer of Weave is the Institute for Visualization * and Perception Research at the University of Massachusetts Lowell. * Portions created by the Initial Developer are Copyright (C) 2008-2015 * the Initial Developer. All Rights Reserved. * * 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/. * * ***** END LICENSE BLOCK ***** */ package weavejs.core { public class EventCallbackCollection/*/<T>/*/ extends CallbackCollection { public function EventCallbackCollection(stopPropagation:/*/(event:T)=>void/*/Function = null) { // specify the preCallback function in super() so data will be set before each callback. super(_setEvent); this._stopPropagation = stopPropagation; } // This variable is set before each callback runs private var _event:Object = null; private var _stopPropagation:Function = null; private function _setEvent(event:Object = null):void { _event = event; } /** * This is the event object. */ public function get event():/*/T/*/Object { return _event; } /** * This function will run callbacks immediately, setting the event variable before each one. * @param event */ public function dispatch(event:/*/T/*/Object):void { // remember previous value so it can be restored in case external code caused us to interrupt something else var prevEvent:Object = _event; _runCallbacksImmediately(event); _setEvent(prevEvent); } /** * calls the stopPropagation function which was passed to the constructor. */ public function stopPropagation():void { if (_stopPropagation != null) _stopPropagation(event); } } }
/* ***** BEGIN LICENSE BLOCK ***** * * This file is part of Weave. * * The Initial Developer of Weave is the Institute for Visualization * and Perception Research at the University of Massachusetts Lowell. * Portions created by the Initial Developer are Copyright (C) 2008-2015 * the Initial Developer. All Rights Reserved. * * 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/. * * ***** END LICENSE BLOCK ***** */ package weavejs.core { public class EventCallbackCollection/*/<T>/*/ extends CallbackCollection { public function EventCallbackCollection() { // specify the preCallback function in super() so data will be set before each callback. super(_setEvent); } // This variable is set before each callback runs private var _event:Object = null; private function _setEvent(event:Object = null):void { _event = event; } /** * This is the event object. */ public function get event():/*/T/*/Object { return _event; } /** * This function will run callbacks immediately, setting the event variable before each one. * @param event */ public function dispatch(event:/*/T/*/Object):void { // remember previous value so it can be restored in case external code caused us to interrupt something else var prevEvent:Object = _event; _runCallbacksImmediately(event); _setEvent(prevEvent); } } }
Revert "added stopPropagation function to EventCallbackCollection"
Revert "added stopPropagation function to EventCallbackCollection" This reverts commit eec7fe6aa043f6ab507a870b98a1936a1b5a60bc.
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
e5c29c15df6e289f41d4d0a5b080c3856c1282f3
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:Protocols; private var _screenWidth:Number; private var _screenHeight:Number; private var _screenColorDepth:String; private var _userAgent:UserAgent; 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:Protocols = null, screenWidth:Number = NaN, screenHeight:Number = NaN, screenColorDepth:String = "", userAgent:UserAgent = 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():Protocols { 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():UserAgent { return _userAgent; } public override function set userAgent( custom:UserAgent ):void { _userAgent = custom; } public override function isInHTML():Boolean { return _isInHTML; } public override function isAIR():Boolean { return _isAIR; } } }
 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:Protocols; 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:Protocols = 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():Protocols { 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; } } }
update Fake class signature to last change to Environment class
update Fake class signature to last change to Environment class
ActionScript
apache-2.0
nsdevaraj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash,minimedj/gaforflash
9cd6b0b75c2bde7670390ea40245c5eed9889b66
src/aerys/minko/type/parser/ParserOptions.as
src/aerys/minko/type/parser/ParserOptions.as
package aerys.minko.type.parser { public final class ParserOptions { private var _loadTextures : Boolean = true; private var _textureFilenameFunction : Function = null; private var _textureFunction : Function = null; // private var _sceneFunction : Function = null; private var _loadMeshes : Boolean = true; private var _mergeMeshes : Boolean = false; private var _loadSkins : Boolean = true; public function get loadTextures() : Boolean { return _loadTextures; } public function get textureFilenameFunction() : Function { return _textureFilenameFunction; } public function get textureFunction() : Function { return _textureFunction; } // public function get sceneFunction() : Function { return _sceneFunction; } public function get loadMeshes() : Boolean { return _loadMeshes; } public function get mergeMeshes() : Boolean { return _mergeMeshes; } public function get loadSkins() : Boolean { return _loadSkins; } public function set loadTextures(value : Boolean) : void { _loadTextures = value; } public function set textureFilenameFunction(value : Function) : void { _textureFilenameFunction = value; } public function set textureFunction(value : Function) : void { _textureFunction = value; } /*public function set sceneFunction(value : Function) : void { _sceneFunction = value; }*/ public function set loadMeshes(value : Boolean) : void { _loadMeshes = value; } public function set mergeMeshes(value : Boolean) : void { _mergeMeshes = value; } public function set loadSkins(value : Boolean) : void { _loadSkins = value; } } }
package aerys.minko.type.parser { public final class ParserOptions { private var _loadTextures : Boolean = true; private var _textureFilenameFunction : Function = null; private var _textureFunction : Function = null; private var _meshFunction : Function = null; private var _loadMeshes : Boolean = true; private var _mergeMeshes : Boolean = false; private var _loadSkins : Boolean = true; public function get loadTextures() : Boolean { return _loadTextures; } public function get textureFilenameFunction() : Function { return _textureFilenameFunction; } public function get textureFunction() : Function { return _textureFunction; } public function get loadMeshes() : Boolean { return _loadMeshes; } public function get meshFunction() : Function { return _meshFunction; } public function get mergeMeshes() : Boolean { return _mergeMeshes; } public function get loadSkins() : Boolean { return _loadSkins; } public function set loadTextures(value : Boolean) : void { _loadTextures = value; } public function set textureFilenameFunction(value : Function) : void { _textureFilenameFunction = value; } public function set textureFunction(value : Function) : void { _textureFunction = value; } public function set meshFunction(value : Function) : void { _meshFunction = value; } public function set loadMeshes(value : Boolean) : void { _loadMeshes = value; } public function set mergeMeshes(value : Boolean) : void { _mergeMeshes = value; } public function set loadSkins(value : Boolean) : void { _loadSkins = value; } } }
Add meshFunction that enable mesh modifications while loading it.
Add meshFunction that enable mesh modifications while loading it.
ActionScript
mit
aerys/minko-as3
4796e0dbb67dca95c6c942c92e4b90a83dba6a18
src/aerys/minko/type/binding/DataBindings.as
src/aerys/minko/type/binding/DataBindings.as
package aerys.minko.type.binding { import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.Signal; import aerys.minko.type.enum.DataProviderUsage; import flash.utils.Dictionary; public final class DataBindings { private var _owner : ISceneNode; private var _providers : Vector.<IDataProvider>; private var _bindingNames : Vector.<String>; private var _bindingNameToValue : Object; private var _bindingNameToChangedSignal : Object; private var _bindingNameToProvider : Object; private var _providerToBindingNames : Dictionary; private var _consumers : Vector.<IDataBindingsConsumer>; public function get owner() : ISceneNode { return _owner; } public function get numProviders() : uint { return _providers.length; } public function get numProperties() : uint { return _bindingNames.length; } public function DataBindings(owner : ISceneNode) { _owner = owner; _providers = new <IDataProvider>[]; _bindingNames = new <String>[]; _bindingNameToValue = {}; _bindingNameToChangedSignal = {}; _bindingNameToProvider = {}; _providerToBindingNames = new Dictionary(true); _consumers = new <IDataBindingsConsumer>[]; } public function contains(dataProvider : IDataProvider) : Boolean { return _providers.indexOf(dataProvider) != -1; } public function addProvider(provider : IDataProvider) : void { if (_providerToBindingNames[provider]) throw new Error('This provider is already bound.'); var dataDescriptor : Object = provider.dataDescriptor; provider.propertyChanged.add(propertyChangedHandler); if (provider is IDynamicDataProvider) { var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider; dynamicProvider.propertyAdded.add(addBinding); dynamicProvider.propertyRemoved.add(removeBinding); } _providerToBindingNames[provider] = new <String>[]; _providers.push(provider); for (var propertyName : String in dataDescriptor) addBinding( provider, propertyName, dataDescriptor[propertyName], provider[propertyName] ); } private function addBinding(provider : IDataProvider, propertyName : String, bindingName : String, value : Object) : void { var providerBindingNames : Vector.<String> = _providerToBindingNames[provider]; if (_bindingNames.indexOf(bindingName) != -1) throw new Error( 'Another data provider is already declaring the \'' + bindingName + '\' property.' ); _bindingNameToProvider[bindingName] = provider; _bindingNameToValue[bindingName] = value; providerBindingNames.push(bindingName); _bindingNames.push(bindingName); if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, null, value); } public function removeProvider(provider : IDataProvider) : void { var providerBindingsNames : Vector.<String> = _providerToBindingNames[provider]; if (providerBindingsNames == null) throw new ArgumentError('Unknown provider.'); var numProviders : uint = _providers.length - 1; provider.propertyChanged.remove(propertyChangedHandler); if (provider is IDynamicDataProvider) { var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider; dynamicProvider.propertyAdded.remove(addBinding); dynamicProvider.propertyRemoved.remove(removeBinding); } _providers[_providers.indexOf(provider)] = _providers[numProviders]; _providers.length = numProviders; delete _providerToBindingNames[provider]; var dataDescriptor : Object = provider.dataDescriptor; for (var propertyName : String in dataDescriptor) removeBinding( provider, propertyName, dataDescriptor[propertyName], provider[propertyName] ); } public function removeBinding(provider : IDataProvider, propertyName : String, bindingName : String, value : Object) : void { var numBindings : uint = _bindingNames.length - 1; var changedSignal : Signal = _bindingNameToChangedSignal[bindingName] as Signal; delete _bindingNameToValue[bindingName]; delete _bindingNameToProvider[bindingName]; _bindingNames[_bindingNames.indexOf(bindingName)] = _bindingNames[numBindings]; _bindingNames.length = numBindings; if (changedSignal != null) changedSignal.execute(this, bindingName, value, null); } public function removeAllProviders() : void { var numProviders : uint = this.numProviders; for (var providerId : int = numProviders - 1; providerId >= 0; --providerId) removeProvider(getProviderAt(providerId)); } public function hasCallback(bindingName : String, callback : Function) : Boolean { var signal : Signal = _bindingNameToChangedSignal[bindingName]; return signal != null && signal.hasCallback(callback); } public function addCallback(bindingName : String, callback : Function) : void { _bindingNameToChangedSignal[bindingName] ||= new Signal( 'DataBindings.changed[' + bindingName + ']' ); Signal(_bindingNameToChangedSignal[bindingName]).add(callback); } public function removeCallback(bindingName : String, callback : Function) : void { var signal : Signal = _bindingNameToChangedSignal[bindingName]; if (!signal) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); signal.remove(callback); if (signal.numCallbacks == 0) delete _bindingNameToChangedSignal[bindingName]; } public function getProviderAt(index : uint) : IDataProvider { return _providers[index]; } public function getProviderByBindingName(bindingName : String) : IDataProvider { if (_bindingNameToProvider[bindingName] == null) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); return _bindingNameToProvider[bindingName]; } public function propertyExists(bindingName : String) : Boolean { return _bindingNameToValue.hasOwnProperty(bindingName); } public function getProperty(bindingName : String) : * { if (_bindingNames.indexOf(bindingName) < 0) throw new Error('The property \'' + bindingName + '\' does not exist.'); return _bindingNameToValue[bindingName]; } public function getPropertyName(bindingIndex : uint) : String { if (bindingIndex > numProperties) throw new ArgumentError('No such binding'); return _bindingNames[bindingIndex]; } public function copySharedProvidersFrom(source : DataBindings) : void { var numProviders : uint = source._providers.length; for (var providerId : uint = 0; providerId < numProviders; ++providerId) { var provider : IDataProvider = source._providers[providerId]; if (provider.usage == DataProviderUsage.SHARED) addProvider(provider); } } private function propertyChangedHandler(source : IDataProvider, propertyName : String, bindingName : String, value : Object) : void { if (propertyName == null) throw new Error('DataProviders must change only one property at a time.'); var oldValue : Object = _bindingNameToValue[bindingName]; _bindingNameToValue[bindingName] = value; var numConsumers : uint = _consumers.length; for (var consumerId : uint = 0; consumerId < numConsumers; ++consumerId) _consumers[consumerId].setProperty(bindingName, value); if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute( this, bindingName, oldValue, value ); } public function addConsumer(consumer : IDataBindingsConsumer) : void { _consumers.push(consumer); var numProperties : uint = this.numProperties; for (var propertyId : uint = 0; propertyId < numProperties; ++propertyId) { var bindingName : String = _bindingNames[propertyId]; consumer.setProperty(bindingName, _bindingNameToValue[bindingName]); } } public function removeConsumer(consumer : IDataBindingsConsumer) : void { var numConsumers : uint = _consumers.length - 1; var index : int = _consumers.indexOf(consumer); if (index < 0) throw new Error('This consumer does not exist.'); _consumers[index] = _consumers[numConsumers]; _consumers.length = numConsumers; } } }
package aerys.minko.type.binding { import aerys.minko.scene.node.ISceneNode; import aerys.minko.type.Signal; import aerys.minko.type.enum.DataProviderUsage; import flash.utils.Dictionary; public final class DataBindings { private var _owner : ISceneNode; private var _providers : Vector.<IDataProvider>; private var _bindingNames : Vector.<String>; private var _bindingNameToValue : Object; private var _bindingNameToChangedSignal : Object; private var _bindingNameToProvider : Object; private var _providerToBindingNames : Dictionary; private var _consumers : Vector.<IDataBindingsConsumer>; public function get owner() : ISceneNode { return _owner; } public function get numProviders() : uint { return _providers.length; } public function get numProperties() : uint { return _bindingNames.length; } public function DataBindings(owner : ISceneNode) { _owner = owner; _providers = new <IDataProvider>[]; _bindingNames = new <String>[]; _bindingNameToValue = {}; _bindingNameToChangedSignal = {}; _bindingNameToProvider = {}; _providerToBindingNames = new Dictionary(true); _consumers = new <IDataBindingsConsumer>[]; } public function contains(dataProvider : IDataProvider) : Boolean { return _providers.indexOf(dataProvider) != -1; } public function addProvider(provider : IDataProvider) : void { if (_providerToBindingNames[provider]) throw new Error('This provider is already bound.'); var dataDescriptor : Object = provider.dataDescriptor; provider.propertyChanged.add(propertyChangedHandler); if (provider is IDynamicDataProvider) { var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider; dynamicProvider.propertyAdded.add(addBinding); dynamicProvider.propertyRemoved.add(removeBinding); } _providerToBindingNames[provider] = new <String>[]; _providers.push(provider); for (var propertyName : String in dataDescriptor) addBinding( provider, propertyName, dataDescriptor[propertyName], provider[propertyName] ); } private function addBinding(provider : IDataProvider, propertyName : String, bindingName : String, value : Object) : void { var providerBindingNames : Vector.<String> = _providerToBindingNames[provider]; if (_bindingNames.indexOf(bindingName) != -1) throw new Error( 'Another data provider is already declaring the \'' + bindingName + '\' property.' ); _bindingNameToProvider[bindingName] = provider; _bindingNameToValue[bindingName] = value; providerBindingNames.push(bindingName); _bindingNames.push(bindingName); var numConsumers : uint = _consumers.length; for (var consumerId : uint = 0; consumerId < numConsumers; ++consumerId) _consumers[consumerId].setProperty(bindingName, value); if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute(this, bindingName, null, value); } public function removeProvider(provider : IDataProvider) : void { var providerBindingsNames : Vector.<String> = _providerToBindingNames[provider]; if (providerBindingsNames == null) throw new ArgumentError('Unknown provider.'); var numProviders : uint = _providers.length - 1; provider.propertyChanged.remove(propertyChangedHandler); if (provider is IDynamicDataProvider) { var dynamicProvider : IDynamicDataProvider = provider as IDynamicDataProvider; dynamicProvider.propertyAdded.remove(addBinding); dynamicProvider.propertyRemoved.remove(removeBinding); } _providers[_providers.indexOf(provider)] = _providers[numProviders]; _providers.length = numProviders; delete _providerToBindingNames[provider]; var dataDescriptor : Object = provider.dataDescriptor; for (var propertyName : String in dataDescriptor) removeBinding( provider, propertyName, dataDescriptor[propertyName], provider[propertyName] ); } public function removeBinding(provider : IDataProvider, propertyName : String, bindingName : String, value : Object) : void { var numBindings : uint = _bindingNames.length - 1; var changedSignal : Signal = _bindingNameToChangedSignal[bindingName] as Signal; delete _bindingNameToValue[bindingName]; delete _bindingNameToProvider[bindingName]; _bindingNames[_bindingNames.indexOf(bindingName)] = _bindingNames[numBindings]; _bindingNames.length = numBindings; var numConsumers : uint = _consumers.length; for (var consumerId : uint = 0; consumerId < numConsumers; ++consumerId) _consumers[consumerId].setProperty(bindingName, null); if (changedSignal != null) changedSignal.execute(this, bindingName, value, null); } public function removeAllProviders() : void { var numProviders : uint = this.numProviders; for (var providerId : int = numProviders - 1; providerId >= 0; --providerId) removeProvider(getProviderAt(providerId)); } public function hasCallback(bindingName : String, callback : Function) : Boolean { var signal : Signal = _bindingNameToChangedSignal[bindingName]; return signal != null && signal.hasCallback(callback); } public function addCallback(bindingName : String, callback : Function) : void { _bindingNameToChangedSignal[bindingName] ||= new Signal( 'DataBindings.changed[' + bindingName + ']' ); Signal(_bindingNameToChangedSignal[bindingName]).add(callback); } public function removeCallback(bindingName : String, callback : Function) : void { var signal : Signal = _bindingNameToChangedSignal[bindingName]; if (!signal) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); signal.remove(callback); if (signal.numCallbacks == 0) delete _bindingNameToChangedSignal[bindingName]; } public function getProviderAt(index : uint) : IDataProvider { return _providers[index]; } public function getProviderByBindingName(bindingName : String) : IDataProvider { if (_bindingNameToProvider[bindingName] == null) throw new ArgumentError('Unkown property \'' + bindingName + '\'.'); return _bindingNameToProvider[bindingName]; } public function propertyExists(bindingName : String) : Boolean { return _bindingNameToValue.hasOwnProperty(bindingName); } public function getProperty(bindingName : String) : * { if (_bindingNames.indexOf(bindingName) < 0) throw new Error('The property \'' + bindingName + '\' does not exist.'); return _bindingNameToValue[bindingName]; } public function getPropertyName(bindingIndex : uint) : String { if (bindingIndex > numProperties) throw new ArgumentError('No such binding'); return _bindingNames[bindingIndex]; } public function copySharedProvidersFrom(source : DataBindings) : void { var numProviders : uint = source._providers.length; for (var providerId : uint = 0; providerId < numProviders; ++providerId) { var provider : IDataProvider = source._providers[providerId]; if (provider.usage == DataProviderUsage.SHARED) addProvider(provider); } } private function propertyChangedHandler(source : IDataProvider, propertyName : String, bindingName : String, value : Object) : void { if (propertyName == null) throw new Error('DataProviders must change only one property at a time.'); var oldValue : Object = _bindingNameToValue[bindingName]; _bindingNameToValue[bindingName] = value; var numConsumers : uint = _consumers.length; for (var consumerId : uint = 0; consumerId < numConsumers; ++consumerId) _consumers[consumerId].setProperty(bindingName, value); if (_bindingNameToChangedSignal[bindingName]) _bindingNameToChangedSignal[bindingName].execute( this, bindingName, oldValue, value ); } public function addConsumer(consumer : IDataBindingsConsumer) : void { _consumers.push(consumer); var numProperties : uint = this.numProperties; for (var propertyId : uint = 0; propertyId < numProperties; ++propertyId) { var bindingName : String = _bindingNames[propertyId]; consumer.setProperty(bindingName, _bindingNameToValue[bindingName]); } } public function removeConsumer(consumer : IDataBindingsConsumer) : void { var numConsumers : uint = _consumers.length - 1; var index : int = _consumers.indexOf(consumer); if (index < 0) throw new Error('This consumer does not exist.'); _consumers[index] = _consumers[numConsumers]; _consumers.length = numConsumers; } } }
fix missing calls to IDataBindingsConsumer.setProperty() when a binding is added/removed
fix missing calls to IDataBindingsConsumer.setProperty() when a binding is added/removed
ActionScript
mit
aerys/minko-as3
9b71d8b219183a6d010ef35bcbfde1195cd2f1f9
src/aerys/minko/render/geometry/GeometrySanitizer.as
src/aerys/minko/render/geometry/GeometrySanitizer.as
package aerys.minko.render.geometry { import aerys.minko.render.shader.compiler.CRC32; import flash.utils.ByteArray; import flash.utils.Dictionary; import flash.utils.Endian; /** * The GeometrySanitizer static class provides methods to clean up * 3D geometry loaded from 3D asset files and make sure it is compliant * with the limitations of the Stage3D API. * * @author Romain Gilliotte * */ public final class GeometrySanitizer { public static const INDEX_LIMIT : uint = 524270; public static const VERTEX_LIMIT : uint = 65535; public static function isValid(indexData : ByteArray, vertexData : ByteArray, bytesPerVertex : uint = 12) : Boolean { var startPosition : uint = indexData.position; var numIndices : uint = indexData.bytesAvailable >> 2; var numVertices : uint = vertexData.bytesAvailable / bytesPerVertex; for (var indexId : uint = 0; indexId < numIndices; ++indexId) if (indexData.readShort() >= numVertices) break; indexData.position = startPosition; return indexId >= numIndices; } /** * Split vertex and index buffers too big the be rendered. * The index stream limit is 524270, the vertex stream limit is 65536. * * @param inVertexData * @param inIndexData * @param outVertexDatas * @param outIndexDatas * @param dwordsPerVertex */ public static function splitBuffers(inVertices : ByteArray, inIndices : ByteArray, outVertices : Vector.<ByteArray>, outIndices : Vector.<ByteArray>, bytesPerVertex : uint = 12) : void { var inVerticesStartPosition : uint = inVertices.position; var numVertices : uint = inVertices.bytesAvailable / bytesPerVertex; var inIndicesStartPosition : uint = inIndices.position; var numIndices : uint = inIndices.bytesAvailable >>> 1; if (numIndices < INDEX_LIMIT && numVertices < VERTEX_LIMIT) { outVertices.push(inVertices); outIndices.push(inIndices); return; } while (inIndices.bytesAvailable) { var indexDataLength : uint = inIndices.bytesAvailable >> 1; // new buffers var partialVertexData : ByteArray = new ByteArray(); var partialIndexData : ByteArray = new ByteArray(); // local variables var oldVertexIds : Vector.<int> = new Vector.<uint>(3, true); var newVertexIds : Vector.<int> = new Vector.<uint>(3, true); var newVertexNeeded : Vector.<Boolean> = new Vector.<Boolean>(3, true); var usedVerticesDic : Dictionary = new Dictionary(); // this dictionary maps old and new indices var usedVerticesCount : uint = 0; // this counts elements in the dictionary var usedIndicesCount : uint = 0; // how many indices have we used? var neededVerticesCount : uint; // iterators & limits var localVertexId : uint; partialVertexData.endian = Endian.LITTLE_ENDIAN; partialIndexData.endian = Endian.LITTLE_ENDIAN; while (usedIndicesCount < indexDataLength) { // check if next triangle fits into the index buffer var remainingIndices : uint = INDEX_LIMIT - usedIndicesCount; if (remainingIndices < 3) break ; // check if next triangle fits into the vertex buffer var remainingVertices : uint = VERTEX_LIMIT - usedVerticesCount; neededVerticesCount = 0; for (localVertexId = 0; localVertexId < 3; ++localVertexId) { inIndices.position = (usedIndicesCount + localVertexId) << 2; oldVertexIds[localVertexId] = inIndices.readShort(); var tmp : Object = usedVerticesDic[oldVertexIds[localVertexId]]; newVertexNeeded[localVertexId] = tmp == null; newVertexIds[localVertexId] = uint(tmp); if (newVertexNeeded[localVertexId]) ++neededVerticesCount; } if (remainingVertices < neededVerticesCount) break ; // it fills, let insert the triangle for (localVertexId = 0; localVertexId < 3; ++localVertexId) { if (newVertexNeeded[localVertexId]) { // copy current vertex into the new array partialVertexData.writeBytes( inVertices, oldVertexIds[localVertexId] * bytesPerVertex, bytesPerVertex ); // updates the id the temporary variable, to allow use filling partial index data later newVertexIds[localVertexId] = usedVerticesCount; // put its previous id in the dictionary usedVerticesDic[oldVertexIds[localVertexId]] = usedVerticesCount++; } partialIndexData.writeShort(newVertexIds[localVertexId]); } // ... increment indices counter usedIndicesCount += 3; } partialVertexData.position = 0; outVertices.push(partialVertexData); partialIndexData.position = 0; outIndices.push(partialIndexData); inVertices.position = inVerticesStartPosition; inIndices.position = inIndicesStartPosition; } } /** * Removes duplicated entries in a vertex buffer, and rewrite the index buffer according to it. * The buffers are modified in place. * * This method simplifies implementing parsers for file-formats that store per-vertex * and per-triangle information in different buffers, such as collada or OBJ: * merging them in a naive way and calling this method will do the job. * * @param vertexData * @param indexData * @param dwordsPerVertex */ public static function removeDuplicatedVertices(vertexData : ByteArray, indexData : ByteArray, bytesPerVertex : uint = 12) : void { var vertexDataStartPosition : uint = vertexData.position; var numVertices : uint = vertexData.bytesAvailable / bytesPerVertex; var indexDataStartPosition : uint = indexData.position; var numIndices : uint = indexData.bytesAvailable >>> 1; var hashToNewVertexId : Object = {}; var oldVertexIdToNewVertexId : Vector.<uint> = new Vector.<uint>(numVertices, true); var newVertexCount : uint = 0; var newLimit : uint = 0; for (var oldVertexId : uint = 0; oldVertexId < numVertices; ++oldVertexId) { vertexData.position = oldVertexId * bytesPerVertex; var numFloats : uint = bytesPerVertex >>> 2; var vertexHash : String = ''; while (numFloats) { vertexHash += vertexData.readFloat() + '|'; --numFloats; } var index : Object = hashToNewVertexId[vertexHash]; var newVertexId : uint = 0; if (index === null) { newVertexId = newVertexCount++; hashToNewVertexId[vertexHash] = newVertexId; newLimit = (1 + newVertexId) * bytesPerVertex; if (newVertexId != oldVertexId) { vertexData.position = newVertexId * bytesPerVertex; vertexData.writeBytes(vertexData, oldVertexId * bytesPerVertex, bytesPerVertex); } } else newVertexId = uint(index); oldVertexIdToNewVertexId[oldVertexId] = newVertexId; } vertexData.position = vertexDataStartPosition; vertexData.length = newLimit; for (var indexId : int = 0; indexId < numIndices; ++indexId) { index = indexData.readShort(); indexData.position -= 2; indexData.writeShort(oldVertexIdToNewVertexId[index]); } indexData.position = indexDataStartPosition; } /** * Removes unused entries in a vertex buffer, and rewrite the index buffer according to it. * The buffers are modified in place. * * @param vertexData * @param indexData * @param dwordsPerVertex */ public static function removeUnusedVertices(vertexData : ByteArray, indexData : ByteArray, bytesPerVertex : uint = 12) : void { var vertexDataStartPosition : uint = vertexData.position; var oldNumVertices : uint = vertexData.bytesAvailable / bytesPerVertex; var newNumVertices : uint = 0; var indexDataStartPosition : uint = indexData.position; var numIndices : uint = indexData.bytesAvailable >>> 1; // iterators var oldVertexId : uint; var indexId : uint; // flag unused vertices by scanning the index buffer var oldVertexIdToUsage : Vector.<Boolean> = new Vector.<Boolean>(oldNumVertices, true); for (indexId = 0; indexId < numIndices; ++indexId) oldVertexIdToUsage[indexData.readShort()] = true; // scan the flags, fix vertex buffer, and store old to new vertex id mapping var oldVertexIdToNewVertexId : Vector.<uint> = new Vector.<uint>(oldNumVertices, true); for (oldVertexId = 0; oldVertexId < oldNumVertices; ++oldVertexId) if (oldVertexIdToUsage[oldVertexId]) { var newVertexId : uint = newNumVertices++; // store new index oldVertexIdToNewVertexId[oldVertexId] = newVertexId; // rewrite vertexbuffer in place if (newVertexId != oldVertexId) { vertexData.position = newVertexId * bytesPerVertex; vertexData.writeBytes(vertexData, oldVertexId * bytesPerVertex, bytesPerVertex); } } vertexData.position = vertexDataStartPosition; vertexData.length = newNumVertices * bytesPerVertex; // rewrite index buffer in place indexData.position = indexDataStartPosition; for (indexId = 0; indexId < numIndices; ++indexId) { var index : uint = indexData.readShort(); indexData.position -= 4; indexData.writeShort(oldVertexIdToNewVertexId[index]); } indexData.position = indexDataStartPosition; } } }
package aerys.minko.render.geometry { import aerys.minko.render.shader.compiler.CRC32; import flash.utils.ByteArray; import flash.utils.Dictionary; import flash.utils.Endian; /** * The GeometrySanitizer static class provides methods to clean up * 3D geometry loaded from 3D asset files and make sure it is compliant * with the limitations of the Stage3D API. * * @author Romain Gilliotte * */ public final class GeometrySanitizer { public static const INDEX_LIMIT : uint = 524270; public static const VERTEX_LIMIT : uint = 65535; public static function isValid(indexData : ByteArray, vertexData : ByteArray, bytesPerVertex : uint = 12) : Boolean { var startPosition : uint = indexData.position; var numIndices : uint = indexData.bytesAvailable >> 2; var numVertices : uint = vertexData.bytesAvailable / bytesPerVertex; for (var indexId : uint = 0; indexId < numIndices; ++indexId) if (indexData.readUnsignedShort() >= numVertices) break; indexData.position = startPosition; return indexId >= numIndices; } /** * Split vertex and index buffers too big the be rendered. * The index stream limit is 524270, the vertex stream limit is 65536. * * @param inVertexData * @param inIndexData * @param outVertexDatas * @param outIndexDatas * @param dwordsPerVertex */ public static function splitBuffers(inVertices : ByteArray, inIndices : ByteArray, outVertices : Vector.<ByteArray>, outIndices : Vector.<ByteArray>, bytesPerVertex : uint = 12) : void { var inVerticesStartPosition : uint = inVertices.position; var numVertices : uint = inVertices.bytesAvailable / bytesPerVertex; var inIndicesStartPosition : uint = inIndices.position; var numIndices : uint = inIndices.bytesAvailable >>> 1; if (numIndices < INDEX_LIMIT && numVertices < VERTEX_LIMIT) { outVertices.push(inVertices); outIndices.push(inIndices); return; } while (inIndices.bytesAvailable) { var indexDataLength : uint = inIndices.bytesAvailable >> 1; // new buffers var partialVertexData : ByteArray = new ByteArray(); var partialIndexData : ByteArray = new ByteArray(); // local variables var oldVertexIds : Vector.<uint> = new Vector.<uint>(3, true); var newVertexIds : Vector.<uint> = new Vector.<uint>(3, true); var newVertexNeeded : Vector.<Boolean> = new Vector.<Boolean>(3, true); var usedVerticesDic : Dictionary = new Dictionary(); // this dictionary maps old and new indices var usedVerticesCount : uint = 0; // this counts elements in the dictionary var usedIndicesCount : uint = 0; // how many indices have we used? var neededVerticesCount : uint; // iterators & limits var localVertexId : uint; partialVertexData.endian = Endian.LITTLE_ENDIAN; partialIndexData.endian = Endian.LITTLE_ENDIAN; while (usedIndicesCount < indexDataLength) { // check if next triangle fits into the index buffer var remainingIndices : uint = INDEX_LIMIT - usedIndicesCount; if (remainingIndices < 3) break ; // check if next triangle fits into the vertex buffer var remainingVertices : uint = VERTEX_LIMIT - usedVerticesCount; neededVerticesCount = 0; for (localVertexId = 0; localVertexId < 3; ++localVertexId) { inIndices.position = (usedIndicesCount + localVertexId) << 2; oldVertexIds[localVertexId] = inIndices.readUnsignedShort(); var tmp : Object = usedVerticesDic[oldVertexIds[localVertexId]]; newVertexNeeded[localVertexId] = tmp == null; newVertexIds[localVertexId] = uint(tmp); if (newVertexNeeded[localVertexId]) ++neededVerticesCount; } if (remainingVertices < neededVerticesCount) break ; // it fills, let insert the triangle for (localVertexId = 0; localVertexId < 3; ++localVertexId) { if (newVertexNeeded[localVertexId]) { // copy current vertex into the new array partialVertexData.writeBytes( inVertices, oldVertexIds[localVertexId] * bytesPerVertex, bytesPerVertex ); // updates the id the temporary variable, to allow use filling partial index data later newVertexIds[localVertexId] = usedVerticesCount; // put its previous id in the dictionary usedVerticesDic[oldVertexIds[localVertexId]] = usedVerticesCount++; } partialIndexData.writeShort(newVertexIds[localVertexId]); } // ... increment indices counter usedIndicesCount += 3; } partialVertexData.position = 0; outVertices.push(partialVertexData); partialIndexData.position = 0; outIndices.push(partialIndexData); inVertices.position = inVerticesStartPosition; inIndices.position = inIndicesStartPosition; } } /** * Removes duplicated entries in a vertex buffer, and rewrite the index buffer according to it. * The buffers are modified in place. * * This method simplifies implementing parsers for file-formats that store per-vertex * and per-triangle information in different buffers, such as collada or OBJ: * merging them in a naive way and calling this method will do the job. * * @param vertexData * @param indexData * @param dwordsPerVertex */ public static function removeDuplicatedVertices(vertexData : ByteArray, indexData : ByteArray, bytesPerVertex : uint = 12) : void { var vertexDataStartPosition : uint = vertexData.position; var numVertices : uint = vertexData.bytesAvailable / bytesPerVertex; var indexDataStartPosition : uint = indexData.position; var numIndices : uint = indexData.bytesAvailable >>> 1; var hashToNewVertexId : Object = {}; var oldVertexIdToNewVertexId : Vector.<uint> = new Vector.<uint>(numVertices, true); var newVertexCount : uint = 0; var newLimit : uint = 0; for (var oldVertexId : uint = 0; oldVertexId < numVertices; ++oldVertexId) { vertexData.position = oldVertexId * bytesPerVertex; var numFloats : uint = bytesPerVertex >>> 2; var vertexHash : String = ''; while (numFloats) { vertexHash += vertexData.readFloat() + '|'; --numFloats; } var index : Object = hashToNewVertexId[vertexHash]; var newVertexId : uint = 0; if (index === null) { newVertexId = newVertexCount++; hashToNewVertexId[vertexHash] = newVertexId; newLimit = (1 + newVertexId) * bytesPerVertex; if (newVertexId != oldVertexId) { vertexData.position = newVertexId * bytesPerVertex; vertexData.writeBytes(vertexData, oldVertexId * bytesPerVertex, bytesPerVertex); } } else newVertexId = uint(index); oldVertexIdToNewVertexId[oldVertexId] = newVertexId; } vertexData.position = vertexDataStartPosition; vertexData.length = newLimit; for (var indexId : int = 0; indexId < numIndices; ++indexId) { index = indexData.readUnsignedShort(); indexData.position -= 2; indexData.writeShort(oldVertexIdToNewVertexId[index]); } indexData.position = indexDataStartPosition; } /** * Removes unused entries in a vertex buffer, and rewrite the index buffer according to it. * The buffers are modified in place. * * @param vertexData * @param indexData * @param dwordsPerVertex */ public static function removeUnusedVertices(vertexData : ByteArray, indexData : ByteArray, bytesPerVertex : uint = 12) : void { var vertexDataStartPosition : uint = vertexData.position; var oldNumVertices : uint = vertexData.bytesAvailable / bytesPerVertex; var newNumVertices : uint = 0; var indexDataStartPosition : uint = indexData.position; var numIndices : uint = indexData.bytesAvailable >>> 1; // iterators var oldVertexId : uint; var indexId : uint; // flag unused vertices by scanning the index buffer var oldVertexIdToUsage : Vector.<Boolean> = new Vector.<Boolean>(oldNumVertices, true); for (indexId = 0; indexId < numIndices; ++indexId) oldVertexIdToUsage[indexData.readUnsignedShort()] = true; // scan the flags, fix vertex buffer, and store old to new vertex id mapping var oldVertexIdToNewVertexId : Vector.<uint> = new Vector.<uint>(oldNumVertices, true); for (oldVertexId = 0; oldVertexId < oldNumVertices; ++oldVertexId) if (oldVertexIdToUsage[oldVertexId]) { var newVertexId : uint = newNumVertices++; // store new index oldVertexIdToNewVertexId[oldVertexId] = newVertexId; // rewrite vertexbuffer in place if (newVertexId != oldVertexId) { vertexData.position = newVertexId * bytesPerVertex; vertexData.writeBytes(vertexData, oldVertexId * bytesPerVertex, bytesPerVertex); } } vertexData.position = vertexDataStartPosition; vertexData.length = newNumVertices * bytesPerVertex; // rewrite index buffer in place indexData.position = indexDataStartPosition; for (indexId = 0; indexId < numIndices; ++indexId) { var index : uint = indexData.readUnsignedShort(); indexData.position -= 4; indexData.writeShort(oldVertexIdToNewVertexId[index]); } indexData.position = indexDataStartPosition; } } }
update GeometrySanitizer methods to use ByteArray.readUnsignerShort() to read indices
update GeometrySanitizer methods to use ByteArray.readUnsignerShort() to read indices
ActionScript
mit
aerys/minko-as3
b2238af499573cd571abedd8af0b4d8e2c7f3d55
WeaveUI/src/weave/ui/CustomTree.as
WeaveUI/src/weave/ui/CustomTree.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.ui { import flash.events.Event; import mx.collections.CursorBookmark; import mx.collections.ICollectionView; import mx.collections.IList; import mx.collections.IViewCursor; import mx.controls.Tree; import mx.core.ScrollPolicy; import mx.core.mx_internal; import mx.utils.ObjectUtil; import weave.utils.EventUtils; /** * This class features a correctly behaving auto scroll policy and scrollToIndex(). * @author adufilie */ public class CustomTree extends Tree { public function CustomTree() { super(); addEventListener("scroll", updateHScrollLater); } /////////////////////////////////////////////////////////////////////////////// // solution for automatic maxHorizontalScrollPosition calculation // modified from http://www.frishy.com/2007/09/autoscrolling-for-flex-tree/ // we need to override maxHorizontalScrollPosition because setting // Tree's maxHorizontalScrollPosition adds an indent value to it, // which we don't need as measureWidthOfItems seems to return exactly // what we need. Not only that, but getIndent() seems to be broken // anyways (SDK-12578). // I hate using mx_internal stuff, but we can't do // super.super.maxHorizontalScrollPosition in AS 3, so we have to // emulate it. override public function get maxHorizontalScrollPosition():Number { if (isNaN(mx_internal::_maxHorizontalScrollPosition)) return 0; return mx_internal::_maxHorizontalScrollPosition; } override public function set maxHorizontalScrollPosition(value:Number):void { if (ObjectUtil.numericCompare(mx_internal::_maxHorizontalScrollPosition, value) != 0) { mx_internal::_maxHorizontalScrollPosition = value; dispatchEvent(new Event("maxHorizontalScrollPositionChanged")); scrollAreaChanged = true; invalidateDisplayList(); } } private const updateHScrollLater:Function = EventUtils.generateDelayedCallback(this, updateHScrollNow, 0); private function updateHScrollNow():void { // we call measureWidthOfItems to get the max width of the item renderers. // then we see how much space we need to scroll, setting maxHorizontalScrollPosition appropriately var widthOfVisibleItems:int = measureWidthOfItems(verticalScrollPosition - offscreenExtraRowsTop, listItems.length); var maxHSP:Number = widthOfVisibleItems - (unscaledWidth - viewMetrics.left - viewMetrics.right); var hspolicy:String = ScrollPolicy.ON; if (maxHSP <= 0) { maxHSP = 0; horizontalScrollPosition = 0; // horizontal scroll is kept on except when there is no vertical scroll // this avoids an infinite hide/show loop where hiding/showing the h-scroll bar affects the max h-scroll value if (maxVerticalScrollPosition == 0) hspolicy = ScrollPolicy.OFF; } maxHorizontalScrollPosition = maxHSP; if (horizontalScrollPolicy != hspolicy) horizontalScrollPolicy = hspolicy; } /** * @param itemTest A function to test for a matching item: function(item:Object):Boolean * @return The matching item, if found. */ public function scrollToAndSelectMatchingItem(itemTest:Function):Object { var i:int = 0; var cursor:IViewCursor = collection.createCursor(); do { if (itemTest(cursor.current)) { // set selection before scrollToIndex() or it won't scroll selectedItems = [cursor.current]; scrollToIndex(i); return cursor.current; } i++; } while (cursor.moveNext()); // no selection selectedItems = []; return null; } /////////////////////////////////////////////////////////////////////////////// // solution for display bugs when hierarchical data changes private var _dataProvider:Object; // remembers previous value that was passed to "set dataProvider" private var _rootItem:Object; override public function set dataProvider(value:Object):void { _dataProvider = value; super.dataProvider = value; _rootItem = mx_internal::_hasRoot ? mx_internal::_rootModel.createCursor().current : null; } /** * This function must be called whenever the hierarchical data changes. * Otherwise, the Tree will not display properly. */ public function refreshDataProvider():void { var _firstVisibleItem:Object = firstVisibleItem; var _selectedItems:Array = selectedItems; var _openItems:Array = openItems.concat(); // use value previously passed to "set dataProvider" in order to create a new collection wrapper. dataProvider = _dataProvider; // commitProperties() behaves as desired when both dataProvider and openItems are set. openItems = _openItems; validateNow(); // necessary in order to select previous items and scroll back to the correct position if (showRoot || _firstVisibleItem != _rootItem) { // scroll to the previous item, but only if it is within scroll range var vsp:int = getItemIndex(_firstVisibleItem); if (vsp >= 0 && vsp <= maxVerticalScrollPosition) firstVisibleItem = _firstVisibleItem; } // selectedItems must be set last to avoid a bug where the Tree scrolls to the top. selectedItems = _selectedItems; } /** * This contains a workaround for a problem in List.configureScrollBars relying on a non-working function CursorBookmark.getViewIndex(). * This fixes the bug where the tree would scroll all the way from the bottom to the top when a node is collapsed. */ override protected function configureScrollBars():void { var ac:ICollectionView = actualCollection; var ai:IViewCursor = actualIterator; var rda:Boolean = runningDataEffect; runningDataEffect = true; actualCollection = ac || collection; // avoids null pointer error actualIterator = ai || iterator; // This is not a perfect scrolling solution. It looks ok when there is a partial row showing at the bottom. var mvsp:int = Math.max(0, collection.length - listItems.length + 1); if (verticalScrollPosition > mvsp) verticalScrollPosition = mvsp; super.configureScrollBars(); runningDataEffect = rda; actualCollection = ac; actualIterator = ai; } override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { updateHScrollLater(); // If showRoot is false and root is showing, force commitProperties() to fix the problem. // This workaround requires that the data descriptor reports that the root item is a branch and it has children, even if it doesn't. if (!showRoot && _rootItem && itemToItemRenderer(_rootItem)) { mx_internal::showRootChanged = true; commitProperties(); } // "iterator" is a HierarchicalViewCursor, and its movePrevious()/moveNext()/seek() functions do not work if "current" is null. // Calling refreshDataProvider() returns the tree to a working state. if (iterator && iterator.current == null) refreshDataProvider(); super.updateDisplayList(unscaledWidth, unscaledHeight); } private var _pendingScrollToIndex:int = -1; override public function scrollToIndex(index:int):Boolean { if (index < -1) { index /= -2; if (index != _pendingScrollToIndex) { _pendingScrollToIndex = -1; return false; } } _pendingScrollToIndex = -1; if (maxVerticalScrollPosition == 0 && index > 0) { _pendingScrollToIndex = index; callLater(scrollToIndex, [index * -2]); return false; } return super.scrollToIndex(index); } } }
/* 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.ui { import flash.events.Event; import mx.collections.CursorBookmark; import mx.collections.ICollectionView; import mx.collections.IList; import mx.collections.IViewCursor; import mx.controls.Tree; import mx.core.ScrollPolicy; import mx.core.mx_internal; import mx.utils.ObjectUtil; import weave.utils.EventUtils; /** * This class features a correctly behaving auto scroll policy and scrollToIndex(). * @author adufilie */ public class CustomTree extends Tree { public function CustomTree() { super(); addEventListener("scroll", updateHScrollLater); } /////////////////////////////////////////////////////////////////////////////// // solution for automatic maxHorizontalScrollPosition calculation // modified from http://www.frishy.com/2007/09/autoscrolling-for-flex-tree/ // we need to override maxHorizontalScrollPosition because setting // Tree's maxHorizontalScrollPosition adds an indent value to it, // which we don't need as measureWidthOfItems seems to return exactly // what we need. Not only that, but getIndent() seems to be broken // anyways (SDK-12578). // I hate using mx_internal stuff, but we can't do // super.super.maxHorizontalScrollPosition in AS 3, so we have to // emulate it. override public function get maxHorizontalScrollPosition():Number { if (isNaN(mx_internal::_maxHorizontalScrollPosition)) return 0; return mx_internal::_maxHorizontalScrollPosition; } override public function set maxHorizontalScrollPosition(value:Number):void { if (ObjectUtil.numericCompare(mx_internal::_maxHorizontalScrollPosition, value) != 0) { mx_internal::_maxHorizontalScrollPosition = value; dispatchEvent(new Event("maxHorizontalScrollPositionChanged")); scrollAreaChanged = true; invalidateDisplayList(); } } private const updateHScrollLater:Function = EventUtils.generateDelayedCallback(this, updateHScrollNow, 0); private function updateHScrollNow():void { // we call measureWidthOfItems to get the max width of the item renderers. // then we see how much space we need to scroll, setting maxHorizontalScrollPosition appropriately var widthOfVisibleItems:int = measureWidthOfItems(verticalScrollPosition - offscreenExtraRowsTop, listItems.length); var maxHSP:Number = widthOfVisibleItems - (unscaledWidth - viewMetrics.left - viewMetrics.right); var hspolicy:String = ScrollPolicy.ON; if (maxHSP <= 0) { maxHSP = 0; horizontalScrollPosition = 0; // horizontal scroll is kept on except when there is no vertical scroll // this avoids an infinite hide/show loop where hiding/showing the h-scroll bar affects the max h-scroll value if (maxVerticalScrollPosition == 0) hspolicy = ScrollPolicy.OFF; } maxHorizontalScrollPosition = maxHSP; if (horizontalScrollPolicy != hspolicy) horizontalScrollPolicy = hspolicy; } /** * @param itemTest A function to test for a matching item: function(item:Object):Boolean * @return The matching item, if found. */ public function scrollToAndSelectMatchingItem(itemTest:Function):Object { var i:int = 0; var cursor:IViewCursor = collection.createCursor(); do { if (itemTest(cursor.current)) { // set selection before scrollToIndex() or it won't scroll selectedItems = [cursor.current]; scrollToIndex(i); return cursor.current; } i++; } while (cursor.moveNext()); // no selection selectedItems = []; return null; } /////////////////////////////////////////////////////////////////////////////// // solution for display bugs when hierarchical data changes private var _dataProvider:Object; // remembers previous value that was passed to "set dataProvider" private var _rootItem:Object; override public function set dataProvider(value:Object):void { _dataProvider = value; super.dataProvider = value; _rootItem = mx_internal::_hasRoot ? mx_internal::_rootModel.createCursor().current : null; } /** * This function must be called whenever the hierarchical data changes. * Otherwise, the Tree will not display properly. */ public function refreshDataProvider():void { var _firstVisibleItem:Object = firstVisibleItem; var _selectedItems:Array = selectedItems; var _openItems:Array = openItems.concat(); // use value previously passed to "set dataProvider" in order to create a new collection wrapper. dataProvider = _dataProvider; // commitProperties() behaves as desired when both dataProvider and openItems are set. openItems = _openItems; validateNow(); // necessary in order to select previous items and scroll back to the correct position if (showRoot || _firstVisibleItem != _rootItem) { // scroll to the previous item, but only if it is within scroll range var vsp:int = getItemIndex(_firstVisibleItem); if (vsp >= 0 && vsp <= maxVerticalScrollPosition) firstVisibleItem = _firstVisibleItem; } // selectedItems must be set last to avoid a bug where the Tree scrolls to the top. selectedItems = _selectedItems; } /** * This contains a workaround for a problem in List.configureScrollBars relying on a non-working function CursorBookmark.getViewIndex(). * This fixes the bug where the tree would scroll all the way from the bottom to the top when a node is collapsed. */ override protected function configureScrollBars():void { var ac:ICollectionView = actualCollection; var ai:IViewCursor = actualIterator; var rda:Boolean = runningDataEffect; runningDataEffect = true; actualCollection = ac || collection; actualIterator = ai || iterator; // This is not a perfect scrolling solution. It looks ok when there is a partial row showing at the bottom. var mvsp:int = actualCollection ? Math.max(0, actualCollection.length - listItems.length + 1) : 0; if (verticalScrollPosition > mvsp) verticalScrollPosition = mvsp; super.configureScrollBars(); runningDataEffect = rda; actualCollection = ac; actualIterator = ai; } override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { updateHScrollLater(); // If showRoot is false and root is showing, force commitProperties() to fix the problem. // This workaround requires that the data descriptor reports that the root item is a branch and it has children, even if it doesn't. if (!showRoot && _rootItem && itemToItemRenderer(_rootItem)) { mx_internal::showRootChanged = true; commitProperties(); } // "iterator" is a HierarchicalViewCursor, and its movePrevious()/moveNext()/seek() functions do not work if "current" is null. // Calling refreshDataProvider() returns the tree to a working state. if (iterator && iterator.current == null) refreshDataProvider(); super.updateDisplayList(unscaledWidth, unscaledHeight); } private var _pendingScrollToIndex:int = -1; override public function scrollToIndex(index:int):Boolean { if (index < -1) { index /= -2; if (index != _pendingScrollToIndex) { _pendingScrollToIndex = -1; return false; } } _pendingScrollToIndex = -1; if (maxVerticalScrollPosition == 0 && index > 0) { _pendingScrollToIndex = index; callLater(scrollToIndex, [index * -2]); return false; } return super.scrollToIndex(index); } } }
fix null pointer error
fix null pointer error
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
19fd00b9d549693684e0c2751f4895be3dfaca87
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; } } }
Change default language to ENGLISH
Change default language to ENGLISH
ActionScript
agpl-3.0
MichaelHoffmann/AGORA,mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA
5df05bb648414779246e1936bab97ab21dafe3dc
exporter/src/main/as/flump/xfl/XflKeyframe.as
exporter/src/main/as/flump/xfl/XflKeyframe.as
// // Flump - Copyright 2012 Three Rings Design package flump.xfl { import flash.geom.Matrix; import flash.geom.Point; import flump.MatrixUtil; import flump.mold.KeyframeMold; import com.threerings.util.XmlUtil; public class XflKeyframe { use namespace xflns; public static function parse (lib :XflLibrary, baseLocation :String, xml :XML, flipbook :Boolean) :KeyframeMold { var kf :KeyframeMold = new KeyframeMold(); kf.index = XmlUtil.getIntAttr(xml, "index"); kf.location = baseLocation + ":" + kf.index; kf.duration = XmlUtil.getNumberAttr(xml, "duration", 1); kf.label = XmlUtil.getStringAttr(xml, "name", null); kf.ease = XmlUtil.getNumberAttr(xml, "acceleration", 0) / 100; if (flipbook) return kf; var symbolXml :XML; for each (var frameEl :XML in xml.elements.elements()) { if (frameEl.name().localName == "DOMSymbolInstance") { if (symbolXml != null) { lib.addError(kf, ParseError.CRIT, "There can be only one symbol instance at " + "a time in a keyframe."); } else symbolXml = frameEl; } else { lib.addError(kf, ParseError.CRIT, "Non-symbols may not be in movie layers"); } } if (symbolXml == null) return kf; // Purely labelled frame if (XmlUtil.hasChild(xml, "tweens")) { lib.addError(kf, ParseError.WARN, "Custom easing is not supported"); } kf.id = kf.libraryItem = XmlUtil.getStringAttr(symbolXml, "libraryItemName"); kf.visible = XmlUtil.getBooleanAttr(symbolXml, "isVisible", true); var matrix :Matrix = new Matrix(); // Read the matrix transform if (symbolXml.matrix != null) { const matrixXml :XML = symbolXml.matrix.Matrix[0]; function m (name :String, def :Number) :Number { return matrixXml == null ? def : XmlUtil.getNumberAttr(matrixXml, name, def); } matrix = new Matrix(m("a", 1), m("b", 0), m("c", 0), m("d", 1), m("tx", 0), m("ty", 0)); // Back out of translation var rewound :Matrix = matrix.clone(); rewound.tx = rewound.ty = 0; var p0 :Point = rewound.transformPoint(new Point(0, 0)); var p1 :Point = rewound.transformPoint(new Point(1, 0)); kf.rotation = Math.atan2(p1.y - p0.y, p1.x - p0.x); // Back out of rotation rewound.rotate(-kf.rotation); p0 = rewound.transformPoint(new Point(0, 0)); p1 = rewound.transformPoint(new Point(1, 1)); kf.scaleX = p1.x - p0.x; kf.scaleY = p1.y - p0.y; // var skewX :Number = p1.x - 1; // var skewY :Number = p1.y - 1; } // Read the pivot point if (symbolXml.transformationPoint != null) { var pivotXml :XML = symbolXml.transformationPoint.Point[0]; if (pivotXml != null) { kf.pivotX = XmlUtil.getNumberAttr(pivotXml, "x", 0); kf.pivotY = XmlUtil.getNumberAttr(pivotXml, "y", 0); // Translate to the pivot point var orig :Matrix = matrix.clone(); matrix.identity(); matrix.translate(kf.pivotX, kf.pivotY); matrix.concat(orig); } } // Now that the matrix and pivot point have been read, apply translation kf.x = matrix.tx; kf.y = matrix.ty; // Read the alpha if (symbolXml.color != null) { var colorXml :XML = symbolXml.color.Color[0]; if (colorXml != null) { kf.alpha = XmlUtil.getNumberAttr(colorXml, "alphaMultiplier", 1); } } return kf; } } }
// // Flump - Copyright 2012 Three Rings Design package flump.xfl { import flash.geom.Matrix; import flash.geom.Point; import flump.MatrixUtil; import flump.mold.KeyframeMold; import com.threerings.util.XmlUtil; public class XflKeyframe { use namespace xflns; public static function parse (lib :XflLibrary, baseLocation :String, xml :XML, flipbook :Boolean) :KeyframeMold { var kf :KeyframeMold = new KeyframeMold(); kf.index = XmlUtil.getIntAttr(xml, "index"); kf.location = baseLocation + ":" + kf.index; kf.duration = XmlUtil.getNumberAttr(xml, "duration", 1); kf.label = XmlUtil.getStringAttr(xml, "name", null); kf.ease = XmlUtil.getNumberAttr(xml, "acceleration", 0) / 100; if (flipbook) return kf; var symbolXml :XML; for each (var frameEl :XML in xml.elements.elements()) { if (frameEl.name().localName == "DOMSymbolInstance") { if (symbolXml != null) { lib.addError(kf, ParseError.CRIT, "There can be only one symbol instance at " + "a time in a keyframe."); } else symbolXml = frameEl; } else { lib.addError(kf, ParseError.CRIT, "Non-symbols may not be in movie layers"); } } if (symbolXml == null) return kf; // Purely labelled frame if (XmlUtil.getBooleanAttr(xml, "hasCustomEase", false)) { lib.addError(kf, ParseError.WARN, "Custom easing is not supported"); } kf.id = kf.libraryItem = XmlUtil.getStringAttr(symbolXml, "libraryItemName"); kf.visible = XmlUtil.getBooleanAttr(symbolXml, "isVisible", true); var matrix :Matrix = new Matrix(); // Read the matrix transform if (symbolXml.matrix != null) { const matrixXml :XML = symbolXml.matrix.Matrix[0]; function m (name :String, def :Number) :Number { return matrixXml == null ? def : XmlUtil.getNumberAttr(matrixXml, name, def); } matrix = new Matrix(m("a", 1), m("b", 0), m("c", 0), m("d", 1), m("tx", 0), m("ty", 0)); // Back out of translation var rewound :Matrix = matrix.clone(); rewound.tx = rewound.ty = 0; var p0 :Point = rewound.transformPoint(new Point(0, 0)); var p1 :Point = rewound.transformPoint(new Point(1, 0)); kf.rotation = Math.atan2(p1.y - p0.y, p1.x - p0.x); // Back out of rotation rewound.rotate(-kf.rotation); p0 = rewound.transformPoint(new Point(0, 0)); p1 = rewound.transformPoint(new Point(1, 1)); kf.scaleX = p1.x - p0.x; kf.scaleY = p1.y - p0.y; // var skewX :Number = p1.x - 1; // var skewY :Number = p1.y - 1; } // Read the pivot point if (symbolXml.transformationPoint != null) { var pivotXml :XML = symbolXml.transformationPoint.Point[0]; if (pivotXml != null) { kf.pivotX = XmlUtil.getNumberAttr(pivotXml, "x", 0); kf.pivotY = XmlUtil.getNumberAttr(pivotXml, "y", 0); // Translate to the pivot point var orig :Matrix = matrix.clone(); matrix.identity(); matrix.translate(kf.pivotX, kf.pivotY); matrix.concat(orig); } } // Now that the matrix and pivot point have been read, apply translation kf.x = matrix.tx; kf.y = matrix.ty; // Read the alpha if (symbolXml.color != null) { var colorXml :XML = symbolXml.color.Color[0]; if (colorXml != null) { kf.alpha = XmlUtil.getNumberAttr(colorXml, "alphaMultiplier", 1); } } return kf; } } }
Change the way custom easing is detected.
Change the way custom easing is detected.
ActionScript
mit
tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,funkypandagame/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump
e81640c1f0a7b20651b50ed436fb92447d7e38fa
src/aerys/minko/render/shader/Shader.as
src/aerys/minko/render/shader/Shader.as
package aerys.minko.render.shader { import aerys.minko.ns.minko_render; import aerys.minko.ns.minko_shader; import aerys.minko.render.RenderTarget; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.shader.compiler.graph.ShaderGraph; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.part.ShaderPart; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import flash.utils.getQualifiedClassName; import aerys.minko.type.binding.Signature; import aerys.minko.render.ShaderDataBindingsProxy; use namespace minko_shader; /** * The base class to extend in order to create ActionScript shaders * and program the GPU using AS3. * * @author Jean-Marc Le Roux * @author Romain Gilliotte * * @see aerys.minko.render.shader.ShaderPart * @see aerys.minko.render.shader.ShaderInstance * @see aerys.minko.render.shader.ShaderSignature * @see aerys.minko.render.shader.ShaderDataBindings */ public class Shader extends ShaderPart { use namespace minko_shader; use namespace minko_render; minko_shader var _meshBindings : ShaderDataBindingsProxy = null; minko_shader var _sceneBindings : ShaderDataBindingsProxy = null; minko_shader var _kills : Vector.<AbstractNode> = new <AbstractNode>[]; private var _name : String = null; private var _enabled : Boolean = true; private var _defaultSettings : ShaderSettings = new ShaderSettings(null); private var _instances : Vector.<ShaderInstance> = new <ShaderInstance>[]; private var _numActiveInstances : uint = 0; private var _numRenderedInstances : uint = 0; private var _settings : Vector.<ShaderSettings> = new <ShaderSettings>[]; private var _programs : Vector.<Program3DResource> = new <Program3DResource>[]; private var _begin : Signal = new Signal('Shader.begin'); private var _end : Signal = new Signal('Shader.end'); /** * The name of the shader. Default value is the qualified name of the * ActionScript shader class (example: "aerys.minko.render.effect.basic::BasicShader"). * * @return * */ public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very first time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get begin() : Signal { return _begin; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very last time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get end() : Signal { return _end; } /** * Whether the shader (and all its forks) are enabled for rendering * or not. * * @return * */ public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } /** * * @param priority Default value is 0. * @param renderTarget Default value is null. * */ public function Shader(renderTarget : RenderTarget = null, priority : Number = 0.0) { super(this); _defaultSettings.renderTarget = renderTarget; _defaultSettings.priority = priority; _name = getQualifiedClassName(this); } public function fork(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderInstance { var pass : ShaderInstance = findPass(sceneBindings, meshBindings); if (!pass) { var signature : Signature = new Signature(); var config : ShaderSettings = findOrCreateSettings( sceneBindings, meshBindings ); signature.mergeWith(config.signature); var program : Program3DResource = null; if (config.enabled) { program = findOrCreateProgram(sceneBindings, meshBindings); signature.mergeWith(program.signature); } pass = new ShaderInstance(this, config, program, signature); pass.retained.add(shaderInstanceRetainedHandler); pass.released.add(shaderInstanceReleasedHandler); _instances.push(pass); } return pass; } public function disposeUnusedResources() : void { var numInstances : uint = _instances.length; var currentId : uint = 0; for (var instanceId : uint = 0; instanceId < numInstances; ++instanceId) { var passInstance : ShaderInstance = _instances[instanceId]; if (!passInstance.isDisposable) _instances[currentId++] = passInstance; } _instances.length = currentId; } /** * Override this method to initialize the settings * - such as the blending operands or the triangle culling - of the shader. * This values can be read from both the mesh and the scene bindings. * * @param settings * * @see aerys.minko.render.shader.ShaderSettings * */ protected function initializeSettings(settings : ShaderSettings) : void { // nothing } /** * The getVertexPosition() method is called to evaluate the vertex shader * program that shall be executed on the GPU. * * @return The position of the vertex in clip space (normalized screen space). * */ protected function getVertexPosition() : SFloat { throw new Error("The method 'getVertexPosition' must be implemented."); } /** * The getPixelColor() method is called to evaluate the fragment shader * program that shall be executed on the GPU. * * @return The color of the pixel on the screen. * */ protected function getPixelColor() : SFloat { throw new Error("The method 'getPixelColor' must be implemented."); } private function findPass(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderInstance { var numPasses : int = _instances.length; for (var passId : uint = 0; passId < numPasses; ++passId) if (_instances[passId].signature.isValid(sceneBindings, meshBindings)) return _instances[passId]; return null; } private function findOrCreateProgram(sceneBindings : DataBindings, meshBindings : DataBindings) : Program3DResource { var numPrograms : int = _programs.length; var program : Program3DResource; for (var programId : uint = 0; programId < numPrograms; ++programId) if (_programs[programId].signature.isValid(sceneBindings, meshBindings)) return _programs[programId]; var signature : Signature = new Signature(); _meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE); var vertexPosition : AbstractNode = getVertexPosition()._node; var pixelColor : AbstractNode = getPixelColor()._node; var shaderGraph : ShaderGraph = new ShaderGraph(vertexPosition, pixelColor, _kills); program = shaderGraph.generateProgram(_name, signature); _meshBindings = null; _sceneBindings = null; _kills.length = 0; _programs.push(program); return program; } private function findOrCreateSettings(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderSettings { var numConfigs : int = _settings.length; var config : ShaderSettings = null; for (var configId : int = 0; configId < numConfigs; ++configId) if (_settings[configId].signature.isValid(sceneBindings, meshBindings)) return _settings[configId]; var signature : Signature = new Signature(); config = _defaultSettings.clone(signature); _meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE); initializeSettings(config); _meshBindings = null; _sceneBindings = null; _settings.push(config); return config; } private function shaderInstanceRetainedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 1) { ++_numActiveInstances; instance.begin.add(shaderInstanceBeginHandler); instance.end.add(shaderInstanceEndHandler); } } private function shaderInstanceReleasedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 0) { --_numActiveInstances; instance.begin.remove(shaderInstanceBeginHandler); instance.end.remove(shaderInstanceEndHandler); } } private function shaderInstanceBeginHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { if (_numRenderedInstances == 0) _begin.execute(this, context, backBuffer); } private function shaderInstanceEndHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { _numRenderedInstances++; if (_numRenderedInstances == _numActiveInstances) { _numRenderedInstances = 0; _end.execute(this, context, backBuffer); } } } }
package aerys.minko.render.shader { import aerys.minko.ns.minko_render; import aerys.minko.ns.minko_shader; import aerys.minko.render.RenderTarget; import aerys.minko.render.ShaderDataBindingsProxy; import aerys.minko.render.resource.Context3DResource; import aerys.minko.render.resource.Program3DResource; import aerys.minko.render.shader.compiler.graph.ShaderGraph; import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode; import aerys.minko.render.shader.part.ShaderPart; import aerys.minko.type.Signal; import aerys.minko.type.binding.DataBindings; import aerys.minko.type.binding.Signature; import flash.utils.getQualifiedClassName; use namespace minko_shader; /** * The base class to extend in order to create ActionScript shaders * and program the GPU using AS3. * * @author Jean-Marc Le Roux * @author Romain Gilliotte * * @see aerys.minko.render.shader.ShaderPart * @see aerys.minko.render.shader.ShaderInstance * @see aerys.minko.render.shader.ShaderSignature * @see aerys.minko.render.shader.ShaderDataBindings */ public class Shader extends ShaderPart { use namespace minko_shader; use namespace minko_render; minko_shader var _meshBindings : ShaderDataBindingsProxy = null; minko_shader var _sceneBindings : ShaderDataBindingsProxy = null; minko_shader var _kills : Vector.<AbstractNode> = new <AbstractNode>[]; private var _name : String = null; private var _enabled : Boolean = true; private var _defaultSettings : ShaderSettings = new ShaderSettings(null); private var _instances : Vector.<ShaderInstance> = new <ShaderInstance>[]; private var _numActiveInstances : uint = 0; private var _numRenderedInstances : uint = 0; private var _settings : Vector.<ShaderSettings> = new <ShaderSettings>[]; private var _programs : Vector.<Program3DResource> = new <Program3DResource>[]; private var _begin : Signal = new Signal('Shader.begin'); private var _end : Signal = new Signal('Shader.end'); /** * The name of the shader. Default value is the qualified name of the * ActionScript shader class (example: "aerys.minko.render.effect.basic::BasicShader"). * * @return * */ public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very first time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get begin() : Signal { return _begin; } /** * The signal executed when the shader (one of its forks) is used * for rendering for the very last time during the current frame. * Callbacks for this signal must accept the following arguments: * <ul> * <li>shader : Shader, the shader executing the signal</li> * <li>context : Context3D, the context used for rendering</li> * <li>backBuffer : RenderTarget, the render target used as the back-buffer</li> * </ul> * * @return * */ public function get end() : Signal { return _end; } /** * Whether the shader (and all its forks) are enabled for rendering * or not. * * @return * */ public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } /** * * @param priority Default value is 0. * @param renderTarget Default value is null. * */ public function Shader(renderTarget : RenderTarget = null, priority : Number = 0.0) { super(this); _defaultSettings.renderTarget = renderTarget; _defaultSettings.priority = priority; _name = getQualifiedClassName(this); } public function fork(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderInstance { var pass : ShaderInstance = findPass(sceneBindings, meshBindings); if (!pass) { var signature : Signature = new Signature(); var config : ShaderSettings = findOrCreateSettings( sceneBindings, meshBindings ); signature.mergeWith(config.signature); var program : Program3DResource = null; if (config.enabled) { program = findOrCreateProgram(sceneBindings, meshBindings); signature.mergeWith(program.signature); } pass = new ShaderInstance(this, config, program, signature); pass.retained.add(shaderInstanceRetainedHandler); pass.released.add(shaderInstanceReleasedHandler); _instances.push(pass); } return pass; } public function disposeUnusedResources() : void { var numInstances : uint = _instances.length; var currentId : uint = 0; for (var instanceId : uint = 0; instanceId < numInstances; ++instanceId) { var passInstance : ShaderInstance = _instances[instanceId]; if (!passInstance.isDisposable) _instances[currentId++] = passInstance; } _instances.length = currentId; } /** * Override this method to initialize the settings * - such as the blending operands or the triangle culling - of the shader. * This values can be read from both the mesh and the scene bindings. * * @param settings * * @see aerys.minko.render.shader.ShaderSettings * */ protected function initializeSettings(settings : ShaderSettings) : void { // nothing } /** * The getVertexPosition() method is called to evaluate the vertex shader * program that shall be executed on the GPU. * * @return The position of the vertex in clip space (normalized screen space). * */ protected function getVertexPosition() : SFloat { throw new Error("The method 'getVertexPosition' must be implemented."); } /** * The getPixelColor() method is called to evaluate the fragment shader * program that shall be executed on the GPU. * * @return The color of the pixel on the screen. * */ protected function getPixelColor() : SFloat { throw new Error("The method 'getPixelColor' must be implemented."); } private function findPass(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderInstance { var numPasses : int = _instances.length; for (var passId : uint = 0; passId < numPasses; ++passId) if (_instances[passId].signature.isValid(sceneBindings, meshBindings)) return _instances[passId]; return null; } private function findOrCreateProgram(sceneBindings : DataBindings, meshBindings : DataBindings) : Program3DResource { var numPrograms : int = _programs.length; var program : Program3DResource; for (var programId : uint = 0; programId < numPrograms; ++programId) if (_programs[programId].signature.isValid(sceneBindings, meshBindings)) return _programs[programId]; var signature : Signature = new Signature(); _meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE); var vertexPosition : AbstractNode = getVertexPosition()._node; var pixelColor : AbstractNode = getPixelColor()._node; var shaderGraph : ShaderGraph = new ShaderGraph(vertexPosition, pixelColor, _kills); program = shaderGraph.generateProgram(_name, signature); _meshBindings = null; _sceneBindings = null; _kills.length = 0; _programs.push(program); return program; } private function findOrCreateSettings(sceneBindings : DataBindings, meshBindings : DataBindings) : ShaderSettings { var numConfigs : int = _settings.length; var config : ShaderSettings = null; for (var configId : int = 0; configId < numConfigs; ++configId) if (_settings[configId].signature.isValid(sceneBindings, meshBindings)) return _settings[configId]; var signature : Signature = new Signature(); config = _defaultSettings.clone(signature); _meshBindings = new ShaderDataBindingsProxy(meshBindings, signature, Signature.SOURCE_MESH); _sceneBindings = new ShaderDataBindingsProxy(sceneBindings, signature, Signature.SOURCE_SCENE); initializeSettings(config); _meshBindings = null; _sceneBindings = null; _settings.push(config); return config; } private function shaderInstanceRetainedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 1) { ++_numActiveInstances; instance.begin.add(shaderInstanceBeginHandler); instance.end.add(shaderInstanceEndHandler); } } private function shaderInstanceReleasedHandler(instance : ShaderInstance, numUses : uint) : void { if (numUses == 0) { --_numActiveInstances; instance.begin.remove(shaderInstanceBeginHandler); instance.end.remove(shaderInstanceEndHandler); } } private function shaderInstanceBeginHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { if (_numRenderedInstances == 0) _begin.execute(this, context, backBuffer); } private function shaderInstanceEndHandler(instance : ShaderInstance, context : Context3DResource, backBuffer : RenderTarget) : void { _numRenderedInstances++; if (_numRenderedInstances == _numActiveInstances) { _numRenderedInstances = 0; _end.execute(this, context, backBuffer); } } } }
refactor imports
refactor imports
ActionScript
mit
aerys/minko-as3
48762f4df8cf990dcbf5f0c6007ed118e46c073f
src/aerys/minko/type/math/Quaternion.as
src/aerys/minko/type/math/Quaternion.as
package aerys.minko.type.math { import mx.charts.chartClasses.NumericAxis; import mx.effects.easing.Quartic; public class Quaternion { private static const TMP_QUATERNION : Quaternion = new Quaternion(); public function get r() : Number { return _r; } public function get i() : Number { return _i; } public function get j() : Number { return _j; } public function get k() : Number { return _k; } protected var _r : Number; protected var _i : Number; protected var _j : Number; protected var _k : Number; public static function isEqual(q1 : Quaternion, q2 : Quaternion) : Boolean { return q1._r == q2._r && q1._i == q2._i && q1._j == q2._j && q1._k == q2._k; } public static function isNotEqual(q1 : Quaternion, q2 : Quaternion) : Boolean { return !isEqual(q1, q2); } public static function norm(q : Quaternion) : Number { return q._r * q._r + q._i * q._i + q._j * q._j + q._k * q._k; } public static function absolute(q : Quaternion) : Number { return Math.sqrt(Quaternion.norm(q)); } public static function add(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = q1._r + q2._r; out._i = q1._i + q2._i; out._j = q1._j + q2._j; out._k = q1._k + q2._k; return out; } public static function substract(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = q1._r - q2._r; out._i = q1._i - q2._i; out._j = q1._j - q2._j; out._k = q1._k - q2._k; return out; } public static function multiplyScalar(q : Quaternion, f : Number, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = q._r * f; out._i = q._i * f; out._j = q._j * f; out._k = q._k * f; return out; } public static function multiply(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); var t0 : Number = (q1._k - q1._j) * (q2._j - q2._k); var t1 : Number = (q1._r + q1._i) * (q2._r + q2._i); var t2 : Number = (q1._r - q1._i) * (q2._j + q2._k); var t3 : Number = (q1._k + q1._j) * (q2._r - q2._i); var t4 : Number = (q1._k - q1._i) * (q2._i - q2._j); var t5 : Number = (q1._k + q1._i) * (q2._i + q2._j); var t6 : Number = (q1._r + q1._j) * (q2._r - q2._k); var t7 : Number = (q1._r - q1._j) * (q2._r + q2._k); var t8 : Number = t5 + t6 + t7; var t9 : Number = (t4 + t8) / 2; out._r = t0 + t9 - t5; out._i = t1 + t9 - t8; out._j = t2 + t9 - t7; out._k = t3 + t9 - t6; return out; } public static function divideScalar(q : Quaternion, f : Number, out : Quaternion = null) : Quaternion { return Quaternion.multiplyScalar(q, 1 / f, out); } public static function divide(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion { Quaternion.invert(q2, TMP_QUATERNION); Quaternion.multiply(q1, TMP_QUATERNION, out); return out; } public static function copy(q : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = q._r; out._i = q._i; out._j = q._j; out._k = q._k; return out; } public static function negate(q : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = - q._r; out._i = - q._i; out._j = - q._j; out._k = - q._k; return out; } public static function conjugate(q : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = q._r; out._i = - q._i; out._j = - q._j; out._k = - q._k; return out; } public static function square(q : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); var tmp : Number = 2 * q._r; out._r = q._r * q._r - (q._i * q._i + q._j * q._j + q._k * q._k); out._i = tmp * q._i; out._j = tmp * q._j; out._k = tmp * q._k; return out; } public static function invert(q : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); var tmp : Number = Quaternion.norm(q); out._r = q._r / tmp; out._i = - q._i / tmp; out._j = - q._j / tmp; out._k = - q._k / tmp; return out; } public function Quaternion(r : Number = 0, i : Number = 0, j : Number = 0, k : Number = 0) { _r = r; _i = i; _j = j; _k = k; } public function isEqual(q : Quaternion) : Boolean { return Quaternion.isEqual(this, q); } public function isNotEqual(q : Quaternion) : Boolean { return Quaternion.isNotEqual(this, q); } public function substract(q : Quaternion) : Quaternion { return Quaternion.substract(this, q, this); } public function add(q : Quaternion) : Quaternion { return Quaternion.add(this, q, this); } public function multiplyScalar(f : Number) : Quaternion { return Quaternion.multiplyScalar(this, f, this); } public function multiply(q : Quaternion) : Quaternion { return Quaternion.multiply(this, q, this); } public function divideScalar(f : Number) : Quaternion { return Quaternion.divideScalar(this, f, this); } public function divide(q : Quaternion) : Quaternion { return Quaternion.divide(this, q, this); } public function clone() : Quaternion { return Quaternion.copy(this); } public function negate() : Quaternion { return Quaternion.negate(this, this); } public function conjugate() : Quaternion { return Quaternion.conjugate(this, this); } public function square() : Quaternion { return Quaternion.square(this, this); } public function invert() : Quaternion { return Quaternion.invert(this, this); } public function toString() : String { return '[Quaternion r="' + _r + '" i="' + _i + '" j="' + _j + '" k="' + _k + '"]'; } } }
package aerys.minko.type.math { public class Quaternion { private static const TMP_QUATERNION : Quaternion = new Quaternion(); public function get r() : Number { return _r; } public function get i() : Number { return _i; } public function get j() : Number { return _j; } public function get k() : Number { return _k; } protected var _r : Number; protected var _i : Number; protected var _j : Number; protected var _k : Number; public static function isEqual(q1 : Quaternion, q2 : Quaternion) : Boolean { return q1._r == q2._r && q1._i == q2._i && q1._j == q2._j && q1._k == q2._k; } public static function isNotEqual(q1 : Quaternion, q2 : Quaternion) : Boolean { return !isEqual(q1, q2); } public static function norm(q : Quaternion) : Number { return q._r * q._r + q._i * q._i + q._j * q._j + q._k * q._k; } public static function absolute(q : Quaternion) : Number { return Math.sqrt(Quaternion.norm(q)); } public static function add(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = q1._r + q2._r; out._i = q1._i + q2._i; out._j = q1._j + q2._j; out._k = q1._k + q2._k; return out; } public static function substract(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = q1._r - q2._r; out._i = q1._i - q2._i; out._j = q1._j - q2._j; out._k = q1._k - q2._k; return out; } public static function multiplyScalar(q : Quaternion, f : Number, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = q._r * f; out._i = q._i * f; out._j = q._j * f; out._k = q._k * f; return out; } public static function multiply(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); var t0 : Number = (q1._k - q1._j) * (q2._j - q2._k); var t1 : Number = (q1._r + q1._i) * (q2._r + q2._i); var t2 : Number = (q1._r - q1._i) * (q2._j + q2._k); var t3 : Number = (q1._k + q1._j) * (q2._r - q2._i); var t4 : Number = (q1._k - q1._i) * (q2._i - q2._j); var t5 : Number = (q1._k + q1._i) * (q2._i + q2._j); var t6 : Number = (q1._r + q1._j) * (q2._r - q2._k); var t7 : Number = (q1._r - q1._j) * (q2._r + q2._k); var t8 : Number = t5 + t6 + t7; var t9 : Number = (t4 + t8) / 2; out._r = t0 + t9 - t5; out._i = t1 + t9 - t8; out._j = t2 + t9 - t7; out._k = t3 + t9 - t6; return out; } public static function divideScalar(q : Quaternion, f : Number, out : Quaternion = null) : Quaternion { return Quaternion.multiplyScalar(q, 1 / f, out); } public static function divide(q1 : Quaternion, q2 : Quaternion, out : Quaternion = null) : Quaternion { Quaternion.invert(q2, TMP_QUATERNION); Quaternion.multiply(q1, TMP_QUATERNION, out); return out; } public static function copy(q : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = q._r; out._i = q._i; out._j = q._j; out._k = q._k; return out; } public static function negate(q : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = - q._r; out._i = - q._i; out._j = - q._j; out._k = - q._k; return out; } public static function conjugate(q : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); out._r = q._r; out._i = - q._i; out._j = - q._j; out._k = - q._k; return out; } public static function square(q : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); var tmp : Number = 2 * q._r; out._r = q._r * q._r - (q._i * q._i + q._j * q._j + q._k * q._k); out._i = tmp * q._i; out._j = tmp * q._j; out._k = tmp * q._k; return out; } public static function invert(q : Quaternion, out : Quaternion = null) : Quaternion { out ||= new Quaternion(); var tmp : Number = Quaternion.norm(q); out._r = q._r / tmp; out._i = - q._i / tmp; out._j = - q._j / tmp; out._k = - q._k / tmp; return out; } public function Quaternion(r : Number = 0, i : Number = 0, j : Number = 0, k : Number = 0) { _r = r; _i = i; _j = j; _k = k; } public function isEqual(q : Quaternion) : Boolean { return Quaternion.isEqual(this, q); } public function isNotEqual(q : Quaternion) : Boolean { return Quaternion.isNotEqual(this, q); } public function substract(q : Quaternion) : Quaternion { return Quaternion.substract(this, q, this); } public function add(q : Quaternion) : Quaternion { return Quaternion.add(this, q, this); } public function multiplyScalar(f : Number) : Quaternion { return Quaternion.multiplyScalar(this, f, this); } public function multiply(q : Quaternion) : Quaternion { return Quaternion.multiply(this, q, this); } public function divideScalar(f : Number) : Quaternion { return Quaternion.divideScalar(this, f, this); } public function divide(q : Quaternion) : Quaternion { return Quaternion.divide(this, q, this); } public function clone() : Quaternion { return Quaternion.copy(this); } public function negate() : Quaternion { return Quaternion.negate(this, this); } public function conjugate() : Quaternion { return Quaternion.conjugate(this, this); } public function square() : Quaternion { return Quaternion.square(this, this); } public function invert() : Quaternion { return Quaternion.invert(this, this); } public function toString() : String { return '[Quaternion r="' + _r + '" i="' + _i + '" j="' + _j + '" k="' + _k + '"]'; } } }
Remove unused imports
Remove unused imports
ActionScript
mit
aerys/minko-as3
4b6e5f366cf88589de155a007b6e6f750e94d05e
src/org/mangui/hls/demux/DemuxHelper.as
src/org/mangui/hls/demux/DemuxHelper.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.demux { import flash.utils.ByteArray; import org.mangui.hls.model.Level; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class DemuxHelper { public static function probe(data : ByteArray, level : Level, audioselect : Function, progress : Function, complete : Function, error : Function, videometadata : Function, id3tagfound : Function, audioOnly : Boolean) : Demuxer { data.position = 0; CONFIG::LOGGING { Log.debug("probe fragment type"); } var aac_match : Boolean = AACDemuxer.probe(data); var mp3_match : Boolean = MP3Demuxer.probe(data); var ts_match : Boolean = TSDemuxer.probe(data); CONFIG::LOGGING { Log.debug("AAC/MP3/TS match:" + aac_match + "/" + mp3_match + "/" + ts_match); } /* prioritize level info : * if ts_match && codec_avc => TS demuxer * if aac_match && codec_aac => AAC demuxer * if mp3_match && codec_mp3 => MP3 demuxer * if no codec info in Manifest, use fallback order : AAC/MP3/TS */ if (ts_match && level.codec_h264) { CONFIG::LOGGING { Log.debug("TS match + H264 signaled in Manifest, use TS demuxer"); } return new TSDemuxer(audioselect, progress, complete, error, videometadata, audioOnly); } else if (aac_match && level.codec_aac) { CONFIG::LOGGING { Log.debug("AAC match + AAC signaled in Manifest, use AAC demuxer"); } return new AACDemuxer(audioselect, progress, complete, error, id3tagfound); } else if (mp3_match && level.codec_mp3) { CONFIG::LOGGING { Log.debug("MP3 match + MP3 signaled in Manifest, use MP3 demuxer"); } return new MP3Demuxer(audioselect, progress, complete, error, id3tagfound); } else if (aac_match) { return new AACDemuxer(audioselect, progress, complete, error, id3tagfound); } else if (mp3_match) { return new MP3Demuxer(audioselect, progress, complete, error, id3tagfound); } else if (ts_match) { return new TSDemuxer(audioselect, progress, complete, error, videometadata, audioOnly); } else { CONFIG::LOGGING { Log.debug("probe fails"); } return null; } } } }
/* 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.demux { import flash.utils.ByteArray; import org.mangui.hls.model.Level; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } public class DemuxHelper { public static function probe(data : ByteArray, level : Level, audioselect : Function, progress : Function, complete : Function, error : Function, videometadata : Function, id3tagfound : Function, audioOnly : Boolean) : Demuxer { data.position = 0; CONFIG::LOGGING { Log.debug("probe fragment type"); } var aac_match : Boolean = AACDemuxer.probe(data); var mp3_match : Boolean = MP3Demuxer.probe(data); var ts_match : Boolean = TSDemuxer.probe(data); CONFIG::LOGGING { Log.debug("AAC/MP3/TS match:" + aac_match + "/" + mp3_match + "/" + ts_match); } /* prioritize level info : * if ts_match && codec_avc => TS demuxer * if aac_match && codec_aac => AAC demuxer * if mp3_match && codec_mp3 => MP3 demuxer * if no codec info in Manifest, use fallback order : AAC/MP3/TS */ if (ts_match && level && level.codec_h264) { CONFIG::LOGGING { Log.debug("TS match + H264 signaled in Manifest, use TS demuxer"); } return new TSDemuxer(audioselect, progress, complete, error, videometadata, audioOnly); } else if (aac_match && level && level.codec_aac) { CONFIG::LOGGING { Log.debug("AAC match + AAC signaled in Manifest, use AAC demuxer"); } return new AACDemuxer(audioselect, progress, complete, error, id3tagfound); } else if (mp3_match && level && level.codec_mp3) { CONFIG::LOGGING { Log.debug("MP3 match + MP3 signaled in Manifest, use MP3 demuxer"); } return new MP3Demuxer(audioselect, progress, complete, error, id3tagfound); } else if (aac_match) { return new AACDemuxer(audioselect, progress, complete, error, id3tagfound); } else if (mp3_match) { return new MP3Demuxer(audioselect, progress, complete, error, id3tagfound); } else if (ts_match) { return new TSDemuxer(audioselect, progress, complete, error, videometadata, audioOnly); } else { CONFIG::LOGGING { Log.debug("probe fails"); } return null; } } } }
Make probe Level parameter optional
[Mangui.DemuxHelper] Make probe Level parameter optional Selection logic ensures proper Demuxer is used anyway
ActionScript
mpl-2.0
codex-corp/flashls,codex-corp/flashls
b34e47baa39e7dc2d250a947fa1f640cff2d665b
WeaveJS/src/weavejs/data/column/StringColumn.as
WeaveJS/src/weavejs/data/column/StringColumn.as
/* ***** BEGIN LICENSE BLOCK ***** * * This file is part of Weave. * * The Initial Developer of Weave is the Institute for Visualization * and Perception Research at the University of Massachusetts Lowell. * Portions created by the Initial Developer are Copyright (C) 2008-2015 * the Initial Developer. All Rights Reserved. * * 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/. * * ***** END LICENSE BLOCK ***** */ package weavejs.data.column { import weavejs.WeaveAPI; import weavejs.api.data.Aggregation; import weavejs.api.data.ColumnMetadata; import weavejs.api.data.DataType; import weavejs.api.data.IBaseColumn; import weavejs.api.data.IPrimitiveColumn; import weavejs.api.data.IQualifiedKey; import weavejs.util.AsyncSort; import weavejs.util.Dictionary2D; import weavejs.util.JS; import weavejs.util.StandardLib; /** * @author adufilie */ public class StringColumn extends AbstractAttributeColumn implements IPrimitiveColumn, IBaseColumn { public function StringColumn(metadata:Object = null) { super(metadata); dataTask = new ColumnDataTask(this, filterStringValue, handleDataTaskComplete); dataCache = new Dictionary2D(); Weave.getCallbacks(_asyncSort).addImmediateCallback(this, handleSortComplete); } override public function getMetadata(propertyName:String):String { var value:String = super.getMetadata(propertyName); if (!value && propertyName == ColumnMetadata.DATA_TYPE) return DataType.STRING; return value; } /** * Sorted list of unique string values. */ private var _uniqueStrings:Array = []; /** * String -> index in sorted _uniqueStrings */ private var _uniqueStringLookup:Object; public function setRecords(keys:Array, stringData:Array):void { dataTask.begin(keys, stringData); _asyncSort.abort(); _uniqueStrings.length = 0; _uniqueStringLookup = {}; _stringToNumberFunction = null; _numberToStringFunction = null; // compile the number format function from the metadata var numberFormat:String = getMetadata(ColumnMetadata.NUMBER); if (numberFormat) { try { _stringToNumberFunction = JS.compile(numberFormat, [ColumnMetadata.STRING, 'array'], errorHandler); } catch (e:Error) { JS.error(e); } } // compile the string format function from the metadata var stringFormat:String = getMetadata(ColumnMetadata.STRING); if (stringFormat) { try { _numberToStringFunction = JS.compile(stringFormat, [ColumnMetadata.NUMBER], errorHandler); } catch (e:Error) { JS.error(e); } } } private function errorHandler(e:*):void { var str:String = e is Error ? e.message : String(e); str = StandardLib.substitute("Error in script for AttributeColumn {0}:\n{1}", Weave.stringify(_metadata), str); if (_lastError != str) { _lastError = str; JS.error(e); } } private var _lastError:String; // variables that do not get reset after async task private var _stringToNumberFunction:Function = null; private var _numberToStringFunction:Function = null; private function filterStringValue(value:String):Boolean { if (!value) return false; // keep track of unique strings if (_uniqueStringLookup[value] === undefined) { _uniqueStrings.push(value); // initialize mapping _uniqueStringLookup[value] = -1; } return true; } private function handleDataTaskComplete():void { // begin sorting unique strings previously listed _asyncSort.beginSort(_uniqueStrings, AsyncSort.compareCaseInsensitive); } private var _asyncSort:AsyncSort = Weave.disposableChild(this, AsyncSort); private function handleSortComplete():void { if (!_asyncSort.result) return; _i = 0; _numberToString = {}; // high priority because not much can be done without data WeaveAPI.Scheduler.startTask(this, _iterate, WeaveAPI.TASK_PRIORITY_HIGH, asyncComplete); } private var _i:int; private var _numberToString:Object = {}; private var _stringToNumber:Object = {}; private function _iterate(stopTime:int):Number { for (; _i < _uniqueStrings.length; _i++) { if (JS.now() > stopTime) return _i / _uniqueStrings.length; var string:String = _uniqueStrings[_i]; _uniqueStringLookup[string] = _i; if (_stringToNumberFunction != null) { var number:Number = StandardLib.asNumber(_stringToNumberFunction(string)); _stringToNumber[string] = number; _numberToString[number] = string; } } return 1; } private function asyncComplete():void { // cache needs to be cleared after async task completes because some values may have been cached while the task was busy dataCache = new Dictionary2D(); triggerCallbacks(); } // find the closest string value at a given normalized value public function deriveStringFromNumber(number:Number):String { if (_metadata && _metadata[ColumnMetadata.NUMBER]) { if (_numberToString.hasOwnProperty(number)) return _numberToString[number]; if (_numberToStringFunction != null) return _numberToString[number] = StandardLib.asString(_numberToStringFunction(number)); } else if (number == int(number) && 0 <= number && number < _uniqueStrings.length) { return _uniqueStrings[int(number)]; } return ''; } override protected function generateValue(key:IQualifiedKey, dataType:Class):Object { var array:Array = dataTask.map_key_arrayData.get(key); if (dataType === String) return aggregate(array, _metadata ? _metadata[ColumnMetadata.AGGREGATION] : null) || ''; var string:String = getValueFromKey(key, String); if (dataType === Number) { if (_stringToNumberFunction != null) return Number(_stringToNumber[string]); return Number(_uniqueStringLookup[string]); } if (dataType === IQualifiedKey) { var type:String = _metadata ? _metadata[ColumnMetadata.DATA_TYPE] : null; if (!type) type = DataType.STRING; return WeaveAPI.QKeyManager.getQKey(type, string); } return null; } /** * Aggregates an Array of Strings into a single String. * @param strings An Array of Strings. * @param aggregation One of the constants in weave.api.data.Aggregation. * @return An aggregated String. * @see weave.api.data.Aggregation */ public static function aggregate(strings:Array, aggregation:String):String { if (!strings) return undefined; if (!aggregation) aggregation = Aggregation.DEFAULT; switch (aggregation) { default: case Aggregation.SAME: var first:String = strings[0]; for each (var value:String in strings) if (value != first) return Weave.lang(Aggregation.AMBIGUOUS_DATA); return first; case Aggregation.FIRST: return strings[0]; case Aggregation.LAST: return strings[strings.length - 1]; } return null; } public static function getSupportedAggregationModes():Array { return [Aggregation.SAME, Aggregation.FIRST, Aggregation.LAST]; } } }
/* ***** BEGIN LICENSE BLOCK ***** * * This file is part of Weave. * * The Initial Developer of Weave is the Institute for Visualization * and Perception Research at the University of Massachusetts Lowell. * Portions created by the Initial Developer are Copyright (C) 2008-2015 * the Initial Developer. All Rights Reserved. * * 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/. * * ***** END LICENSE BLOCK ***** */ package weavejs.data.column { import weavejs.WeaveAPI; import weavejs.api.data.Aggregation; import weavejs.api.data.ColumnMetadata; import weavejs.api.data.DataType; import weavejs.api.data.IBaseColumn; import weavejs.api.data.IPrimitiveColumn; import weavejs.api.data.IQualifiedKey; import weavejs.util.AsyncSort; import weavejs.util.Dictionary2D; import weavejs.util.JS; import weavejs.util.StandardLib; /** * @author adufilie */ public class StringColumn extends AbstractAttributeColumn implements IPrimitiveColumn, IBaseColumn { public function StringColumn(metadata:Object = null) { super(metadata); dataTask = new ColumnDataTask(this, filterStringValue, handleDataTaskComplete); dataCache = new Dictionary2D(); Weave.getCallbacks(_asyncSort).addImmediateCallback(this, handleSortComplete); } override public function getMetadata(propertyName:String):String { var value:String = super.getMetadata(propertyName); if (!value && propertyName == ColumnMetadata.DATA_TYPE) return DataType.STRING; return value; } /** * Sorted list of unique string values. */ private var _uniqueStrings:Array = []; /** * String -> index in sorted _uniqueStrings */ private var _uniqueStringLookup:Object = new JS.Map(); public function setRecords(keys:Array, stringData:Array):void { dataTask.begin(keys, stringData); _asyncSort.abort(); _uniqueStrings.length = 0; _uniqueStringLookup.clear(); _stringToNumberFunction = null; _numberToStringFunction = null; // compile the number format function from the metadata var numberFormat:String = getMetadata(ColumnMetadata.NUMBER); if (numberFormat) { try { _stringToNumberFunction = JS.compile(numberFormat, [ColumnMetadata.STRING, 'array'], errorHandler); } catch (e:Error) { JS.error(e); } } // compile the string format function from the metadata var stringFormat:String = getMetadata(ColumnMetadata.STRING); if (stringFormat) { try { _numberToStringFunction = JS.compile(stringFormat, [ColumnMetadata.NUMBER], errorHandler); } catch (e:Error) { JS.error(e); } } } private function errorHandler(e:*):void { var str:String = e is Error ? e.message : String(e); str = StandardLib.substitute("Error in script for AttributeColumn {0}:\n{1}", Weave.stringify(_metadata), str); if (_lastError != str) { _lastError = str; JS.error(e); } } private var _lastError:String; // variables that do not get reset after async task private var _stringToNumberFunction:Function = null; private var _numberToStringFunction:Function = null; private function filterStringValue(value:String):Boolean { if (!value) return false; // keep track of unique strings if (!_uniqueStringLookup.has(value)) { _uniqueStrings.push(value); // initialize mapping _uniqueStringLookup.set(value, -1); } return true; } private function handleDataTaskComplete():void { // begin sorting unique strings previously listed _asyncSort.beginSort(_uniqueStrings, AsyncSort.compareCaseInsensitive); } private var _asyncSort:AsyncSort = Weave.disposableChild(this, AsyncSort); private function handleSortComplete():void { if (!_asyncSort.result) return; _i = 0; _numberToString = {}; // high priority because not much can be done without data WeaveAPI.Scheduler.startTask(this, _iterate, WeaveAPI.TASK_PRIORITY_HIGH, asyncComplete); } private var _i:int; private var _numberToString:Object = {}; private var _stringToNumber:Object = {}; private function _iterate(stopTime:int):Number { for (; _i < _uniqueStrings.length; _i++) { if (JS.now() > stopTime) return _i / _uniqueStrings.length; var string:String = _uniqueStrings[_i]; _uniqueStringLookup.set(string, _i); if (_stringToNumberFunction != null) { var number:Number = StandardLib.asNumber(_stringToNumberFunction(string)); _stringToNumber[string] = number; _numberToString[number] = string; } } return 1; } private function asyncComplete():void { // cache needs to be cleared after async task completes because some values may have been cached while the task was busy dataCache = new Dictionary2D(); triggerCallbacks(); } // find the closest string value at a given normalized value public function deriveStringFromNumber(number:Number):String { if (_metadata && _metadata[ColumnMetadata.NUMBER]) { if (_numberToString.hasOwnProperty(number)) return _numberToString[number]; if (_numberToStringFunction != null) return _numberToString[number] = StandardLib.asString(_numberToStringFunction(number)); } else if (number == int(number) && 0 <= number && number < _uniqueStrings.length) { return _uniqueStrings[int(number)]; } return ''; } override protected function generateValue(key:IQualifiedKey, dataType:Class):Object { var array:Array = dataTask.map_key_arrayData.get(key); if (dataType === String) return aggregate(array, _metadata ? _metadata[ColumnMetadata.AGGREGATION] : null) || ''; var string:String = getValueFromKey(key, String); if (dataType === Number) { if (_stringToNumberFunction != null) return Number(_stringToNumber[string]); return Number(_uniqueStringLookup.get(string)); } if (dataType === IQualifiedKey) { var type:String = _metadata ? _metadata[ColumnMetadata.DATA_TYPE] : null; if (!type) type = DataType.STRING; return WeaveAPI.QKeyManager.getQKey(type, string); } return null; } /** * Aggregates an Array of Strings into a single String. * @param strings An Array of Strings. * @param aggregation One of the constants in weave.api.data.Aggregation. * @return An aggregated String. * @see weave.api.data.Aggregation */ public static function aggregate(strings:Array, aggregation:String):String { if (!strings) return undefined; if (!aggregation) aggregation = Aggregation.DEFAULT; switch (aggregation) { default: case Aggregation.SAME: var first:String = strings[0]; for each (var value:String in strings) if (value != first) return Weave.lang(Aggregation.AMBIGUOUS_DATA); return first; case Aggregation.FIRST: return strings[0]; case Aggregation.LAST: return strings[strings.length - 1]; } return null; } public static function getSupportedAggregationModes():Array { return [Aggregation.SAME, Aggregation.FIRST, Aggregation.LAST]; } } }
Change StringColumn to use Map instead of Object
Change StringColumn to use Map instead of Object
ActionScript
mpl-2.0
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
ff22389a15abfe58ad0b5172ad875ed6571a1565
exporter/src/main/as/flump/export/BetwixtPublisher.as
exporter/src/main/as/flump/export/BetwixtPublisher.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import flump.bytesToXML; import flump.xfl.XflLibrary; import flump.xfl.XflMovie; import com.threerings.util.Log; public class BetwixtPublisher { public static function modified (lib :XflLibrary, metadata :File) :Boolean { if (!metadata.exists) return true; var stream :FileStream = new FileStream(); stream.open(metadata, FileMode.READ); var bytes :ByteArray = new ByteArray(); stream.readBytes(bytes); var md5 :String = null; switch (Files.getExtension(metadata)) { case "xml": var xml :XML = bytesToXML(bytes); md5 = xml.@md5; break; case "json": var json :Object = JSON.parse(bytes.readUTFBytes(bytes.length)); md5 = json.md5; break; } return md5 != lib.md5; } public static function publish (lib :XflLibrary, source: File, authoredDevice :DeviceType, exportDir :File) :void { var packers :Array = [ new Packer(DeviceType.IPHONE_RETINA, authoredDevice, lib), new Packer(DeviceType.IPHONE, authoredDevice, lib) ]; const destDir :File = exportDir.resolvePath(lib.location); destDir.createDirectory(); for each (var packer :Packer in packers) { for each (var atlas :Atlas in packer.atlases) { atlas.publish(exportDir); } } publishMetadata(lib, packers, authoredDevice, destDir.resolvePath("resources.xml")); publishMetadata(lib, packers, authoredDevice, destDir.resolvePath("resources.json")); } protected static function publishMetadata (lib :XflLibrary, packers :Array, authoredDevice :DeviceType, dest :File) :void { var out :FileStream = new FileStream(); out.open(dest, FileMode.WRITE); switch (Files.getExtension(dest)) { case "xml": var xml :XML = <resources md5={lib.md5}/>; var prefix :String = lib.location.replace("/", "_") + "_"; for each (var movie :XflMovie in lib.movies) { var movieXml :XML = movie.toXML(); movieXml.@authoredDevice = authoredDevice.name(); movieXml.@name = prefix + movieXml.@name; xml.appendChild(movieXml); } var groupsXml :XML = <textureGroups/>; xml.appendChild(groupsXml); for each (var packer :Packer in packers) { var groupXml :XML = <textureGroup target={packer.targetDevice}/>; groupsXml.appendChild(groupXml); for each (var atlas :Atlas in packer.atlases) { groupXml.appendChild(atlas.toXML()); } } for each (var texture :XML in groupsXml..texture) { texture.@name = prefix + texture.@name; } out.writeUTFBytes(xml.toString()); break; case "json": var json :Object = { md5: lib.md5, movies: lib.movies, atlases: packers[0].atlases }; var pretty :Boolean = false; out.writeUTFBytes(JSON.stringify(json, null, pretty ? " " : null)); break; } out.close(); } private static const log :Log = Log.getLog(BetwixtPublisher); } }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.filesystem.File; import flash.filesystem.FileMode; import flash.filesystem.FileStream; import flash.utils.ByteArray; import flump.bytesToXML; import flump.xfl.XflLibrary; import flump.xfl.XflMovie; import com.threerings.util.Log; public class BetwixtPublisher { public static function modified (lib :XflLibrary, metadata :File) :Boolean { if (!metadata.exists) return true; var stream :FileStream = new FileStream(); stream.open(metadata, FileMode.READ); var bytes :ByteArray = new ByteArray(); stream.readBytes(bytes); var md5 :String = null; switch (Files.getExtension(metadata)) { case "xml": var xml :XML = bytesToXML(bytes); md5 = xml.@md5; break; case "json": var json :Object = JSON.parse(bytes.readUTFBytes(bytes.length)); md5 = json.md5; break; } return md5 != lib.md5; } public static function publish (lib :XflLibrary, source: File, authoredDevice :DeviceType, exportDir :File) :void { var packers :Array = [ new Packer(DeviceType.IPHONE_RETINA, authoredDevice, lib), new Packer(DeviceType.IPHONE, authoredDevice, lib) ]; const destDir :File = exportDir.resolvePath(lib.location); destDir.createDirectory(); for each (var packer :Packer in packers) { for each (var atlas :Atlas in packer.atlases) { atlas.publish(exportDir); } } publishMetadata(lib, packers, authoredDevice, destDir.resolvePath("resources.xml")); publishMetadata(lib, packers, authoredDevice, destDir.resolvePath("resources.json")); } protected static function publishMetadata (lib :XflLibrary, packers :Array, authoredDevice :DeviceType, dest :File) :void { var out :FileStream = new FileStream(); out.open(dest, FileMode.WRITE); switch (Files.getExtension(dest)) { case "xml": var xml :XML = <resources md5={lib.md5}/>; var prefix :String = lib.location + "/"; for each (var movie :XflMovie in lib.movies) { var movieXml :XML = movie.toXML(); movieXml.@authoredDevice = authoredDevice.name(); movieXml.@name = prefix + movieXml.@name; for each (var kf :XML in movieXml..kf) { kf.@ref = prefix + kf.@ref; } xml.appendChild(movieXml); } var groupsXml :XML = <textureGroups/>; xml.appendChild(groupsXml); for each (var packer :Packer in packers) { var groupXml :XML = <textureGroup target={packer.targetDevice}/>; groupsXml.appendChild(groupXml); for each (var atlas :Atlas in packer.atlases) { groupXml.appendChild(atlas.toXML()); } } for each (var texture :XML in groupsXml..texture) { texture.@name = prefix + texture.@name; } out.writeUTFBytes(xml.toString()); break; case "json": var json :Object = { md5: lib.md5, movies: lib.movies, atlases: packers[0].atlases }; var pretty :Boolean = false; out.writeUTFBytes(JSON.stringify(json, null, pretty ? " " : null)); break; } out.close(); } private static const log :Log = Log.getLog(BetwixtPublisher); } }
Use slashes for prefixes, and prefix symbol references too.
Use slashes for prefixes, and prefix symbol references too.
ActionScript
mit
funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump
17ba90dbadd06728693a2a79118ac00bbc4e88e6
src/net/manaca/loaderqueue/LoaderProgress.as
src/net/manaca/loaderqueue/LoaderProgress.as
package net.manaca.loaderqueue { import flash.events.Event; import flash.events.EventDispatcher; import flash.utils.clearInterval; import flash.utils.setInterval; /** * 任务队列总进度更新时派发 * @eventType flash.events.Event.CHANGE */ [Event(name="change", type="flash.events.Event")] /** * 任务队列完成时派发 * @eventType flash.events.Event.COMPLETE */ [Event(name="complete", type="flash.events.Event")] /** * 用于计算一个加载集合和总进度. * @author Sean Zou * */ public class LoaderProgress extends EventDispatcher { //========================================================================== // Constructor //========================================================================== /** * 构造函数. * */ public function LoaderProgress() { } //========================================================================== // Variables //========================================================================== private var items:Array = []; private var isStart:Boolean = false; private var updateInterval:int; //========================================================================== // Properties //========================================================================== private var _totalProgress:Number; /** * 总进度 * @return * */ public function get totalProgress():Number { return _totalProgress; } //========================================================================== // Methods //========================================================================== /** * 添加一个需要计算的下载对象 * @param loaderAdapter * */ public function addItem(loaderAdapter:ILoaderAdapter):void { if(items.indexOf(loaderAdapter) == -1) { items.push(loaderAdapter); if(isStart) { update(); } } } /** * 删除一个需要计算的下载对象 * @param loaderAdapter * */ public function removeItem(loaderAdapter:ILoaderAdapter):void { var index:int = items.indexOf(loaderAdapter); if(index != -1) { items.splice(index, 1); if(isStart) { update(); } } } /** * 开始计算 * */ public function start():void { updateInterval = setInterval(update, 100); isStart = true; } /** * 结束计算 * */ public function stop():void { clearInterval(updateInterval); isStart = false; } /** * 销毁该对象 * */ public function dispose():void { stop(); items = null; } /** * 更新进度 * @private */ private function update():void { var itemsLen:int = items.length; var loader:ILoaderAdapter; var tp:Number = 0; for (var i:int = 0; i < itemsLen; i++) { loader = items[i]; if(!isNaN(loader.bytesLoaded / loader.bytesTotal)) { tp += loader.bytesLoaded / loader.bytesTotal; } } _totalProgress = tp / itemsLen; dispatchEvent(new Event(Event.CHANGE)); if(_totalProgress == 1 || itemsLen == 0) { dispatchEvent(new Event(Event.COMPLETE)); stop(); } } } }
package net.manaca.loaderqueue { import flash.events.Event; import flash.events.EventDispatcher; import flash.utils.clearInterval; import flash.utils.setInterval; /** * 任务队列总进度更新时派发 * @eventType flash.events.Event.CHANGE */ [Event(name="change", type="flash.events.Event")] /** * 任务队列完成时派发 * @eventType flash.events.Event.COMPLETE */ [Event(name="complete", type="flash.events.Event")] /** * 用于计算一个加载集合和总进度. * @author Sean Zou * */ public class LoaderProgress extends EventDispatcher { //========================================================================== // Constructor //========================================================================== /** * 构造函数. * */ public function LoaderProgress() { } //========================================================================== // Variables //========================================================================== private var items:Array = []; private var isStarted:Boolean = false; private var updateInterval:int; //========================================================================== // Properties //========================================================================== private var _totalProgress:Number; /** * 总进度 * @return * */ public function get totalProgress():Number { return _totalProgress; } //========================================================================== // Methods //========================================================================== /** * 添加一个需要计算的下载对象 * @param loaderAdapter * */ public function addItem(loaderAdapter:ILoaderAdapter):void { if(items.indexOf(loaderAdapter) == -1) { items.push(loaderAdapter); if(isStarted) { update(); } } } /** * 删除一个需要计算的下载对象 * @param loaderAdapter * */ public function removeItem(loaderAdapter:ILoaderAdapter):void { var index:int = items.indexOf(loaderAdapter); if(index != -1) { items.splice(index, 1); if(isStarted) { update(); } } } /** * 开始计算 * */ public function start():void { updateInterval = setInterval(update, 100); isStarted = true; } /** * 结束计算 * */ public function stop():void { clearInterval(updateInterval); isStarted = false; } /** * 销毁该对象 * */ public function dispose():void { stop(); items = null; } /** * 更新进度 * @private */ private function update():void { var itemsLen:int = items.length; var loader:ILoaderAdapter; var tp:Number = 0; for (var i:int = 0; i < itemsLen; i++) { loader = items[i]; if(!isNaN(loader.bytesLoaded / loader.bytesTotal)) { tp += loader.bytesLoaded / loader.bytesTotal; } } _totalProgress = tp / itemsLen; dispatchEvent(new Event(Event.CHANGE)); if(_totalProgress == 1 || itemsLen == 0) { dispatchEvent(new Event(Event.COMPLETE)); stop(); } } } }
Rename isStart to isStarted
Rename isStart to isStarted
ActionScript
mit
wersling/LoaderQueue
c85996ae5d6282efdb07c025837ba0ccf82786da
src/as/com/threerings/util/Name.as
src/as/com/threerings/util/Name.as
package com.threerings.util { import com.threerings.util.Equalable; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamable; public class Name extends Object implements Comparable, Hashable, Streamable { public function Name (name :String = "") { _name = name; } public function getNormal () :String { if (_normal == null) { _normal = normalize(_name); if (_normal === _name) { _normal = _name; } } return _normal; } public function isValid () :Boolean { return !isBlank(); } public function isBlank () :Boolean { return Name.isBlank(this); } public function toString () :String { return _name; } // from interface Hashable public function equals (other :Object) :Boolean { return (ClassUtil.getClass(other) == Name) && (getNormal() === (other as Name).getNormal()); } // from interface Hashable public function hashCode () :int { return StringUtil.hashCode(getNormal()); } // from interface Comparable public function compareTo (other :Object) :int { var thisNormal :String = getNormal(); var thatNormal :String = (other as Name).getNormal(); return thisNormal.localeCompare(thatNormal); } // from interface Streamable public function writeObject (out :ObjectOutputStream) :void //throws IOError { out.writeField(_name); } // from interface Streamable public function readObject (ins :ObjectInputStream) :void //throws IOError { _name = (ins.readField(String) as String); } protected function normalize (txt :String) :String { return txt.toLowerCase(); } public static function isBlank (name :Name) :Boolean { return (name == null || "" === name.toString()); } /** The raw name text. */ protected var _name :String; /** The normalized name text. */ protected var _normal :String; } }
package com.threerings.util { import com.threerings.util.Equalable; import com.threerings.io.ObjectInputStream; import com.threerings.io.ObjectOutputStream; import com.threerings.io.Streamable; public class Name extends Object implements Comparable, Hashable, Streamable { public function Name (name :String = "") { _name = name; } public function getNormal () :String { if (_normal == null) { _normal = normalize(_name); if (_normal === _name) { _normal = _name; } } return _normal; } public function isValid () :Boolean { return !isBlank(); } public function isBlank () :Boolean { return Name.isBlank(this); } public function toString () :String { return _name; } // from interface Hashable public function equals (other :Object) :Boolean { return (other != null) && // this is a check to see if they are the same class (other.constructor == Object(this).constructor) && (getNormal() === (other as Name).getNormal()); } // from interface Hashable public function hashCode () :int { return StringUtil.hashCode(getNormal()); } // from interface Comparable public function compareTo (other :Object) :int { var thisNormal :String = getNormal(); var thatNormal :String = (other as Name).getNormal(); return thisNormal.localeCompare(thatNormal); } // from interface Streamable public function writeObject (out :ObjectOutputStream) :void //throws IOError { out.writeField(_name); } // from interface Streamable public function readObject (ins :ObjectInputStream) :void //throws IOError { _name = (ins.readField(String) as String); } protected function normalize (txt :String) :String { return txt.toLowerCase(); } public static function isBlank (name :Name) :Boolean { return (name == null || "" === name.toString()); } /** The raw name text. */ protected var _name :String; /** The normalized name text. */ protected var _normal :String; } }
Check that the other name is the same subclass of Name, not just a Name. (And found a faster way to compare the classes of two objects.)
Check that the other name is the same subclass of Name, not just a Name. (And found a faster way to compare the classes of two objects.) git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4321 542714f4-19e9-0310-aa3c-eee0fc999fb1
ActionScript
lgpl-2.1
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
36665dfe40b184c7e4302972364494b8dbb54ed3
src/com/rails2u/debug/Benchmark.as
src/com/rails2u/debug/Benchmark.as
package com.rails2u.debug { import flash.utils.Dictionary; import flash.events.Event; import flash.utils.getTimer; /** * Simple Benchmark class * * example: * <listing version="3.0"> * Benchmark.start('check'); * // code * Benchmark.end('check'); * </listing> * * <listing version="3.0"> * Benchmark.benchmark('check2', function() { * // code * }, this); * </listing> */ public class Benchmark { private static var dict:Object = {}; public static function start(name:String):void { dict[name] = getTimer(); } public static function benchmark(name:String, callback:Function, bindObject:Object = null):Number { start(name); callback.call(bindObject); return end(name); } public static function loop(name:String, callback:Function, bindObject:Object = null, times:uint = 100):Number { start(name); for (var i:uint = 0; i < times; i++) callback.call(bindObject); return end(name); } public static function end(name:String):Number { var re:uint = getTimer() - dict[name]; log(name + ':' + ' ' + re + 'ms'); return re; } } }
package com.rails2u.debug { import flash.utils.Dictionary; import flash.events.Event; import flash.utils.getTimer; /** * Simple Benchmark class * * example: * <listing version="3.0"> * Benchmark.start('check'); * // code * Benchmark.end('check'); * </listing> * * <listing version="3.0"> * Benchmark.benchmark('check2', function() { * // code * }, this); * </listing> */ public class Benchmark { private static var dict:Object = {}; public static function start(name:String):void { dict[name] = getTimer(); } public static function benchmark(name:String, callback:Function, bindObject:Object = null, times:uint = 1):Number { start(name); for (var i:uint = 0; i < times; i++) callback.call(bindObject); return end(name); } public static function end(name:String):Number { var re:uint = getTimer() - dict[name]; log(name + ':' + ' ' + re + 'ms'); return re; } } }
remove loop method
remove loop method git-svn-id: 864080e30cc358c5edb906449bbf014f90258007@43 96db6a20-122f-0410-8d9f-89437bbe4005
ActionScript
mit
hotchpotch/as3rails2u,hotchpotch/as3rails2u
c77aa926c01e2cb6d544fe00ba9dc7a564c031d0
flash/src/org/flashsocket/utils/SHA1.as
flash/src/org/flashsocket/utils/SHA1.as
package org.flashsocket.utils { import flash.utils.ByteArray; public class SHA1 { public static function hash(input:String):String { var inputLength:int = input.length; // Number of 8-bit bytes to represent the 512-bit blocks var numberOfBytes:int = (inputLength + 9) + ((55 - inputLength) & 0x3f); // Number of 512-bit blocks required var numberOfBlocks:int = numberOfBytes >> 6; // Convert input String to ByteArray var bytes:ByteArray = StringUtil.toBytes(input); // Insert the first padding bit "1" right after the message bytes.writeByte(0x80); // Insert the message length as the last 8 bytes bytes.position = numberOfBytes - 8; bytes.writeUnsignedInt(inputLength >>> 29); bytes.writeUnsignedInt(inputLength << 3); bytes.position = 0; // Compute the Message Digest // algorithm based on the C code demonstration shown at // http://www.faqs.org/rfcs/rfc3174.html var H0:int = 0x67452301; var H1:int = 0xefcdab89; var H2:int = 0x98badcfe; var H3:int = 0x10325476; var H4:int = 0xc3d2e1f0; var W:Array = new Array(80); var temp:int; var A:int; var B:int; var C:int; var D:int; var E:int; var t:int; while (numberOfBlocks--) { A = H0; B = H1; C = H2; D = H3; E = H4; for (t = 0; t < 16; t++) { W[t] = bytes.readUnsignedInt(); } for (t = 16; t < 80; t++) { temp = int(W[t - 3]) ^ int(W[t - 8]) ^ int(W[t - 14]) ^ int(W[t - 16]); W[t] = (temp << 1) | (temp >>> 31); } for (t = 0; t < 20; t++) { temp = ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + E + int(W[t]) + 0x5a827999; E = D; D = C; C = (B << 30) | (B >>> 2); B = A; A = temp; } for (t = 20; t < 40; t++) { temp = ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + E + int(W[t]) + 0x6ed9eba1; E = D; D = C; C = (B << 30) | (B >>> 2); B = A; A = temp; } for (t = 40; t < 60; t++) { temp = ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + E + int(W[t]) + 0x8f1bbcdc; E = D; D = C; C = (B << 30) | (B >>> 2); B = A; A = temp; } for (t = 60; t < 80; t++) { temp = ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + E + int(W[t]) + 0xca62c1d6; E = D; D = C; C = (B << 30) | (B >>> 2); B = A; A = temp; } H0 += A; H1 += B; H2 += C; H3 += D; H4 += E; } return String.fromCharCode( H0 >> 24 & 0xff, H0 >> 16 & 0xff, H0 >> 8 & 0xff, H0 & 0xff, H1 >> 24 & 0xff, H1 >> 16 & 0xff, H1 >> 8 & 0xff, H1 & 0xff, H2 >> 24 & 0xff, H2 >> 16 & 0xff, H2 >> 8 & 0xff, H2 & 0xff, H3 >> 24 & 0xff, H3 >> 16 & 0xff, H3 >> 8 & 0xff, H3 & 0xff, H4 >> 24 & 0xff, H4 >> 16 & 0xff, H4 >> 8 & 0xff, H4 & 0xff ); } public static function test():void { var tests:Array = [ "abc", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "a", "0123456701234567012345670123456701234567012345670123456701234567" ]; var results:Array = [ "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D", "84 98 3E 44 1C 3B D2 6E BA AE 4A A1 F9 51 29 E5 E5 46 70 F1", "86 F7 E4 37 FA A5 A7 FC E1 5D 1D DC B9 EA EA EA 37 76 67 B8", "E0 C0 94 E8 67 EF 46 C3 50 EF 54 A7 F5 9D D6 0B ED 92 AE 83" ]; for (var t:int = 0; t < tests.length; t++) { trace("Test " + (t + 1) + ": " + tests[t]); trace("expected: " + results[t]); var hashed:String = hash(tests[t]); var hex:Array = []; for (var h:int = 0; h < hashed.length; h++) { hex.push((0x100 + hashed.charCodeAt(h)).toString(16).replace('1', '').toUpperCase()); } var result:String = hex.join(" "); trace("result: " + result); trace("correct: " + (result === results[t])); trace(); } } } }
package org.flashsocket.utils { import flash.utils.ByteArray; public class SHA1 { public static function hash(input:String):String { var inputLength:int = input.length; // Number of 8-bit bytes to represent the 512-bit blocks var numberOfBytes:int = (inputLength + 9) + ((55 - inputLength) & 0x3f); // Number of 512-bit blocks required var numberOfBlocks:int = numberOfBytes >> 6; // Convert input String to ByteArray var bytes:ByteArray = StringUtil.toBytes(input); // Insert the first padding bit "1" right after the message bytes.writeByte(0x80); // Insert the message length as the last 8 bytes bytes.position = numberOfBytes - 8; bytes.writeUnsignedInt(inputLength >>> 29); bytes.writeUnsignedInt(inputLength << 3); bytes.position = 0; // Compute the Message Digest // algorithm based on the C code demonstration shown at // http://www.faqs.org/rfcs/rfc3174.html var H0:int = 0x67452301; var H1:int = 0xefcdab89; var H2:int = 0x98badcfe; var H3:int = 0x10325476; var H4:int = 0xc3d2e1f0; var W:Array = new Array(80); var temp:int; var A:int; var B:int; var C:int; var D:int; var E:int; var t:int; while (numberOfBlocks--) { A = H0; B = H1; C = H2; D = H3; E = H4; for (t = 0; t < 16; t++) { W[t] = bytes.readUnsignedInt(); } for (t = 16; t < 80; t++) { temp = int(W[t - 3]) ^ int(W[t - 8]) ^ int(W[t - 14]) ^ int(W[t - 16]); W[t] = (temp << 1) | (temp >>> 31); } for (t = 0; t < 20; t++) { temp = ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + E + int(W[t]) + 0x5a827999; E = D; D = C; C = (B << 30) | (B >>> 2); B = A; A = temp; } for (t = 20; t < 40; t++) { temp = ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + E + int(W[t]) + 0x6ed9eba1; E = D; D = C; C = (B << 30) | (B >>> 2); B = A; A = temp; } for (t = 40; t < 60; t++) { temp = ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + E + int(W[t]) + 0x8f1bbcdc; E = D; D = C; C = (B << 30) | (B >>> 2); B = A; A = temp; } for (t = 60; t < 80; t++) { temp = ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + E + int(W[t]) + 0xca62c1d6; E = D; D = C; C = (B << 30) | (B >>> 2); B = A; A = temp; } H0 += A; H1 += B; H2 += C; H3 += D; H4 += E; } return String.fromCharCode( H0 >> 24 & 0xff, H0 >> 16 & 0xff, H0 >> 8 & 0xff, H0 & 0xff, H1 >> 24 & 0xff, H1 >> 16 & 0xff, H1 >> 8 & 0xff, H1 & 0xff, H2 >> 24 & 0xff, H2 >> 16 & 0xff, H2 >> 8 & 0xff, H2 & 0xff, H3 >> 24 & 0xff, H3 >> 16 & 0xff, H3 >> 8 & 0xff, H3 & 0xff, H4 >> 24 & 0xff, H4 >> 16 & 0xff, H4 >> 8 & 0xff, H4 & 0xff ); } CONFIG::debug { public static function test():void { var tests:Array = [ "abc", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "a", "0123456701234567012345670123456701234567012345670123456701234567" ]; var results:Array = [ "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D", "84 98 3E 44 1C 3B D2 6E BA AE 4A A1 F9 51 29 E5 E5 46 70 F1", "86 F7 E4 37 FA A5 A7 FC E1 5D 1D DC B9 EA EA EA 37 76 67 B8", "E0 C0 94 E8 67 EF 46 C3 50 EF 54 A7 F5 9D D6 0B ED 92 AE 83" ]; for (var t:int = 0; t < tests.length; t++) { trace("Test " + (t + 1) + ": " + tests[t]); trace("expected: " + results[t]); var hashed:String = hash(tests[t]); var hex:Array = []; for (var h:int = 0; h < hashed.length; h++) { hex.push((0x100 + hashed.charCodeAt(h)).toString(16).replace('1', '').toUpperCase()); } var result:String = hex.join(" "); trace("result: " + result); trace("correct: " + (result === results[t])); trace(); } } } } }
hide debugging code
hide debugging code
ActionScript
mit
arahaya/FlashSocket,arahaya/FlashSocket
c7a48ec6b90c93d0155bac99eecc5d4e1ed3b5a1
src/org/flintparticles/common/easing/TwoWay.as
src/org/flintparticles/common/easing/TwoWay.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.easing { /** * A set of easing equations for modifying the particle energy such that it starts * and ends at zero and peaks at one half way through the particle's lifetime. * * @see org.flintparticles.common.actions.Age */ public class TwoWay { /** * Gives a linear increase and decrease in energy either side of the centre point. */ public static function linear( t : Number, b : Number, c : Number, d : Number ):Number { if( ( t = 2 * t / d ) <= 1 ) { return t * c + b; } return ( 2 - t ) * c + b; } /** * Energy increases and then decreases as if following the top half of a circle. */ public static function circular( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); return Math.sqrt( 1 - t * t ) * c + b; } /** * Energy follows the first half of a sine wave. */ public static function sine( t : Number, b : Number, c : Number, d : Number ):Number { return Math.sin( Math.PI * t / d ) * c + b; } /** * Eases towards the middle using a quadratic curve. */ public static function quadratic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); return ( 1 - t * t ) * c + b; } /** * Eases towards the middle using a cubic curve. */ public static function cubic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); if( t < 0 ) t = -t; return ( 1 - t * t * t ) * c + b; } /** * Eases towards the middle using a quartic curve. */ public static function quartic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); return ( 1 - t * t * t * t ) * c + b; } /** * Eases towards the middle using a quintic curve. */ public static function quintic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); if( t < 0 ) t = -t; return ( 1 - t * t * t * t * t ) * c + b; } } }
/* * 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.easing { /** * A set of easing equations that start and end at the end value and reach the start value * at the half-time point. They are designed for modifying the particle energy such that it * starts and ends at zero and peaks at half way through the particle's lifetime. * * @see org.flintparticles.common.actions.Age */ public class TwoWay { /** * Gives a linear increase and decrease in energy either side of the centre point. */ public static function linear( t : Number, b : Number, c : Number, d : Number ):Number { if( ( t = 2 * t / d ) <= 1 ) { return ( 1 - t ) * c + b; } return ( t - 1 ) * c + b; } /** * Energy increases and then decreases as if following the top half of a circle. */ public static function circular( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); return ( 1 - Math.sqrt( 1 - t * t ) ) * c + b; } /** * Energy follows the first half of a sine wave. */ public static function sine( t : Number, b : Number, c : Number, d : Number ):Number { return ( 1 - Math.sin( Math.PI * t / d ) ) * c + b; } /** * Eases towards the middle using a quadratic curve. */ public static function quadratic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); return t * t * c + b; } /** * Eases towards the middle using a cubic curve. */ public static function cubic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); if( t < 0 ) t = -t; return t * t * t * c + b; } /** * Eases towards the middle using a quartic curve. */ public static function quartic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); return t * t * t * t * c + b; } /** * Eases towards the middle using a quintic curve. */ public static function quintic( t : Number, b : Number, c : Number, d : Number ):Number { t = 1 - (2 * t / d); if( t < 0 ) t = -t; return t * t * t * t * t * c + b; } } }
Fix error in TwoWay easing functions
Fix error in TwoWay easing functions
ActionScript
mit
richardlord/Flint
60198173604c46e69321d400cd2dbc9110a24beb
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 : 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; var oldNodeToId : Dictionary = _nodeToId; var oldInitialized : Vector.<uint> = _initialized; var oldLocalToWorldTransforms : Vector.<Matrix4x4> = _localToWorldTransforms; var oldWorldToLocalTransform : Vector.<Matrix4x4> = _worldToLocalTransforms; _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; if (oldNodeToId && node in oldNodeToId) { var oldNodeId : uint = oldNodeToId[node]; _localToWorldTransforms[nodeId] = oldLocalToWorldTransforms[oldNodeId]; _worldToLocalTransforms[nodeId] = oldWorldToLocalTransform[oldNodeId]; _initialized[nodeId] = oldInitialized[oldNodeId]; } else { _localToWorldTransforms[nodeId] = new Matrix4x4().lock(); _worldToLocalTransforms[nodeId] = null; _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; 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 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, subtreeOnly : Boolean = false) : 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]; var subtreeMax : uint = nodeId; 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); } if (lastChildId > subtreeMax) subtreeMax = lastChildId; 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; 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); } } if (subtreeOnly && nodeId && nodeId >= subtreeMax) { 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 : 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, true); } 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; var oldNodeToId : Dictionary = _nodeToId; var oldInitialized : Vector.<uint> = _initialized; var oldLocalToWorldTransforms : Vector.<Matrix4x4> = _localToWorldTransforms; var oldWorldToLocalTransform : Vector.<Matrix4x4> = _worldToLocalTransforms; _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; if (oldNodeToId && node in oldNodeToId) { var oldNodeId : uint = oldNodeToId[node]; _localToWorldTransforms[nodeId] = oldLocalToWorldTransforms[oldNodeId]; _worldToLocalTransforms[nodeId] = oldWorldToLocalTransform[oldNodeId]; _initialized[nodeId] = oldInitialized[oldNodeId]; } else { _localToWorldTransforms[nodeId] = new Matrix4x4().lock(); _worldToLocalTransforms[nodeId] = null; _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; } } }
optimize TransformController.updateLocalToWorld() to update only the nodes of the subtree when subtreeOnly = true
optimize TransformController.updateLocalToWorld() to update only the nodes of the subtree when subtreeOnly = true
ActionScript
mit
aerys/minko-as3
355c328abe7ef0438ebbcd41f23818d8a2adfae4
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; 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; } } }
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 updateLocalToWorldPath(path : Vector.<uint> = null) : void { var numNodes : uint = path.length; var nodeId : uint = path[uint(numNodes - 1)]; var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId]; updateRootLocalToWorld(nodeId); for (var i : int = numNodes - 2; i >= 0; --i) { var childId : uint = path[i]; var childTransform : Matrix4x4 = _transforms[childId]; var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId]; var childFlags : uint = _flags[childId]; 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); localToWorld = childLocalToWorld; } } private function updateAncestorsAndSelfLocalToWorld(nodeId : uint) : void { var dirtyRoot : int = -1; var tmpNodeId : int = nodeId; var path : Vector.<uint> = new <uint>[]; var numNodes : uint = 0; while (tmpNodeId >= 0) { if ((_transforms[tmpNodeId] as Matrix4x4)._hasChanged || !(_flags[nodeId] & FLAG_INIT_LOCAL_TO_WORLD)) dirtyRoot = tmpNodeId; path[numNodes] = tmpNodeId; ++numNodes; tmpNodeId = _parentId[tmpNodeId]; } if (dirtyRoot >= 0) updateLocalToWorldPath(path); // 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 getSharedLocalToWorldTransformReference(node : ISceneNode) : Matrix4x4 { return _localToWorldTransforms[getNodeId(node)]; } 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 getSharedWorldToLocalTransformReference(node : ISceneNode) : Matrix4x4 { var nodeId : uint = getNodeId(node); return _worldToLocalTransforms[nodeId] || (_worldToLocalTransforms[nodeId] = new Matrix4x4()); } 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; } } }
add TransformController.getSharedWorldToLocalTransformReference() and TransformController.getSharedLocalToWorldTransformReference() methods
add TransformController.getSharedWorldToLocalTransformReference() and TransformController.getSharedLocalToWorldTransformReference() methods
ActionScript
mit
aerys/minko-as3
8d310d2daf1734700914cd5b6f10dca4e925f05a
generator/sources/as3/com/kaltura/delegates/WebDelegateBase.as
generator/sources/as3/com/kaltura/delegates/WebDelegateBase.as
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2011 Kaltura Inc. // // 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/>. // // @ignore // =================================================================================================== package com.kaltura.delegates { import com.kaltura.config.IKalturaConfig; import com.kaltura.config.KalturaConfig; import com.kaltura.core.KClassFactory; import com.kaltura.encryption.MD5; import com.kaltura.errors.KalturaError; import com.kaltura.events.KalturaEvent; import com.kaltura.net.KalturaCall; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.HTTPStatusEvent; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.FileReference; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.utils.Timer; import flash.utils.getDefinitionByName; public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate { public static var CONNECT_TIME:int = 120000; //120 secs public static var LOAD_TIME:int = 120000; //120 secs protected var connectTimer:Timer; protected var loadTimer:Timer; protected var _call:KalturaCall; protected var _config:KalturaConfig; protected var loader:URLLoader; protected var fileRef:FileReference; //Setters & getters public function get call():KalturaCall { return _call; } public function set call(newVal:KalturaCall):void { _call = newVal; } public function get config():IKalturaConfig { return _config; } public function set config(newVal:IKalturaConfig):void { _config = newVal as KalturaConfig; } public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) { this.call = call; this.config = config; if (!call) return; //maybe a multi request if (call.useTimeout) { connectTimer = new Timer(CONNECT_TIME, 1); connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout); loadTimer = new Timer(LOAD_TIME, 1); loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut); } execute(); } public function close():void { try { loader.close(); } catch (e:*) { } if (call.useTimeout) { connectTimer.stop(); loadTimer.stop(); } } protected function onConnectTimeout(event:TimerEvent):void { var kError:KalturaError = new KalturaError(); kError.errorCode = "CONNECTION_TIMEOUT"; kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client."; _call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); loadTimer.stop(); close(); } protected function onLoadTimeOut(event:TimerEvent):void { connectTimer.stop(); close(); var kError:KalturaError = new KalturaError(); kError.errorCode = "POST_TIMEOUT"; kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result."; _call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } protected function execute():void { if (call == null) { throw new Error('No call defined.'); } post(); //post the call } /** * Helper function for sending the call straight to the server */ protected function post():void { addOptionalArguments(); formatRequest(); sendRequest(); if (call.useTimeout) { connectTimer.start(); } } protected function formatRequest():void { //The configuration is stronger then the args if (_config.partnerId != null && _call.args["partnerId"] == -1) _call.setRequestArgument("partnerId", _config.partnerId); if (_config.ks != null) _call.setRequestArgument("ks", _config.ks); if (_config.clientTag != null) _call.setRequestArgument("clientTag", _config.clientTag); _call.setRequestArgument("ignoreNull", _config.ignoreNull); //Create signature hash. //call.setRequestArgument("kalsig", getMD5Checksum(call)); } protected function getMD5Checksum(call:KalturaCall):String { var props:Array = new Array(); for each (var prop:String in call.args) props.push(prop); props.push("service"); props.push("action"); props.sort(); var s:String; for each (prop in props) { s += prop; if (prop == "service") s += call.service; else if (prop == "action") s += call.action; else s += call.args[prop]; } return MD5.encrypt(s); } protected function sendRequest():void { //construct the loader createURLLoader(); //Create signature hash. var kalsig:String = getMD5Checksum(call); //create the service request for normal calls var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;; if (_call.method == URLRequestMethod.GET) url += "&"; var req:URLRequest = new URLRequest(url); req.contentType = "application/x-www-form-urlencoded"; req.method = call.method; req.data = call.args; loader.dataFormat = URLLoaderDataFormat.TEXT; loader.load(req); } protected function createURLLoader():void { loader = new URLLoader(); loader.addEventListener(Event.COMPLETE, onDataComplete); loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus); loader.addEventListener(IOErrorEvent.IO_ERROR, onError); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); loader.addEventListener(Event.OPEN, onOpen); } protected function onHTTPStatus(event:HTTPStatusEvent):void { } protected function onOpen(event:Event):void { if (call.useTimeout) { connectTimer.stop(); loadTimer.start(); } } protected function addOptionalArguments():void { //add optional args here } // Event Handlers /** * try to process received data. * if procesing failed, let call handle the processing error * @param event load complete event */ protected function onDataComplete(event:Event):void { try { handleResult(XML(event.target.data)); } catch (e:Error) { var kErr:KalturaError = new KalturaError(); kErr.errorCode = String(e.errorID); kErr.errorMsg = e.message; _call.handleError(kErr); } } /** * handle io or security error events from the loader. * create relevant KalturaError, let the call process it. * @param event */ protected function onError(event:ErrorEvent):void { clean(); var kError:KalturaError = createKalturaError(event, loader.data); if (!kError) { kError = new KalturaError(); kError.errorMsg = event.text; //kError.errorCode; } call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } /** * parse the server's response and let the call process it. * @param result server's response */ protected function handleResult(result:XML):void { clean(); var error:KalturaError = validateKalturaResponse(result); if (error == null) { var digestedResult:Object = parse(result); call.handleResult(digestedResult); } else { call.handleError(error); } } /** * stop timers and clean event listeners */ protected function clean():void { if (call.useTimeout) { connectTimer.stop(); loadTimer.stop(); } if (loader == null) { return; } loader.removeEventListener(Event.COMPLETE, onDataComplete); loader.removeEventListener(IOErrorEvent.IO_ERROR, onError); loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); loader.removeEventListener(Event.OPEN, onOpen); } /** * create the correct object and populate it with the given values. if the needed class is not found * in the file, a generic object is created with attributes matching the XML attributes. * Override this parssing function in the specific delegate to create the correct object. * @param result instance attributes * @return an instance of the class declared by the given XML. * */ public function parse(result:XML):* { //by defualt create the response object var cls:Class; try { cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class; } catch (e:Error) { cls = Object; } var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result); return obj; } /** * If the result string holds an error, return a KalturaError object with * relevant values. <br/> * Overide this to create validation object and fill it. * @param result the string returned from the server. * @return matching error object */ protected function validateKalturaResponse(result:String):KalturaError { var kError:KalturaError = null; var xml:XML = XML(result); if (xml.result.hasOwnProperty('error') && xml.result.error.hasOwnProperty('code') && xml.result.error.hasOwnProperty('message')) { kError = new KalturaError(); kError.errorCode = String(xml.result.error.code); kError.errorMsg = xml.result.error.message; dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } return kError; } /** * create error object and fill it with relevant details * @param event * @param loaderData * @return detailed KalturaError to be processed */ protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError { var ke:KalturaError = new KalturaError(); ke.errorMsg = event.text; return ke; } /** * create the url that is used for serve actions * @param call the KalturaCall that defines the required parameters * @return URLRequest with relevant parameters * */ public function getServeUrl(call:KalturaCall):URLRequest { var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action; for (var key:String in call.args) { url += "&" + key + "=" + call.args[key]; } var req:URLRequest = new URLRequest(url); req.contentType = "application/x-www-form-urlencoded"; req.method = call.method; // req.data = call.args; return req; } } }
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // // Copyright (C) 2006-2011 Kaltura Inc. // // 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/>. // // @ignore // =================================================================================================== package com.kaltura.delegates { import com.kaltura.config.IKalturaConfig; import com.kaltura.config.KalturaConfig; import com.kaltura.core.KClassFactory; import com.kaltura.encryption.MD5; import com.kaltura.errors.KalturaError; import com.kaltura.events.KalturaEvent; import com.kaltura.net.KalturaCall; import flash.events.ErrorEvent; import flash.events.Event; import flash.events.EventDispatcher; import flash.events.HTTPStatusEvent; import flash.events.IOErrorEvent; import flash.events.SecurityErrorEvent; import flash.events.TimerEvent; import flash.net.FileReference; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.utils.Timer; import flash.utils.getDefinitionByName; public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate { public static var CONNECT_TIME:int = 120000; //120 secs public static var LOAD_TIME:int = 120000; //120 secs protected var connectTimer:Timer; protected var loadTimer:Timer; protected var _call:KalturaCall; protected var _config:KalturaConfig; protected var loader:URLLoader; protected var fileRef:FileReference; //Setters & getters public function get call():KalturaCall { return _call; } public function set call(newVal:KalturaCall):void { _call = newVal; } public function get config():IKalturaConfig { return _config; } public function set config(newVal:IKalturaConfig):void { _config = newVal as KalturaConfig; } public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) { this.call = call; this.config = config; if (!call) return; //maybe a multi request if (call.useTimeout) { connectTimer = new Timer(CONNECT_TIME, 1); connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout); loadTimer = new Timer(LOAD_TIME, 1); loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut); } execute(); } public function close():void { try { loader.close(); } catch (e:*) { } if (call.useTimeout) { connectTimer.stop(); loadTimer.stop(); } } protected function onConnectTimeout(event:TimerEvent):void { var kError:KalturaError = new KalturaError(); kError.errorCode = "CONNECTION_TIMEOUT"; kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client."; _call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); loadTimer.stop(); close(); } protected function onLoadTimeOut(event:TimerEvent):void { connectTimer.stop(); close(); var kError:KalturaError = new KalturaError(); kError.errorCode = "POST_TIMEOUT"; kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result."; _call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } protected function execute():void { if (call == null) { throw new Error('No call defined.'); } post(); //post the call } /** * Helper function for sending the call straight to the server */ protected function post():void { addOptionalArguments(); formatRequest(); sendRequest(); if (call.useTimeout) { connectTimer.start(); } } protected function formatRequest():void { //The configuration is stronger then the args if (_config.partnerId != null && _call.args["partnerId"] == -1) _call.setRequestArgument("partnerId", _config.partnerId); if (_config.ks != null) _call.setRequestArgument("ks", _config.ks); if (_config.clientTag != null) _call.setRequestArgument("clientTag", _config.clientTag); _call.setRequestArgument("ignoreNull", _config.ignoreNull); //Create signature hash. //call.setRequestArgument("kalsig", getMD5Checksum(call)); } protected function getMD5Checksum(call:KalturaCall):String { var props:Array = new Array(); for each (var prop:String in call.args) props.push(prop); props.push("service"); props.push("action"); props.sort(); var s:String; for each (prop in props) { s += prop; if (prop == "service") s += call.service; else if (prop == "action") s += call.action; else s += call.args[prop]; } return MD5.encrypt(s); } protected function sendRequest():void { //construct the loader createURLLoader(); //Create signature hash. var kalsig:String = getMD5Checksum(call); //create the service request for normal calls var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;; if (_call.method == URLRequestMethod.GET) url += "&"; var req:URLRequest = new URLRequest(url); req.contentType = "application/x-www-form-urlencoded"; req.method = call.method; req.data = call.args; loader.dataFormat = URLLoaderDataFormat.TEXT; loader.load(req); } protected function createURLLoader():void { loader = new URLLoader(); loader.addEventListener(Event.COMPLETE, onDataComplete); loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus); loader.addEventListener(IOErrorEvent.IO_ERROR, onError); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); loader.addEventListener(Event.OPEN, onOpen); } protected function onHTTPStatus(event:HTTPStatusEvent):void { } protected function onOpen(event:Event):void { if (call.useTimeout) { connectTimer.stop(); loadTimer.start(); } } protected function addOptionalArguments():void { //add optional args here } // Event Handlers /** * try to process received data. * if procesing failed, let call handle the processing error * @param event load complete event */ protected function onDataComplete(event:Event):void { try { handleResult(XML(event.target.data)); } catch (e:Error) { var kErr:KalturaError = new KalturaError(); kErr.errorCode = String(e.errorID); kErr.errorMsg = e.message; _call.handleError(kErr); } } /** * handle io or security error events from the loader. * create relevant KalturaError, let the call process it. * @param event */ protected function onError(event:ErrorEvent):void { clean(); var kError:KalturaError = createKalturaError(event, loader.data); if (!kError) { kError = new KalturaError(); kError.errorMsg = event.text; kError.errorCode = event.type; // either IOErrorEvent.IO_ERROR or SecurityErrorEvent.SECURITY_ERROR } call.handleError(kError); dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } /** * parse the server's response and let the call process it. * @param result server's response */ protected function handleResult(result:XML):void { clean(); var error:KalturaError = validateKalturaResponse(result); if (error == null) { var digestedResult:Object = parse(result); call.handleResult(digestedResult); } else { call.handleError(error); } } /** * stop timers and clean event listeners */ protected function clean():void { if (call.useTimeout) { connectTimer.stop(); loadTimer.stop(); } if (loader == null) { return; } loader.removeEventListener(Event.COMPLETE, onDataComplete); loader.removeEventListener(IOErrorEvent.IO_ERROR, onError); loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError); loader.removeEventListener(Event.OPEN, onOpen); } /** * create the correct object and populate it with the given values. if the needed class is not found * in the file, a generic object is created with attributes matching the XML attributes. * Override this parssing function in the specific delegate to create the correct object. * @param result instance attributes * @return an instance of the class declared by the given XML. * */ public function parse(result:XML):* { //by defualt create the response object var cls:Class; try { cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class; } catch (e:Error) { cls = Object; } var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result); return obj; } /** * If the result string holds an error, return a KalturaError object with * relevant values. <br/> * Overide this to create validation object and fill it. * @param result the string returned from the server. * @return matching error object */ protected function validateKalturaResponse(result:String):KalturaError { var kError:KalturaError = null; var xml:XML = XML(result); if (xml.result.hasOwnProperty('error') && xml.result.error.hasOwnProperty('code') && xml.result.error.hasOwnProperty('message')) { kError = new KalturaError(); kError.errorCode = String(xml.result.error.code); kError.errorMsg = xml.result.error.message; dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError)); } return kError; } /** * create error object and fill it with relevant details * @param event * @param loaderData * @return detailed KalturaError to be processed */ protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError { var ke:KalturaError = new KalturaError(); ke.errorMsg = event.text; return ke; } /** * create the url that is used for serve actions * @param call the KalturaCall that defines the required parameters * @return URLRequest with relevant parameters * */ public function getServeUrl(call:KalturaCall):URLRequest { var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action; for (var key:String in call.args) { url += "&" + key + "=" + call.args[key]; } var req:URLRequest = new URLRequest(url); req.contentType = "application/x-www-form-urlencoded"; req.method = call.method; // req.data = call.args; return req; } } }
add error code (event.type) to ioerror / securityerror events
fwr: add error code (event.type) to ioerror / securityerror events git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@96549 6b8eccd3-e8c5-4e7d-8186-e12b5326b719
ActionScript
agpl-3.0
ivesbai/server,ivesbai/server,ivesbai/server,doubleshot/server,doubleshot/server,ratliff/server,ratliff/server,doubleshot/server,kaltura/server,ratliff/server,kaltura/server,ivesbai/server,DBezemer/server,matsuu/server,jorgevbo/server,jorgevbo/server,jorgevbo/server,gale320/server,kaltura/server,jorgevbo/server,doubleshot/server,doubleshot/server,ivesbai/server,DBezemer/server,matsuu/server,matsuu/server,gale320/server,gale320/server,jorgevbo/server,jorgevbo/server,DBezemer/server,matsuu/server,ivesbai/server,doubleshot/server,doubleshot/server,kaltura/server,gale320/server,matsuu/server,DBezemer/server,ivesbai/server,ratliff/server,DBezemer/server,gale320/server,ratliff/server,ratliff/server,jorgevbo/server,kaltura/server,DBezemer/server,gale320/server,ratliff/server,matsuu/server,matsuu/server,ratliff/server,kaltura/server,DBezemer/server,ivesbai/server,jorgevbo/server,DBezemer/server,gale320/server,gale320/server,doubleshot/server,matsuu/server
024e47f75fa52f3fa65659e05f0e8e6358b59285
swfcat.as
swfcat.as
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.text.TextField; import flash.text.TextFormat; import flash.events.Event; import flash.utils.setTimeout; import FacilitatorSocket; import events.FacilitatorSocketEvent; import ProxyPair; import RTMFPProxyPair; import SQSProxyPair; import TCPProxyPair; import rtmfp.CirrusSocket; import rtmfp.events.CirrusSocketEvent; public class swfcat extends Sprite { /* Adobe's Cirrus server for RTMFP connections. The Cirrus key is defined at compile time by reading from the CIRRUS_KEY environment var. */ private const DEFAULT_CIRRUS_ADDR:String = "rtmfp://p2p.rtmfp.net"; private const DEFAULT_CIRRUS_KEY:String = RTMFP::CIRRUS_KEY; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "tor-facilitator.bamsoftware.com", port: 9002 }; /* Default Tor client to use in case of RTMFP connection */ private const DEFAULT_TOR_CLIENT_ADDR:Object = { host: "127.0.0.1", port: 9002 }; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Socket to Cirrus server private var s_c:CirrusSocket; // Socket to facilitator. private var s_f:FacilitatorSocket; // Handle local-remote traffic private var p_p:ProxyPair; private var client_id:String; private var proxy_pair_factory:Function; private var proxy_pairs:Array; private var debug_mode:Boolean; private var proxy_mode:Boolean; /* TextField for debug output. */ private var output_text:TextField; /* Badge for display */ private var badge:InternetFreedomBadge; private var fac_addr:Object; private var relay_addr:Object; public function swfcat() { proxy_mode = false; debug_mode = false; // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } public function puts(s:String):void { if (output_text != null) { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } } private function loaderinfo_complete(e:Event):void { var fac_spec:String; var relay_spec:String; debug_mode = (this.loaderInfo.parameters["debug"] != null) proxy_mode = (this.loaderInfo.parameters["proxy"] != null); if (proxy_mode && !debug_mode) { badge = new InternetFreedomBadge(this); badge.display(); } else { output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; addChild(output_text); } puts("Starting: parameters loaded."); /* TODO: use this to have multiple proxies going at once */ proxy_pairs = new Array(); fac_spec = this.loaderInfo.parameters["facilitator"]; if (fac_spec) { puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } } else { fac_addr = DEFAULT_FACILITATOR_ADDR; } main(); } /* The main logic begins here, after start-up issues are taken care of. */ private function main():void { if (proxy_mode) { establish_facilitator_connection(); } else { establish_cirrus_connection(); } } private function establish_cirrus_connection():void { s_c = new CirrusSocket(); s_c.addEventListener(CirrusSocketEvent.CONNECT_SUCCESS, function (e:CirrusSocketEvent):void { puts("Cirrus: connected with id " + s_c.id + "."); if (proxy_mode) { start_proxy_pair(); s_c.send_hello(client_id); } else { establish_facilitator_connection(); } }); s_c.addEventListener(CirrusSocketEvent.CONNECT_FAILED, function (e:CirrusSocketEvent):void { puts("Error: failed to connect to Cirrus."); }); s_c.addEventListener(CirrusSocketEvent.CONNECT_CLOSED, function (e:CirrusSocketEvent):void { puts("Cirrus: closed connection."); }); s_c.addEventListener(CirrusSocketEvent.HELLO_RECEIVED, function (e:CirrusSocketEvent):void { puts("Cirrus: received hello from peer " + e.peer); /* don't bother if we already have a proxy going */ if (p_p != null && p_p.connected) { return; } /* if we're in proxy mode, we should have already set up a proxy pair */ if (!proxy_mode) { relay_addr = DEFAULT_TOR_CLIENT_ADDR; proxy_pair_factory = rtmfp_proxy_pair_factory; start_proxy_pair(); s_c.send_hello(e.peer); } else if (!debug_mode && badge != null) { badge.total_proxy_pairs++; badge.num_proxy_pairs++; } p_p.client = {peer: e.peer, stream: e.stream}; }); s_c.connect(DEFAULT_CIRRUS_ADDR, DEFAULT_CIRRUS_KEY); } private function establish_facilitator_connection():void { s_f = new FacilitatorSocket(fac_addr.host, fac_addr.port); s_f.addEventListener(FacilitatorSocketEvent.CONNECT_FAILED, function (e:Event):void { puts("Facilitator: connect failed."); setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL); }); if (proxy_mode) { s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_RECEIVED, function (e:FacilitatorSocketEvent):void { var client_addr:Object = parse_addr_spec(e.client); relay_addr = parse_addr_spec(e.relay); if (client_addr == null) { puts("Facilitator: got registration " + e.client); proxy_pair_factory = rtmfp_proxy_pair_factory; if (s_c == null || !s_c.connected) { client_id = e.client; establish_cirrus_connection(); } else { start_proxy_pair(); s_c.send_hello(e.client); } } else { proxy_pair_factory = tcp_proxy_pair_factory; start_proxy_pair(); p_p.client = client_addr; } }); s_f.addEventListener(FacilitatorSocketEvent.REGISTRATIONS_EMPTY, function (e:Event):void { puts("Facilitator: no registrations available."); setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL); }); puts("Facilitator: getting registration."); s_f.get_registration(); } else { s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_FAILED, function (e:Event):void { puts("Facilitator: registration failed."); setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL); }); puts("Facilitator: posting registration."); s_f.post_registration(s_c.id); } } private function start_proxy_pair():void { p_p = proxy_pair_factory(); p_p.addEventListener(Event.CONNECT, function (e:Event):void { puts("ProxyPair: connected!"); }); p_p.addEventListener(Event.CLOSE, function (e:Event):void { puts("ProxyPair: connection closed."); p_p = null; if (proxy_mode && !debug_mode && badge != null) { badge.num_proxy_pairs--; } establish_facilitator_connection(); }); p_p.relay = relay_addr; } private function rtmfp_proxy_pair_factory():ProxyPair { return new RTMFPProxyPair(this, s_c, s_c.local_stream_name); } // currently is the same as TCPProxyPair // could be interesting to see how this works // can't imagine it will work terribly well... private function sqs_proxy_pair_factory():ProxyPair { return new SQSProxyPair(this); } private function tcp_proxy_pair_factory():ProxyPair { return new TCPProxyPair(this); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.text.TextField; import flash.text.TextFormat; class InternetFreedomBadge { private var ui:swfcat; private var _num_proxy_pairs:uint; private var _total_proxy_pairs:uint; [Embed(source="badge.png")] private var BadgeImage:Class; private var tot_client_count_tf:TextField; private var tot_client_count_fmt:TextFormat; private var cur_client_count_tf:TextField; private var cur_client_count_fmt:TextFormat; public function InternetFreedomBadge(ui:swfcat) { this.ui = ui; _num_proxy_pairs = 0; _total_proxy_pairs = 0; /* Setup client counter for badge. */ tot_client_count_fmt = new TextFormat(); tot_client_count_fmt.color = 0xFFFFFF; tot_client_count_fmt.align = "center"; tot_client_count_fmt.font = "courier-new"; tot_client_count_fmt.bold = true; tot_client_count_fmt.size = 10; tot_client_count_tf = new TextField(); tot_client_count_tf.width = 20; tot_client_count_tf.height = 17; tot_client_count_tf.background = false; tot_client_count_tf.defaultTextFormat = tot_client_count_fmt; tot_client_count_tf.x=47; tot_client_count_tf.y=0; cur_client_count_fmt = new TextFormat(); cur_client_count_fmt.color = 0xFFFFFF; cur_client_count_fmt.align = "center"; cur_client_count_fmt.font = "courier-new"; cur_client_count_fmt.bold = true; cur_client_count_fmt.size = 10; cur_client_count_tf = new TextField(); cur_client_count_tf.width = 20; cur_client_count_tf.height = 17; cur_client_count_tf.background = false; cur_client_count_tf.defaultTextFormat = cur_client_count_fmt; cur_client_count_tf.x=47; cur_client_count_tf.y=6; /* Update the client counter on badge. */ update_client_count(); } public function display():void { ui.addChild(new BadgeImage()); /* Tried unsuccessfully to add counter to badge. */ /* For now, need two addChilds :( */ ui.addChild(tot_client_count_tf); ui.addChild(cur_client_count_tf); } public function get num_proxy_pairs():uint { return _num_proxy_pairs; } public function set num_proxy_pairs(amount:uint):void { _num_proxy_pairs = amount; update_client_count(); } public function get total_proxy_pairs():uint { return _total_proxy_pairs; } public function set total_proxy_pairs(amount:uint):void { _total_proxy_pairs = amount; /* note: doesn't update, so be sure to update this before you update num_proxy_pairs! */ } private function update_client_count():void { /* Update total client count. */ if (String(total_proxy_pairs).length == 1) tot_client_count_tf.text = "0" + String(total_proxy_pairs); else tot_client_count_tf.text = String(total_proxy_pairs); /* Update current client count. */ cur_client_count_tf.text = ""; for(var i:Number = 0; i < num_proxy_pairs; i++) cur_client_count_tf.appendText("."); } }
package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.text.TextField; import flash.text.TextFormat; import flash.events.Event; import flash.utils.setTimeout; import FacilitatorSocket; import events.FacilitatorSocketEvent; import ProxyPair; import RTMFPProxyPair; import SQSProxyPair; import TCPProxyPair; import rtmfp.CirrusSocket; import rtmfp.events.CirrusSocketEvent; public class swfcat extends Sprite { /* Adobe's Cirrus server for RTMFP connections. The Cirrus key is defined at compile time by reading from the CIRRUS_KEY environment var. */ private const DEFAULT_CIRRUS_ADDR:String = "rtmfp://p2p.rtmfp.net"; private const DEFAULT_CIRRUS_KEY:String = RTMFP::CIRRUS_KEY; private const DEFAULT_FACILITATOR_ADDR:Object = { host: "tor-facilitator.bamsoftware.com", port: 9002 }; /* Default Tor client to use in case of RTMFP connection */ private const DEFAULT_TOR_CLIENT_ADDR:Object = { host: "127.0.0.1", port: 9002 }; // Milliseconds. private const FACILITATOR_POLL_INTERVAL:int = 10000; // Socket to Cirrus server private var s_c:CirrusSocket; // Socket to facilitator. private var s_f:FacilitatorSocket; // Handle local-remote traffic private var p_p:ProxyPair; private var client_id:String; private var proxy_pair_factory:Function; private var proxy_pairs:Array; private var debug_mode:Boolean; private var proxy_mode:Boolean; /* TextField for debug output. */ private var output_text:TextField; /* Badge for display */ private var badge:Badge; private var fac_addr:Object; private var relay_addr:Object; public function swfcat() { proxy_mode = false; debug_mode = false; // Absolute positioning. stage.scaleMode = StageScaleMode.NO_SCALE; stage.align = StageAlign.TOP_LEFT; // Wait until the query string parameters are loaded. this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete); } public function puts(s:String):void { if (output_text != null) { output_text.appendText(s + "\n"); output_text.scrollV = output_text.maxScrollV; } } private function loaderinfo_complete(e:Event):void { var fac_spec:String; var relay_spec:String; debug_mode = (this.loaderInfo.parameters["debug"] != null) proxy_mode = (this.loaderInfo.parameters["proxy"] != null); if (proxy_mode && !debug_mode) { badge = new Badge(); addChild(badge); } else { output_text = new TextField(); output_text.width = stage.stageWidth; output_text.height = stage.stageHeight; output_text.background = true; output_text.backgroundColor = 0x001f0f; output_text.textColor = 0x44cc44; addChild(output_text); } puts("Starting: parameters loaded."); /* TODO: use this to have multiple proxies going at once */ proxy_pairs = new Array(); fac_spec = this.loaderInfo.parameters["facilitator"]; if (fac_spec) { puts("Facilitator spec: \"" + fac_spec + "\""); fac_addr = parse_addr_spec(fac_spec); if (!fac_addr) { puts("Error: Facilitator spec must be in the form \"host:port\"."); return; } } else { fac_addr = DEFAULT_FACILITATOR_ADDR; } main(); } /* The main logic begins here, after start-up issues are taken care of. */ private function main():void { if (proxy_mode) { establish_facilitator_connection(); } else { establish_cirrus_connection(); } } private function establish_cirrus_connection():void { s_c = new CirrusSocket(); s_c.addEventListener(CirrusSocketEvent.CONNECT_SUCCESS, function (e:CirrusSocketEvent):void { puts("Cirrus: connected with id " + s_c.id + "."); if (proxy_mode) { start_proxy_pair(); s_c.send_hello(client_id); } else { establish_facilitator_connection(); } }); s_c.addEventListener(CirrusSocketEvent.CONNECT_FAILED, function (e:CirrusSocketEvent):void { puts("Error: failed to connect to Cirrus."); }); s_c.addEventListener(CirrusSocketEvent.CONNECT_CLOSED, function (e:CirrusSocketEvent):void { puts("Cirrus: closed connection."); }); s_c.addEventListener(CirrusSocketEvent.HELLO_RECEIVED, function (e:CirrusSocketEvent):void { puts("Cirrus: received hello from peer " + e.peer); /* don't bother if we already have a proxy going */ if (p_p != null && p_p.connected) { return; } /* if we're in proxy mode, we should have already set up a proxy pair */ if (!proxy_mode) { relay_addr = DEFAULT_TOR_CLIENT_ADDR; proxy_pair_factory = rtmfp_proxy_pair_factory; start_proxy_pair(); s_c.send_hello(e.peer); } else if (!debug_mode && badge != null) { badge.proxy_begin(); } p_p.client = {peer: e.peer, stream: e.stream}; }); s_c.connect(DEFAULT_CIRRUS_ADDR, DEFAULT_CIRRUS_KEY); } private function establish_facilitator_connection():void { s_f = new FacilitatorSocket(fac_addr.host, fac_addr.port); s_f.addEventListener(FacilitatorSocketEvent.CONNECT_FAILED, function (e:Event):void { puts("Facilitator: connect failed."); setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL); }); if (proxy_mode) { s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_RECEIVED, function (e:FacilitatorSocketEvent):void { var client_addr:Object = parse_addr_spec(e.client); relay_addr = parse_addr_spec(e.relay); if (client_addr == null) { puts("Facilitator: got registration " + e.client); proxy_pair_factory = rtmfp_proxy_pair_factory; if (s_c == null || !s_c.connected) { client_id = e.client; establish_cirrus_connection(); } else { start_proxy_pair(); s_c.send_hello(e.client); } } else { proxy_pair_factory = tcp_proxy_pair_factory; start_proxy_pair(); p_p.client = client_addr; } }); s_f.addEventListener(FacilitatorSocketEvent.REGISTRATIONS_EMPTY, function (e:Event):void { puts("Facilitator: no registrations available."); setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL); }); puts("Facilitator: getting registration."); s_f.get_registration(); } else { s_f.addEventListener(FacilitatorSocketEvent.REGISTRATION_FAILED, function (e:Event):void { puts("Facilitator: registration failed."); setTimeout(establish_facilitator_connection, FACILITATOR_POLL_INTERVAL); }); puts("Facilitator: posting registration."); s_f.post_registration(s_c.id); } } private function start_proxy_pair():void { p_p = proxy_pair_factory(); p_p.addEventListener(Event.CONNECT, function (e:Event):void { puts("ProxyPair: connected!"); }); p_p.addEventListener(Event.CLOSE, function (e:Event):void { puts("ProxyPair: connection closed."); p_p = null; if (proxy_mode && !debug_mode && badge != null) { badge.proxy_end(); } establish_facilitator_connection(); }); p_p.relay = relay_addr; } private function rtmfp_proxy_pair_factory():ProxyPair { return new RTMFPProxyPair(this, s_c, s_c.local_stream_name); } // currently is the same as TCPProxyPair // could be interesting to see how this works // can't imagine it will work terribly well... private function sqs_proxy_pair_factory():ProxyPair { return new SQSProxyPair(this); } private function tcp_proxy_pair_factory():ProxyPair { return new TCPProxyPair(this); } /* Parse an address in the form "host:port". Returns an Object with keys "host" (String) and "port" (int). Returns null on error. */ private function parse_addr_spec(spec:String):Object { var parts:Array; var addr:Object; parts = spec.split(":", 2); if (parts.length != 2 || !parseInt(parts[1])) return null; addr = {} addr.host = parts[0]; addr.port = parseInt(parts[1]); return addr; } } } import flash.text.TextFormat; import flash.text.TextField; class Badge extends flash.display.Sprite { /* Number of proxy pairs currently connected. */ private var num_proxy_pairs:int = 0; /* Number of proxy pairs ever connected. */ private var total_proxy_pairs:int = 0; [Embed(source="badge.png")] private var BadgeImage:Class; private var tot_client_count_tf:TextField; private var tot_client_count_fmt:TextFormat; private var cur_client_count_tf:TextField; private var cur_client_count_fmt:TextFormat; public function Badge() { /* Setup client counter for badge. */ tot_client_count_fmt = new TextFormat(); tot_client_count_fmt.color = 0xFFFFFF; tot_client_count_fmt.align = "center"; tot_client_count_fmt.font = "courier-new"; tot_client_count_fmt.bold = true; tot_client_count_fmt.size = 10; tot_client_count_tf = new TextField(); tot_client_count_tf.width = 20; tot_client_count_tf.height = 17; tot_client_count_tf.background = false; tot_client_count_tf.defaultTextFormat = tot_client_count_fmt; tot_client_count_tf.x=47; tot_client_count_tf.y=0; cur_client_count_fmt = new TextFormat(); cur_client_count_fmt.color = 0xFFFFFF; cur_client_count_fmt.align = "center"; cur_client_count_fmt.font = "courier-new"; cur_client_count_fmt.bold = true; cur_client_count_fmt.size = 10; cur_client_count_tf = new TextField(); cur_client_count_tf.width = 20; cur_client_count_tf.height = 17; cur_client_count_tf.background = false; cur_client_count_tf.defaultTextFormat = cur_client_count_fmt; cur_client_count_tf.x=47; cur_client_count_tf.y=6; addChild(new BadgeImage()); addChild(tot_client_count_tf); addChild(cur_client_count_tf); /* Update the client counter on badge. */ update_client_count(); } public function proxy_begin():void { num_proxy_pairs++; total_proxy_pairs++; update_client_count(); } public function proxy_end():void { num_proxy_pairs--; update_client_count(); } private function update_client_count():void { /* Update total client count. */ if (String(total_proxy_pairs).length == 1) tot_client_count_tf.text = "0" + String(total_proxy_pairs); else tot_client_count_tf.text = String(total_proxy_pairs); /* Update current client count. */ cur_client_count_tf.text = ""; for(var i:Number = 0; i < num_proxy_pairs; i++) cur_client_count_tf.appendText("."); } }
Refactor InternetFreedomBadge (now Badge).
Refactor InternetFreedomBadge (now Badge). Make it its own Sprite, don't cause it to change the UI of the main display. Use proxy_begin and proxy_end methods instead of modifying current/total counts directly.
ActionScript
mit
arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy
5aa7bcfa81851ef5f8fef33402c659a0cfcfb95c
exporter/src/main/as/flump/export/Exporter.as
exporter/src/main/as/flump/export/Exporter.as
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.desktop.NativeApplication; import flash.display.NativeMenu; import flash.display.NativeMenuItem; import flash.display.NativeWindow; import flash.display.Stage; import flash.display.StageQuality; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.net.SharedObject; import flash.utils.IDataOutput; import flump.executor.Executor; import flump.executor.Future; import flump.export.Ternary; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import mx.collections.ArrayList; import mx.events.CollectionEvent; import mx.events.PropertyChangeEvent; import spark.components.DataGrid; import spark.components.DropDownList; import spark.components.List; import spark.components.Window; import spark.events.GridSelectionEvent; import com.threerings.util.F; import com.threerings.util.Log; import com.threerings.util.StringUtil; import starling.display.Sprite; public class Exporter { public static const NA :NativeApplication = NativeApplication.nativeApplication; public function Exporter (win :ExporterWindow) { Log.setLevel("", Log.INFO); _win = win; _errors = _win.errors; _libraries = _win.libraries; function updatePreviewAndExport (..._) :void { _win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 && _libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); var status :DocStatus = _libraries.selectedItem as DocStatus; _win.preview.enabled = status != null && status.isValid; if (_exportChooser.dir == null) return; _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); } var fileMenuItem :NativeMenuItem; if (NativeApplication.supportsMenu) { // Grab the existing menu on macs. Use an index to get it as it's not going to be // 'File' in all languages fileMenuItem = NA.menu.getItemAt(1); // Add a separator before the existing close command fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 0); } else { _win.nativeWindow.menu = new NativeMenu(); fileMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File"); } // Add save and save as by index to work with the existing items on Mac // Mac menus have an existing "Close" item, so everything we add should go ahead of that var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New"), 0); newMenuItem.keyEquivalent = "n"; newMenuItem.addEventListener(Event.SELECT, function (..._) :void { _confFile = null; _conf = new FlumpConf(); updatePublisher(); }); var openMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open..."), 1); openMenuItem.keyEquivalent = "o"; openMenuItem.addEventListener(Event.SELECT, function (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; openConf(); updatePublisher(); }); file.browseForOpen("Open Flump Configuration"); }); fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2); const saveMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save"), 3); saveMenuItem.keyEquivalent = "s"; function saveConf () :void { Files.write(_confFile, function (out :IDataOutput) :void { // Set directories relative to where this file is being saved. Fall back to absolute // paths if relative paths aren't possible. if (_importChooser.dir != null) { _conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true); if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath; } if (_exportChooser.dir != null) { _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath; } out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2)); }); }; function saveAs (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; trace("Conf file is now " + _confFile.nativePath); _settings.data["CONF_FILE"] = _confFile.nativePath; _settings.flush(); saveConf(); }); file.browseForSave("Save Flump Configuration"); }; saveMenuItem.addEventListener(Event.SELECT, function (..._) :void { if (_confFile == null) saveAs(); else saveConf(); }); function openConf () :void { try { _conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile)); _win.title = _confFile.name; var dir :String = _confFile.parent.resolvePath(_conf.importDir).nativePath; setImport(new File(dir)); } catch (e :Error) { log.warning("Unable to parse conf", e); _errors.dataProvider.addItem(new ParseError(_confFile.nativePath, ParseError.CRIT, "Unable to read configuration")); _confFile = null; } }; const saveAsMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save As..."), 4); saveAsMenuItem.keyEquivalent = "S"; saveAsMenuItem.addEventListener(Event.SELECT, saveAs); if (_settings.data.hasOwnProperty("CONF_FILE")) { _confFile = new File(_settings.data["CONF_FILE"]); openConf(); } var curSelection :DocStatus = null; _libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _libraries.selectedIndices); updatePreviewAndExport(); if (curSelection != null) { curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } var newSelection :DocStatus = _libraries.selectedItem as DocStatus; if (newSelection != null) { newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } curSelection = newSelection; }); _win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void { setImport(_importChooser.dir); updatePreviewAndExport(); }); _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _libraries.selectedItems) { exportFlashDocument(status); } }); _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { showPreviewWindow(_libraries.selectedItem.lib); }); _importChooser = new DirChooser(null, _win.importRoot, _win.browseImport); _importChooser.changed.add(setImport); _exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport); _exportChooser.changed.add(updatePreviewAndExport); function updatePublisher (..._) :void { if (_confFile != null) { _importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null; _exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null; } else { _importChooser.dir = null; _exportChooser.dir = null; } if (_exportChooser.dir == null || _conf.exports.length == 0) _publisher = null; else _publisher = new Publisher(_exportChooser.dir, Vector.<ExportConf>(_conf.exports)); var formatNames :Array = []; for each (var export :ExportConf in _conf.exports) formatNames.push(export.name); _win.formatOverview.text = formatNames.join(", "); }; _exportChooser.changed.add(updatePublisher); var editFormats :EditFormatsWindow; _win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void { if (editFormats == null || editFormats.closed) { editFormats = new EditFormatsWindow(); editFormats.open(); } else editFormats.orderToFront(); var dataProvider :ArrayList = new ArrayList(_conf.exports); dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, updatePublisher); editFormats.exports.dataProvider = dataProvider; editFormats.buttonAdd.addEventListener(MouseEvent.CLICK, function (..._) :void { var export :ExportConf = new ExportConf(); export.name = "format" + (_conf.exports.length+1); if (_conf.exports.length > 0) { export.format = _conf.exports[0].format; } dataProvider.addItem(export); }); editFormats.exports.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { editFormats.buttonRemove.enabled = (editFormats.exports.selectedItem != null); }); editFormats.buttonRemove.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var export :ExportConf in editFormats.exports.selectedItems) { dataProvider.removeItem(export); } }); }); updatePublisher(); _win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); }); } protected function setImport (root :File) :void { _libraries.dataProvider.removeAll(); _errors.dataProvider.removeAll(); if (root == null) return; _rootLen = root.nativePath.length + 1; if (_docFinder != null) _docFinder.shutdownNow(); _docFinder = new Executor(); findFlashDocuments(root, _docFinder, true); _win.reload.enabled = true; } protected function showPreviewWindow (lib :XflLibrary) :void { if (_previewController == null || _previewWindow.closed || _previewControls.closed) { _previewWindow = new PreviewWindow(); _previewControls = new PreviewControlsWindow(); _previewWindow.started = function (container :Sprite) :void { _previewController = new PreviewController(lib, container, _previewWindow, _previewControls); } _previewWindow.open(); _previewControls.open(); preventWindowClose(_previewWindow.nativeWindow); preventWindowClose(_previewControls.nativeWindow); } else { _previewController.lib = lib; _previewWindow.nativeWindow.visible = true; _previewControls.nativeWindow.visible = true; } _previewWindow.orderToFront(); _previewControls.orderToFront(); } // Causes a window to be hidden, rather than closed, when its close box is clicked protected static function preventWindowClose (window :NativeWindow) :void { window.addEventListener(Event.CLOSING, function (e :Event) :void { e.preventDefault(); window.visible = false; }); } protected var _previewController :PreviewController; protected var _previewWindow :PreviewWindow; protected var _previewControls :PreviewControlsWindow; protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void { Files.list(base, exec).succeeded.add(function (files :Array) :void { if (exec.isShutdown) return; for each (var file :File in files) { if (Files.hasExtension(file, "xfl")) { if (ignoreXflAtBase) { _errors.dataProvider.addItem(new ParseError(base.nativePath, ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " + base.parent.nativePath + "?")); } else addFlashDocument(file); return; } } for each (file in files) { if (StringUtil.startsWith(file.name, ".", "RECOVER_")) { continue; // Ignore hidden VCS directories, and recovered backups created by Flash } if (file.isDirectory) findFlashDocuments(file, exec); else addFlashDocument(file); } }); } protected function exportFlashDocument (status :DocStatus) :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; _publisher.publish(status.lib); stage.quality = prevQuality; status.updateModified(Ternary.FALSE); } protected function addFlashDocument (file :File) :void { var name :String = file.nativePath.substring(_rootLen).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); break; case "fla": name = name.substr(0, name.lastIndexOf(".")); load = new FlaLoader().load(name, file); break; default: // Unsupported file type, ignore return; } const status :DocStatus = new DocStatus(name, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null); _libraries.dataProvider.addItem(status); load.succeeded.add(function (lib :XflLibrary) :void { status.lib = lib; status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib))); for each (var err :ParseError in lib.getErrors()) _errors.dataProvider.addItem(err); status.updateValid(Ternary.of(lib.valid)); }); load.failed.add(function (error :Error) :void { trace("Failed to load " + file.nativePath + ": " + error); status.updateValid(Ternary.FALSE); throw error; }); } protected var _rootLen :int; protected var _publisher :Publisher; protected var _docFinder :Executor; protected var _win :ExporterWindow; protected var _libraries :DataGrid; protected var _errors :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; protected var _authoredResolution :DropDownList; protected var _conf :FlumpConf = new FlumpConf(); protected var _confFile :File; protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter"); private static const log :Log = Log.getLog(Exporter); } } import flash.events.EventDispatcher; import flump.export.Ternary; import flump.xfl.XflLibrary; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; class DocStatus extends EventDispatcher implements IPropertyChangeNotifier { public var path :String; public var modified :String; public var valid :String = QUESTION; public var lib :XflLibrary; public function DocStatus (path :String, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) { this.lib = lib; this.path = path; _uid = path; updateModified(modified); updateValid(valid); } public function updateValid (newValid :Ternary) :void { changeField("valid", function (..._) :void { if (newValid == Ternary.TRUE) valid = CHECK; else if (newValid == Ternary.FALSE) valid = FROWN; else valid = QUESTION; }); } public function get isValid () :Boolean { return valid == CHECK; } public function updateModified (newModified :Ternary) :void { changeField("modified", function (..._) :void { if (newModified == Ternary.TRUE) modified = CHECK; else if (newModified == Ternary.FALSE) modified = " "; else modified = QUESTION; }); } protected function changeField(fieldName :String, modifier :Function) :void { const oldValue :Object = this[fieldName]; modifier(); const newValue :Object = this[fieldName]; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue)); } public function get uid () :String { return _uid; } public function set uid (uid :String) :void { _uid = uid; } protected var _uid :String; protected static const QUESTION :String = "?"; protected static const FROWN :String = "☹"; protected static const CHECK :String = "✓"; }
// // Flump - Copyright 2012 Three Rings Design package flump.export { import flash.desktop.NativeApplication; import flash.display.NativeMenu; import flash.display.NativeMenuItem; import flash.display.NativeWindow; import flash.display.Stage; import flash.display.StageQuality; import flash.events.Event; import flash.events.MouseEvent; import flash.filesystem.File; import flash.net.SharedObject; import flash.utils.IDataOutput; import flump.executor.Executor; import flump.executor.Future; import flump.export.Ternary; import flump.xfl.ParseError; import flump.xfl.XflLibrary; import mx.collections.ArrayList; import mx.events.CollectionEvent; import mx.events.PropertyChangeEvent; import spark.components.DataGrid; import spark.components.DropDownList; import spark.components.List; import spark.components.Window; import spark.events.GridSelectionEvent; import com.threerings.util.F; import com.threerings.util.Log; import com.threerings.util.StringUtil; import starling.display.Sprite; public class Exporter { public static const NA :NativeApplication = NativeApplication.nativeApplication; public function Exporter (win :ExporterWindow) { Log.setLevel("", Log.INFO); _win = win; _errors = _win.errors; _libraries = _win.libraries; function updatePreviewAndExport (..._) :void { _win.export.enabled = _exportChooser.dir != null && _libraries.selectionLength > 0 && _libraries.selectedItems.some(function (status :DocStatus, ..._) :Boolean { return status.isValid; }); var status :DocStatus = _libraries.selectedItem as DocStatus; _win.preview.enabled = status != null && status.isValid; if (_exportChooser.dir == null) return; _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); } var fileMenuItem :NativeMenuItem; if (NativeApplication.supportsMenu) { // Grab the existing menu on macs. Use an index to get it as it's not going to be // 'File' in all languages fileMenuItem = NA.menu.getItemAt(1); // Add a separator before the existing close command fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 0); } else { _win.nativeWindow.menu = new NativeMenu(); fileMenuItem = _win.nativeWindow.menu.addSubmenu(new NativeMenu(), "File"); } // Add save and save as by index to work with the existing items on Mac // Mac menus have an existing "Close" item, so everything we add should go ahead of that var newMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("New"), 0); newMenuItem.keyEquivalent = "n"; newMenuItem.addEventListener(Event.SELECT, function (..._) :void { _confFile = null; _conf = new FlumpConf(); updatePublisher(); }); var openMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Open..."), 1); openMenuItem.keyEquivalent = "o"; openMenuItem.addEventListener(Event.SELECT, function (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; openConf(); updatePublisher(); }); file.browseForOpen("Open Flump Configuration"); }); fileMenuItem.submenu.addItemAt(new NativeMenuItem("Sep", /*separator=*/true), 2); const saveMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save"), 3); saveMenuItem.keyEquivalent = "s"; function saveConf () :void { Files.write(_confFile, function (out :IDataOutput) :void { // Set directories relative to where this file is being saved. Fall back to absolute // paths if relative paths aren't possible. if (_importChooser.dir != null) { _conf.importDir = _confFile.parent.getRelativePath(_importChooser.dir, /*useDotDot=*/true); if (_conf.importDir == null) _conf.importDir = _importChooser.dir.nativePath; } if (_exportChooser.dir != null) { _conf.exportDir = _confFile.parent.getRelativePath(_exportChooser.dir, /*useDotDot=*/true); if (_conf.exportDir == null) _conf.exportDir = _exportChooser.dir.nativePath; } out.writeUTFBytes(JSON.stringify(_conf, null, /*space=*/2)); }); }; function saveAs (..._) :void { var file :File = new File(); file.addEventListener(Event.SELECT, function (..._) :void { _confFile = file; trace("Conf file is now " + _confFile.nativePath); _settings.data["CONF_FILE"] = _confFile.nativePath; _settings.flush(); saveConf(); }); file.browseForSave("Save Flump Configuration"); }; saveMenuItem.addEventListener(Event.SELECT, function (..._) :void { if (_confFile == null) saveAs(); else saveConf(); }); function openConf () :void { try { _conf = FlumpConf.fromJSON(JSONFormat.readJSON(_confFile)); _win.title = _confFile.name; var dir :String = _confFile.parent.resolvePath(_conf.importDir).nativePath; setImport(new File(dir)); } catch (e :Error) { log.warning("Unable to parse conf", e); _errors.dataProvider.addItem(new ParseError(_confFile.nativePath, ParseError.CRIT, "Unable to read configuration")); _confFile = null; } }; const saveAsMenuItem :NativeMenuItem = fileMenuItem.submenu.addItemAt(new NativeMenuItem("Save As..."), 4); saveAsMenuItem.keyEquivalent = "S"; saveAsMenuItem.addEventListener(Event.SELECT, saveAs); if (_settings.data.hasOwnProperty("CONF_FILE")) { _confFile = new File(_settings.data["CONF_FILE"]); openConf(); } var curSelection :DocStatus = null; _libraries.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { log.info("Changed", "selected", _libraries.selectedIndices); updatePreviewAndExport(); if (curSelection != null) { curSelection.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } var newSelection :DocStatus = _libraries.selectedItem as DocStatus; if (newSelection != null) { newSelection.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, updatePreviewAndExport); } curSelection = newSelection; }); _win.reload.addEventListener(MouseEvent.CLICK, function (..._) :void { setImport(_importChooser.dir); updatePreviewAndExport(); }); _win.export.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var status :DocStatus in _libraries.selectedItems) { exportFlashDocument(status); } }); _win.preview.addEventListener(MouseEvent.CLICK, function (..._) :void { showPreviewWindow(_libraries.selectedItem.lib); }); _importChooser = new DirChooser(null, _win.importRoot, _win.browseImport); _importChooser.changed.add(setImport); _exportChooser = new DirChooser(null, _win.exportRoot, _win.browseExport); _exportChooser.changed.add(updatePreviewAndExport); function updatePublisher (..._) :void { if (_confFile != null) { _importChooser.dir = (_conf.importDir != null) ? _confFile.parent.resolvePath(_conf.importDir) : null; _exportChooser.dir = (_conf.exportDir != null) ? _confFile.parent.resolvePath(_conf.exportDir) : null; } else { _importChooser.dir = null; _exportChooser.dir = null; } if (_exportChooser.dir == null || _conf.exports.length == 0) _publisher = null; else _publisher = new Publisher(_exportChooser.dir, Vector.<ExportConf>(_conf.exports)); var formatNames :Array = []; for each (var export :ExportConf in _conf.exports) formatNames.push(export.name); _win.formatOverview.text = formatNames.join(", "); }; var editFormats :EditFormatsWindow; _win.editFormats.addEventListener(MouseEvent.CLICK, function (..._) :void { if (editFormats == null || editFormats.closed) { editFormats = new EditFormatsWindow(); editFormats.open(); } else editFormats.orderToFront(); var dataProvider :ArrayList = new ArrayList(_conf.exports); dataProvider.addEventListener(CollectionEvent.COLLECTION_CHANGE, updatePublisher); editFormats.exports.dataProvider = dataProvider; editFormats.buttonAdd.addEventListener(MouseEvent.CLICK, function (..._) :void { var export :ExportConf = new ExportConf(); export.name = "format" + (_conf.exports.length+1); if (_conf.exports.length > 0) { export.format = _conf.exports[0].format; } dataProvider.addItem(export); }); editFormats.exports.addEventListener(GridSelectionEvent.SELECTION_CHANGE, function (..._) :void { editFormats.buttonRemove.enabled = (editFormats.exports.selectedItem != null); }); editFormats.buttonRemove.addEventListener(MouseEvent.CLICK, function (..._) :void { for each (var export :ExportConf in editFormats.exports.selectedItems) { dataProvider.removeItem(export); } }); }); updatePublisher(); _win.addEventListener(Event.CLOSE, function (..._) :void { NA.exit(0); }); } protected function setImport (root :File) :void { _libraries.dataProvider.removeAll(); _errors.dataProvider.removeAll(); if (root == null) return; _rootLen = root.nativePath.length + 1; if (_docFinder != null) _docFinder.shutdownNow(); _docFinder = new Executor(); findFlashDocuments(root, _docFinder, true); _win.reload.enabled = true; } protected function showPreviewWindow (lib :XflLibrary) :void { if (_previewController == null || _previewWindow.closed || _previewControls.closed) { _previewWindow = new PreviewWindow(); _previewControls = new PreviewControlsWindow(); _previewWindow.started = function (container :Sprite) :void { _previewController = new PreviewController(lib, container, _previewWindow, _previewControls); } _previewWindow.open(); _previewControls.open(); preventWindowClose(_previewWindow.nativeWindow); preventWindowClose(_previewControls.nativeWindow); } else { _previewController.lib = lib; _previewWindow.nativeWindow.visible = true; _previewControls.nativeWindow.visible = true; } _previewWindow.orderToFront(); _previewControls.orderToFront(); } // Causes a window to be hidden, rather than closed, when its close box is clicked protected static function preventWindowClose (window :NativeWindow) :void { window.addEventListener(Event.CLOSING, function (e :Event) :void { e.preventDefault(); window.visible = false; }); } protected var _previewController :PreviewController; protected var _previewWindow :PreviewWindow; protected var _previewControls :PreviewControlsWindow; protected function findFlashDocuments (base :File, exec :Executor, ignoreXflAtBase :Boolean = false) :void { Files.list(base, exec).succeeded.add(function (files :Array) :void { if (exec.isShutdown) return; for each (var file :File in files) { if (Files.hasExtension(file, "xfl")) { if (ignoreXflAtBase) { _errors.dataProvider.addItem(new ParseError(base.nativePath, ParseError.CRIT, "The import directory can't be an XFL directory, did you mean " + base.parent.nativePath + "?")); } else addFlashDocument(file); return; } } for each (file in files) { if (StringUtil.startsWith(file.name, ".", "RECOVER_")) { continue; // Ignore hidden VCS directories, and recovered backups created by Flash } if (file.isDirectory) findFlashDocuments(file, exec); else addFlashDocument(file); } }); } protected function exportFlashDocument (status :DocStatus) :void { const stage :Stage = NA.activeWindow.stage; const prevQuality :String = stage.quality; stage.quality = StageQuality.BEST; _publisher.publish(status.lib); stage.quality = prevQuality; status.updateModified(Ternary.FALSE); } protected function addFlashDocument (file :File) :void { var name :String = file.nativePath.substring(_rootLen).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); break; case "fla": name = name.substr(0, name.lastIndexOf(".")); load = new FlaLoader().load(name, file); break; default: // Unsupported file type, ignore return; } const status :DocStatus = new DocStatus(name, _rootLen, Ternary.UNKNOWN, Ternary.UNKNOWN, null); _libraries.dataProvider.addItem(status); load.succeeded.add(function (lib :XflLibrary) :void { status.lib = lib; status.updateModified(Ternary.of(_publisher == null || _publisher.modified(lib))); for each (var err :ParseError in lib.getErrors()) _errors.dataProvider.addItem(err); status.updateValid(Ternary.of(lib.valid)); }); load.failed.add(function (error :Error) :void { trace("Failed to load " + file.nativePath + ": " + error); status.updateValid(Ternary.FALSE); throw error; }); } protected var _rootLen :int; protected var _publisher :Publisher; protected var _docFinder :Executor; protected var _win :ExporterWindow; protected var _libraries :DataGrid; protected var _errors :DataGrid; protected var _exportChooser :DirChooser; protected var _importChooser :DirChooser; protected var _authoredResolution :DropDownList; protected var _conf :FlumpConf = new FlumpConf(); protected var _confFile :File; protected const _settings :SharedObject = SharedObject.getLocal("flump/Exporter"); private static const log :Log = Log.getLog(Exporter); } } import flash.events.EventDispatcher; import flump.export.Ternary; import flump.xfl.XflLibrary; import mx.core.IPropertyChangeNotifier; import mx.events.PropertyChangeEvent; class DocStatus extends EventDispatcher implements IPropertyChangeNotifier { public var path :String; public var modified :String; public var valid :String = QUESTION; public var lib :XflLibrary; public function DocStatus (path :String, rootLen :int, modified :Ternary, valid :Ternary, lib :XflLibrary) { this.lib = lib; this.path = path; _uid = path; updateModified(modified); updateValid(valid); } public function updateValid (newValid :Ternary) :void { changeField("valid", function (..._) :void { if (newValid == Ternary.TRUE) valid = CHECK; else if (newValid == Ternary.FALSE) valid = FROWN; else valid = QUESTION; }); } public function get isValid () :Boolean { return valid == CHECK; } public function updateModified (newModified :Ternary) :void { changeField("modified", function (..._) :void { if (newModified == Ternary.TRUE) modified = CHECK; else if (newModified == Ternary.FALSE) modified = " "; else modified = QUESTION; }); } protected function changeField(fieldName :String, modifier :Function) :void { const oldValue :Object = this[fieldName]; modifier(); const newValue :Object = this[fieldName]; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, fieldName, oldValue, newValue)); } public function get uid () :String { return _uid; } public function set uid (uid :String) :void { _uid = uid; } protected var _uid :String; protected static const QUESTION :String = "?"; protected static const FROWN :String = "☹"; protected static const CHECK :String = "✓"; }
Fix for export directory not updating.
Fix for export directory not updating.
ActionScript
mit
mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump
87cd3d40e4fb5a292773b65859c0cc805754fd60
src/aerys/minko/scene/node/AbstractSceneNode.as
src/aerys/minko/scene/node/AbstractSceneNode.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.IRebindableController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.data.TransformDataProvider; import aerys.minko.type.Signal; import aerys.minko.type.clone.CloneOptions; import aerys.minko.type.clone.ControllerCloneAction; import aerys.minko.type.math.Matrix4x4; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * The base class to extend in order to create new scene node types. * * @author Jean-Marc Le Roux * */ public class AbstractSceneNode implements ISceneNode { private static var _id : uint; private var _name : String; private var _root : ISceneNode; private var _parent : Group; private var _transform : Matrix4x4; private var _localToWorld : Matrix4x4; private var _worldToLocal : Matrix4x4; private var _controllers : Vector.<AbstractController>; private var _added : Signal; private var _removed : Signal; private var _addedToScene : Signal; private var _removedFromScene : Signal; private var _controllerAdded : Signal; private var _controllerRemoved : Signal; public function get x() : Number { return _transform.translationX; } public function set x(value : Number) : void { _transform.translationX = value; } public function get y() : Number { return _transform.translationX; } public function set y(value : Number) : void { _transform.translationY = value; } public function get z() : Number { return _transform.translationX; } public function set z(value : Number) : void { _transform.translationZ = value; } public function get rotationX() : Number { return _transform.rotationX; } public function set rotationX(value : Number) : void { _transform.rotationX = value; } public function get rotationY() : Number { return _transform.rotationY; } public function set rotationY(value : Number) : void { _transform.rotationY = value; } public function get rotationZ() : Number { return _transform.rotationZ; } public function set rotationZ(value : Number) : void { _transform.rotationZ = value; } public function get scaleX() : Number { return _transform.scaleX; } public function set scaleX(value : Number) : void { _transform.scaleX = value; } public function get scaleY() : Number { return _transform.scaleX; } public function set scaleY(value : Number) : void { _transform.scaleY = value; } public function get scaleZ() : Number { return _transform.scaleZ; } public function set scaleZ(value : Number) : void { _transform.scaleZ = value; } public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } public function get parent() : Group { return _parent; } public function set parent(value : Group) : void { if (value == _parent) return ; // remove child if (_parent) { var oldParent : Group = _parent; oldParent._children.splice( oldParent.getChildIndex(this), 1 ); parent._numChildren--; oldParent.descendantRemoved.execute(oldParent, this); _parent = null; _removed.execute(this, oldParent); } // set parent _parent = value; // add child if (_parent) { _parent._children[_parent.numChildren] = this; _parent._numChildren++; _parent.descendantAdded.execute(_parent, this); _added.execute(this, _parent); } } public function get root() : ISceneNode { return _root; } public function get transform() : Matrix4x4 { return _transform; } public function get localToWorld() : Matrix4x4 { return _localToWorld; } public function get worldToLocal() : Matrix4x4 { return _worldToLocal; } public function get added() : Signal { return _added; } public function get removed() : Signal { return _removed; } public function get addedToScene() : Signal { return _addedToScene; } public function get removedFromScene() : Signal { return _removedFromScene; } public function get numControllers() : uint { return _controllers.length; } public function get controllerAdded() : Signal { return _controllerAdded; } public function get controllerRemoved() : Signal { return _controllerRemoved; } public function AbstractSceneNode() { initialize(); } private function initialize() : void { _name = getDefaultSceneName(this); _root = this; _transform = new Matrix4x4(); _localToWorld = new Matrix4x4(); _worldToLocal = new Matrix4x4(); _controllers = new <AbstractController>[]; _added = new Signal('AbstractSceneNode.added'); _removed = new Signal('AbstractSceneNode.removed'); _addedToScene = new Signal('AbstractSceneNode.addedToScene'); _removedFromScene = new Signal('AbstractSceneNode.removedFromScene'); _controllerAdded = new Signal('AbstractSceneNode.controllerAdded'); _controllerRemoved = new Signal('AbstractSceneNode.controllerRemoved'); _added.add(addedHandler); _removed.add(removedHandler); _addedToScene.add(addedToSceneHandler); _removedFromScene.add(removedFromSceneHandler); addController(new TransformController()); } protected function addedHandler(child : ISceneNode, parent : Group) : void { _root = _parent ? _parent.root : this; if (_root is Scene) _addedToScene.execute(this, _root); } protected function removedHandler(child : ISceneNode, parent : Group) : void { // update root var oldRoot : ISceneNode = _root; _root = _parent ? _parent.root : this; if (oldRoot is Scene) _removedFromScene.execute(this, oldRoot); } protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } public function addController(controller : AbstractController) : ISceneNode { _controllers.push(controller); controller.addTarget(this); _controllerAdded.execute(this, controller); return this; } public function removeController(controller : AbstractController) : ISceneNode { var numControllers : uint = _controllers.length - 1; _controllers[_controllers.indexOf(controller)] = _controllers[numControllers]; _controllers.length = numControllers; controller.removeTarget(this); _controllerRemoved.execute(this, controller); return this; } public function removeAllControllers() : ISceneNode { while (numControllers) removeController(getController(0)); return this; } public function getController(index : uint) : AbstractController { return _controllers[index]; } public function getControllersByType(type : Class, controllers : Vector.<AbstractController> = null) : Vector.<AbstractController> { controllers ||= new Vector.<AbstractController>(); var nbControllers : uint = numControllers; for (var i : int = 0; i < nbControllers; ++i) { var ctrl : AbstractController = getController(i); if (ctrl is type) controllers.push(ctrl); } return controllers; } public static function getDefaultSceneName(scene : ISceneNode) : String { var className : String = getQualifiedClassName(scene); return className.substr(className.lastIndexOf(':') + 1) + '_' + (++_id); } minko_scene function cloneNode() : AbstractSceneNode { throw new Error('Must be overriden'); } public final function clone(cloneOptions : CloneOptions = null) : ISceneNode { cloneOptions ||= CloneOptions.defaultOptions; // fill up 2 dics with all nodes and controllers var nodeMap : Dictionary = new Dictionary(); var controllerMap : Dictionary = new Dictionary(); listItems(cloneNode(), nodeMap, controllerMap); // clone controllers with respect with instructions cloneControllers(controllerMap, cloneOptions); // rebind all controller dependencies. rebindControllerDependencies(controllerMap, nodeMap, cloneOptions); // add cloned/rebinded/original controllers to clones for (var objNode : Object in nodeMap) { var node : AbstractSceneNode = AbstractSceneNode(objNode); var numControllers : uint = node.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controller : AbstractController = controllerMap[node.getController(controllerId)]; if (controller != null) nodeMap[node].addController(controller); } } return nodeMap[this]; } private function listItems(clonedRoot : ISceneNode, nodes : Dictionary, controllers : Dictionary) : void { var numControllers : uint = this.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) controllers[getController(controllerId)] = true; nodes[this] = clonedRoot; if (this is Group) { var group : Group = Group(this); var clonedGroup : Group = Group(clonedRoot); var numChildren : uint = group.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(group.getChildAt(childId)); var clonedChild : AbstractSceneNode = AbstractSceneNode(clonedGroup.getChildAt(childId)); child.listItems(clonedChild, nodes, controllers); } } } private function cloneControllers(controllerMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (action == ControllerCloneAction.CLONE) controllerMap[controller] = controller.clone(); else if (action == ControllerCloneAction.REASSIGN) controllerMap[controller] = controller; else if (action == ControllerCloneAction.IGNORE) controllerMap[controller] = null; else throw new Error(); } } private function rebindControllerDependencies(controllerMap : Dictionary, nodeMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (controller is IRebindableController && action == ControllerCloneAction.CLONE) IRebindableController(controllerMap[controller]).rebindDependencies(nodeMap, controllerMap); } } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.controller.IRebindableController; import aerys.minko.scene.controller.TransformController; import aerys.minko.scene.data.TransformDataProvider; import aerys.minko.type.Signal; import aerys.minko.type.clone.CloneOptions; import aerys.minko.type.clone.ControllerCloneAction; import aerys.minko.type.math.Matrix4x4; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; use namespace minko_scene; /** * The base class to extend in order to create new scene node types. * * @author Jean-Marc Le Roux * */ public class AbstractSceneNode implements ISceneNode { private static var _id : uint; private var _name : String; private var _root : ISceneNode; private var _parent : Group; private var _transform : Matrix4x4; private var _localToWorld : Matrix4x4; private var _worldToLocal : Matrix4x4; private var _controllers : Vector.<AbstractController>; private var _added : Signal; private var _removed : Signal; private var _addedToScene : Signal; private var _removedFromScene : Signal; private var _controllerAdded : Signal; private var _controllerRemoved : Signal; public function get x() : Number { return _transform.translationX; } public function set x(value : Number) : void { _transform.translationX = value; } public function get y() : Number { return _transform.translationX; } public function set y(value : Number) : void { _transform.translationY = value; } public function get z() : Number { return _transform.translationX; } public function set z(value : Number) : void { _transform.translationZ = value; } public function get rotationX() : Number { return _transform.rotationX; } public function set rotationX(value : Number) : void { _transform.rotationX = value; } public function get rotationY() : Number { return _transform.rotationY; } public function set rotationY(value : Number) : void { _transform.rotationY = value; } public function get rotationZ() : Number { return _transform.rotationZ; } public function set rotationZ(value : Number) : void { _transform.rotationZ = value; } public function get scaleX() : Number { return _transform.scaleX; } public function set scaleX(value : Number) : void { _transform.scaleX = value; } public function get scaleY() : Number { return _transform.scaleY; } public function set scaleY(value : Number) : void { _transform.scaleY = value; } public function get scaleZ() : Number { return _transform.scaleZ; } public function set scaleZ(value : Number) : void { _transform.scaleZ = value; } public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } public function get parent() : Group { return _parent; } public function set parent(value : Group) : void { if (value == _parent) return ; // remove child if (_parent) { var oldParent : Group = _parent; oldParent._children.splice( oldParent.getChildIndex(this), 1 ); parent._numChildren--; oldParent.descendantRemoved.execute(oldParent, this); _parent = null; _removed.execute(this, oldParent); } // set parent _parent = value; // add child if (_parent) { _parent._children[_parent.numChildren] = this; _parent._numChildren++; _parent.descendantAdded.execute(_parent, this); _added.execute(this, _parent); } } public function get root() : ISceneNode { return _root; } public function get transform() : Matrix4x4 { return _transform; } public function get localToWorld() : Matrix4x4 { return _localToWorld; } public function get worldToLocal() : Matrix4x4 { return _worldToLocal; } public function get added() : Signal { return _added; } public function get removed() : Signal { return _removed; } public function get addedToScene() : Signal { return _addedToScene; } public function get removedFromScene() : Signal { return _removedFromScene; } public function get numControllers() : uint { return _controllers.length; } public function get controllerAdded() : Signal { return _controllerAdded; } public function get controllerRemoved() : Signal { return _controllerRemoved; } public function AbstractSceneNode() { initialize(); } private function initialize() : void { _name = getDefaultSceneName(this); _root = this; _transform = new Matrix4x4(); _localToWorld = new Matrix4x4(); _worldToLocal = new Matrix4x4(); _controllers = new <AbstractController>[]; _added = new Signal('AbstractSceneNode.added'); _removed = new Signal('AbstractSceneNode.removed'); _addedToScene = new Signal('AbstractSceneNode.addedToScene'); _removedFromScene = new Signal('AbstractSceneNode.removedFromScene'); _controllerAdded = new Signal('AbstractSceneNode.controllerAdded'); _controllerRemoved = new Signal('AbstractSceneNode.controllerRemoved'); _added.add(addedHandler); _removed.add(removedHandler); _addedToScene.add(addedToSceneHandler); _removedFromScene.add(removedFromSceneHandler); addController(new TransformController()); } protected function addedHandler(child : ISceneNode, parent : Group) : void { _root = _parent ? _parent.root : this; if (_root is Scene) _addedToScene.execute(this, _root); } protected function removedHandler(child : ISceneNode, parent : Group) : void { // update root var oldRoot : ISceneNode = _root; _root = _parent ? _parent.root : this; if (oldRoot is Scene) _removedFromScene.execute(this, oldRoot); } protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } public function addController(controller : AbstractController) : ISceneNode { _controllers.push(controller); controller.addTarget(this); _controllerAdded.execute(this, controller); return this; } public function removeController(controller : AbstractController) : ISceneNode { var numControllers : uint = _controllers.length - 1; _controllers[_controllers.indexOf(controller)] = _controllers[numControllers]; _controllers.length = numControllers; controller.removeTarget(this); _controllerRemoved.execute(this, controller); return this; } public function removeAllControllers() : ISceneNode { while (numControllers) removeController(getController(0)); return this; } public function getController(index : uint) : AbstractController { return _controllers[index]; } public function getControllersByType(type : Class, controllers : Vector.<AbstractController> = null) : Vector.<AbstractController> { controllers ||= new Vector.<AbstractController>(); var nbControllers : uint = numControllers; for (var i : int = 0; i < nbControllers; ++i) { var ctrl : AbstractController = getController(i); if (ctrl is type) controllers.push(ctrl); } return controllers; } public static function getDefaultSceneName(scene : ISceneNode) : String { var className : String = getQualifiedClassName(scene); return className.substr(className.lastIndexOf(':') + 1) + '_' + (++_id); } minko_scene function cloneNode() : AbstractSceneNode { throw new Error('Must be overriden'); } public final function clone(cloneOptions : CloneOptions = null) : ISceneNode { cloneOptions ||= CloneOptions.defaultOptions; // fill up 2 dics with all nodes and controllers var nodeMap : Dictionary = new Dictionary(); var controllerMap : Dictionary = new Dictionary(); listItems(cloneNode(), nodeMap, controllerMap); // clone controllers with respect with instructions cloneControllers(controllerMap, cloneOptions); // rebind all controller dependencies. rebindControllerDependencies(controllerMap, nodeMap, cloneOptions); // add cloned/rebinded/original controllers to clones for (var objNode : Object in nodeMap) { var node : AbstractSceneNode = AbstractSceneNode(objNode); var numControllers : uint = node.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controller : AbstractController = controllerMap[node.getController(controllerId)]; if (controller != null) nodeMap[node].addController(controller); } } return nodeMap[this]; } private function listItems(clonedRoot : ISceneNode, nodes : Dictionary, controllers : Dictionary) : void { var numControllers : uint = this.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) controllers[getController(controllerId)] = true; nodes[this] = clonedRoot; if (this is Group) { var group : Group = Group(this); var clonedGroup : Group = Group(clonedRoot); var numChildren : uint = group.numChildren; for (var childId : uint = 0; childId < numChildren; ++childId) { var child : AbstractSceneNode = AbstractSceneNode(group.getChildAt(childId)); var clonedChild : AbstractSceneNode = AbstractSceneNode(clonedGroup.getChildAt(childId)); child.listItems(clonedChild, nodes, controllers); } } } private function cloneControllers(controllerMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (action == ControllerCloneAction.CLONE) controllerMap[controller] = controller.clone(); else if (action == ControllerCloneAction.REASSIGN) controllerMap[controller] = controller; else if (action == ControllerCloneAction.IGNORE) controllerMap[controller] = null; else throw new Error(); } } private function rebindControllerDependencies(controllerMap : Dictionary, nodeMap : Dictionary, cloneOptions : CloneOptions) : void { for (var objController : Object in controllerMap) { var controller : AbstractController = AbstractController(objController); var action : uint = cloneOptions.getActionForController(controller); if (controller is IRebindableController && action == ControllerCloneAction.CLONE) IRebindableController(controllerMap[controller]).rebindDependencies(nodeMap, controllerMap); } } } }
Update src/aerys/minko/scene/node/AbstractSceneNode.as
Update src/aerys/minko/scene/node/AbstractSceneNode.as BUG:scaleY 
ActionScript
mit
aerys/minko-as3
6a1efa70477256e66a542ed0822aae606841c063
WEB-INF/lps/lfc/kernel/swf9/LzXMLTranslator.as
WEB-INF/lps/lfc/kernel/swf9/LzXMLTranslator.as
/** * LzXMLTranslator.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 */ /** * @shortdesc: Utility for converting native XML DOM object into LzDataNode tree */ public class LzXMLTranslator { static function copyXML (xmlobj:XML, trimwhitespace:Boolean, nsprefix:Boolean) :LzDataElement { var lfcnode:LzDataNodeMixin = copyFlashXML(xmlobj, trimwhitespace, nsprefix); if (lfcnode == null) { trace('LzXMLTranslator.copyXML: lfcnode.children is null', lfcnode); } if (lfcnode is LzDataText) { return null; } // create a new, empty ownerDocument (LPP-7537) new LzDataElement(null, {}, [lfcnode]); return (lfcnode cast LzDataElement); } static const whitespaceChars :Object = {' ': true, '\r': true, '\n': true, '\t': true}; /** * trim whitespace from start and end of string * @access private */ static function trim (str:String) :String { var whitech:Object = whitespaceChars; var len:int = str.length; var sindex:int = 0; var eindex:int = str.length -1; var ch:String; while (sindex < len) { ch = str.charAt(sindex); if (whitech[ch] != true) break; sindex++; } while (eindex > sindex) { ch = str.charAt(eindex); if (whitech[ch] != true) break; eindex--; } return str.slice(sindex,eindex+1); } // Recursively copy a Flash XML(Node) tree into a LzDataElement // tree. Used by LzDataNode.stringToLzData /** * @param boolean trimwhitespace: trim whitespace from start and end of text nodes * @param boolean nsprefix: preserve namespace prefixes on node names and attribute names * @access private */ static function copyFlashXML (node:XML, trimwhitespace:Boolean, nsprefix:Boolean) :LzDataNodeMixin { var lfcnode:LzDataNodeMixin = null; // text node? if (node.nodeKind() == 'text') { var nv:String = node.toString(); if (trimwhitespace == true) { nv = trim(nv); } lfcnode = new LzDataText(nv); //PBR Changed to match swf kernel // } else if (node.nodeKind() == 'element') { } else { var nattrs:XMLList = node.attributes(); var cattrs:Object = {}; for (var i:int = 0; i < nattrs.length(); i++) { var attr:XML = nattrs[i]; var qattr:QName = attr.name(); if (nsprefix) { var ns:Namespace = attr.namespace(); var key:String; if (ns != null && ns.prefix != "") { key = ns.prefix + ":" + qattr.localName; } else { key = qattr.localName; } cattrs[key] = attr.toString(); } else { cattrs[qattr.localName] = attr.toString(); } } var nsDecl:Array = node.namespaceDeclarations(); for (var i:int = 0; i < nsDecl.length; ++i) { var ns:Namespace = nsDecl[i]; var prefix:String = ns.prefix; var key:String = (prefix == "" ? "xmlns" : nsprefix ? "xmlns:" + prefix : prefix); cattrs[key] = ns.uri; } var nname:String; var qname:QName = node.name(); if (nsprefix) { var ns:Namespace = node.namespace(); if (ns != null && ns.prefix != "") { nname = ns.prefix + ":" + qname.localName; } else { nname = qname.localName; } } else { nname = qname.localName; } lfcnode = new LzDataElement(nname, cattrs); var children:XMLList = node.children(); var newchildren:Array = []; for (var i:int = 0; i < children.length(); i++) { var child:XML = children[i]; var lfcchild:LzDataNodeMixin = copyFlashXML(child, trimwhitespace, nsprefix); newchildren[i] = lfcchild; } (lfcnode cast LzDataElement).$lzc$set_childNodes(newchildren); } return lfcnode; } } // End of LzXMLTranslator
/** * LzXMLTranslator.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 */ /** * @shortdesc: Utility for converting native XML DOM object into LzDataNode tree */ public class LzXMLTranslator { /** * LzXMLTranslator interface */ static function copyXML (xmlobj:XML, trimwhitespace:Boolean, nsprefix:Boolean) :LzDataElement { var lfcnode:LzDataNodeMixin = copyFlashXML(xmlobj, trimwhitespace, nsprefix); return (lfcnode cast LzDataElement); } private static function nextSibling (node:XML) :XML { var p:XML = node.parent(); return p ? p.children()[node.childIndex() + 1] : null; } private static function firstChild (node:XML) :XML { return node.children()[0]; } /** * Translate a single Flash XML(Node) into a LzDataNode. */ static function copyFlashNode (node:XML, trimwhitespace:Boolean, nsprefix:Boolean) :LzDataNodeMixin { var kind:String = node.nodeKind(); if (kind == 'text') { var nv:String = node.toString(); if (trimwhitespace) { nv = LzDataElement.trim(nv); } return new LzDataText(nv); } else if (kind == 'element') { var nname:String; var qname:QName = node.name(); if (nsprefix) { var ns:Namespace = node.namespace(); if (ns != null && ns.prefix != "") { nname = ns.prefix + ":" + qname.localName; } else { nname = qname.localName; } } else { nname = qname.localName; } var nattrs:XMLList = node.attributes(); var cattrs:Object = {}; for (var i:int = 0, len:int = nattrs.length(); i < len; i++) { var attr:XML = nattrs[i]; var qattr:QName = attr.name(); if (nsprefix) { var ns:Namespace = attr.namespace(); var key:String; if (ns != null && ns.prefix != "") { key = ns.prefix + ":" + qattr.localName; } else { key = qattr.localName; } cattrs[key] = attr.toString(); } else { cattrs[qattr.localName] = attr.toString(); } } var nsDecl:Array = node.namespaceDeclarations(); for (var i:int = 0, len:int = nsDecl.length; i < len; ++i) { var ns:Namespace = nsDecl[i]; var prefix:String = ns.prefix; var key:String = (prefix == "" ? "xmlns" : nsprefix ? "xmlns:" + prefix : prefix); cattrs[key] = ns.uri; } var lfcnode:LzDataElement = new LzDataElement(nname); // avoid copy of cattrs (see LzDataElement ctor) lfcnode.attributes = cattrs; return lfcnode; } else { return null; } } /** * Copy a Flash XML(Node) tree into a LzDataElement tree. Used by LzDataElement.stringToLzData * * @param boolean trimwhitespace: trim whitespace from start and end of text nodes * @param boolean nsprefix: preserve namespace prefixes on node names and attribute names * @access private */ static function copyFlashXML (xmlnode:XML, trimwhitespace:Boolean, nsprefix:Boolean) :LzDataNodeMixin { // create a new, empty ownerDocument (LPP-7537) var document:LzDataElement = new LzDataElement(null); // handle this separately so you don't need to worry about the // case when xmlnode has got siblings if (! firstChild(xmlnode)) { return document.appendChild(copyFlashNode(xmlnode, trimwhitespace, nsprefix)); } var lfcparent:LzDataElement = document; var next:XML, node:XML = xmlnode; // traverse DOM tree for (;;) { var kind:String = node.nodeKind(); if (kind == 'text') { var lfctext:LzDataText = LzDataText(copyFlashNode(node, trimwhitespace, nsprefix)); // inlined lfcparent.appendChild(lfcnode) lfctext.parentNode = lfcparent; lfctext.ownerDocument = document; lfctext.__LZo = (lfcparent.childNodes.push(lfctext) - 1); } else if (kind == 'element') { var lfcnode:LzDataElement = LzDataElement(copyFlashNode(node, trimwhitespace, nsprefix)); // inlined lfcparent.appendChild(lfcnode) lfcnode.parentNode = lfcparent; lfcnode.ownerDocument = document; lfcnode.__LZo = (lfcparent.childNodes.push(lfcnode) - 1); // traverse down first if ((next = firstChild(node))) { // this node is the new context lfcparent = lfcnode; node = next; continue; } } // select next node while (! (next = nextSibling(node))) { // no nextSibling, go back in DOM node = node.parent(); lfcparent = lfcparent.parentNode; if (node === xmlnode) { // reached top element, copy finished return document.childNodes[0]; } } node = next; } // add return to make flash compiler happy return null; } } // End of LzXMLTranslator
Change 20090516-bargull-NOm by bargull@dell--p4--2-53 on 2009-05-16 00:21:34 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20090516-bargull-NOm by bargull@dell--p4--2-53 on 2009-05-16 00:21:34 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk Summary: copy native xml-tree iteratively (SWF9) New Features: Bugs Fixed: LPP-8067 (Improve data performance) (SWF9) Technical Reviewer: henry QA Reviewer: (pending) Doc Reviewer: (pending) Documentation: Release Notes: Details: Remove recursion in copyFlashXML() when traversing the DOM tree. This is similar to the changes for the DHTML and SWF8 kernel. Tests: smokecheck, alldata in swf9 git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@13927 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
9c0ab25999330d05a24854c8ef0d448fe0494490
bin/Data/Scripts/Editor/EditorViewDebugIcons.as
bin/Data/Scripts/Editor/EditorViewDebugIcons.as
// Editor debug icons BillboardSet@ debugIconsSetDirectionalLights; BillboardSet@ debugIconsSetSpotLights; BillboardSet@ debugIconsSetPointLights; BillboardSet@ debugIconsSetCameras; BillboardSet@ debugIconsSetSoundSources; BillboardSet@ debugIconsSetSoundSources3D; BillboardSet@ debugIconsSetSoundListeners; BillboardSet@ debugIconsSetZones; BillboardSet@ debugIconsSetSplinesPoints; Node@ debugIconsNode = null; int stepDebugIconsUpdate = 30; //ms int timeToNextDebugIconsUpdate = 0; const int splinePathResolution = 16; bool debugIconsShow = true; Vector2 debugIconsSize = Vector2(0.025, 0.025); Vector2 debugIconsSizeSmall = debugIconsSize / 2.0; void CreateDebugIcons() { if (editorScene is null) return; debugIconsSetDirectionalLights = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetDirectionalLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconLight.xml"); debugIconsSetDirectionalLights.material.renderOrder = 255; debugIconsSetDirectionalLights.sorted = true; debugIconsSetDirectionalLights.temporary = true; debugIconsSetDirectionalLights.viewMask = 0x80000000; debugIconsSetSpotLights = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSpotLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconSpotLight.xml"); debugIconsSetSpotLights.material.renderOrder = 255; debugIconsSetSpotLights.sorted = true; debugIconsSetSpotLights.temporary = true; debugIconsSetSpotLights.viewMask = 0x80000000; debugIconsSetPointLights = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetPointLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconPointLight.xml"); debugIconsSetPointLights.material.renderOrder = 255; debugIconsSetPointLights.sorted = true; debugIconsSetPointLights.temporary = true; debugIconsSetPointLights.viewMask = 0x80000000; debugIconsSetCameras = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetCameras.material = cache.GetResource("Material", "Materials/Editor/DebugIconCamera.xml"); debugIconsSetCameras.material.renderOrder = 255; debugIconsSetCameras.sorted = true; debugIconsSetCameras.temporary = true; debugIconsSetCameras.viewMask = 0x80000000; debugIconsSetSoundSources = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSoundSources.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundSource.xml"); debugIconsSetSoundSources.material.renderOrder = 255; debugIconsSetSoundSources.sorted = true; debugIconsSetSoundSources.temporary = true; debugIconsSetSoundSources.viewMask = 0x80000000; debugIconsSetSoundSources3D = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSoundSources3D.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundSource.xml"); debugIconsSetSoundSources3D.material.renderOrder = 255; debugIconsSetSoundSources3D.sorted = true; debugIconsSetSoundSources3D.temporary = true; debugIconsSetSoundSources3D.viewMask = 0x80000000; debugIconsSetSoundListeners = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSoundListeners.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundListener.xml"); debugIconsSetSoundListeners.material.renderOrder = 255; debugIconsSetSoundListeners.sorted = true; debugIconsSetSoundListeners.temporary = true; debugIconsSetSoundListeners.viewMask = 0x80000000; debugIconsSetZones = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetZones.material = cache.GetResource("Material", "Materials/Editor/DebugIconZone.xml"); debugIconsSetZones.material.renderOrder = 255; debugIconsSetZones.sorted = true; debugIconsSetZones.temporary = true; debugIconsSetZones.viewMask = 0x80000000; debugIconsSetSplinesPoints = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSplinesPoints.material = cache.GetResource("Material", "Materials/Editor/DebugIconSplinePathPoint.xml"); debugIconsSetSplinesPoints.material.renderOrder = 255; debugIconsSetSplinesPoints.sorted = true; debugIconsSetSplinesPoints.temporary = true; debugIconsSetSplinesPoints.viewMask = 0x80000000; } void UpdateViewDebugIcons() { if (timeToNextDebugIconsUpdate > time.systemTime) return; if (editorScene is null) 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 they at once BillboardSet@ bbs = debugIconsNode.GetComponent("BillboardSet"); if (bbs is null) { CreateDebugIcons(); } Vector3 camPos = cameraNode.worldPosition; if (debugIconsSetPointLights !is null) { debugIconsSetDirectionalLights.enabled = debugIconsShow; debugIconsSetSpotLights.enabled = debugIconsShow; debugIconsSetPointLights.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("Light", true); if (nodes.length > 0) { debugIconsSetDirectionalLights.numBillboards = 0; debugIconsSetSpotLights.numBillboards = 0; debugIconsSetPointLights.numBillboards = 0; debugIconsSetPointLights.Commit(); debugIconsSetSpotLights.Commit(); debugIconsSetDirectionalLights.Commit(); debugIconsSetDirectionalLights.numBillboards = nodes.length; debugIconsSetSpotLights.numBillboards = nodes.length; debugIconsSetPointLights.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Light@ light = nodes[i].GetComponent("Light"); if (light.lightType == LIGHT_POINT) { Billboard@ bb = debugIconsSetPointLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } else if (light.lightType == LIGHT_DIRECTIONAL) { Billboard@ bb = debugIconsSetDirectionalLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } else if (light.lightType == LIGHT_SPOT) { Billboard@ bb = debugIconsSetSpotLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } } debugIconsSetPointLights.Commit(); debugIconsSetSpotLights.Commit(); debugIconsSetDirectionalLights.Commit(); } } if (debugIconsSetCameras !is null) { debugIconsSetCameras.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("Camera", true); if (nodes.length > 0) { debugIconsSetCameras.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Camera@ camera = nodes[i].GetComponent("Camera"); Billboard@ bb = debugIconsSetCameras.billboards[i]; bb.position = nodes[i].worldPosition; // if mainCamera enough closer to selected camera then make bb size relative to distance float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } debugIconsSetCameras.Commit(); } } if (debugIconsSetSoundSources !is null) { debugIconsSetSoundSources.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundSource", true); if (nodes.length > 0) { debugIconsSetSoundSources.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundSource"); Billboard@ bb = debugIconsSetSoundSources.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundSources.Commit(); } } if (debugIconsSetSoundSources3D !is null) { debugIconsSetSoundSources3D.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundSource3D", true); if (nodes.length > 0) { debugIconsSetSoundSources3D.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundSource3D"); Billboard@ bb = debugIconsSetSoundSources3D.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundSources3D.Commit(); } } if (debugIconsSetSoundListeners !is null) { debugIconsSetSoundListeners.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundListener" , true); if (nodes.length > 0) { debugIconsSetSoundListeners.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundListener"); Billboard@ bb = debugIconsSetSoundListeners.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundListeners.Commit(); } } if (debugIconsSetZones !is null) { debugIconsSetZones.enabled = debugIconsShow; // Collect all scene's Zones and add it Array<Node@> nodes = editorScene.GetChildrenWithComponent("Zone", true); Zone@ zone = editorScene.GetComponent("Zone"); if (zone !is null) { debugIconsSetZones.numBillboards = 1; Billboard@ bb = debugIconsSetZones.billboards[0]; bb.position = Vector3(0,0,0); float distance = (camPos - bb.position).length; bb.size = debugIconsSize * distance; //bb.color = zone.ambientColor; bb.enabled = zone.enabled; } if (nodes.length > 0) { debugIconsSetZones.numBillboards = 1 + nodes.length; for (int i=0;i<nodes.length; i++) { Zone@ zone = nodes[i].GetComponent("Zone"); Billboard@ bb = debugIconsSetZones.billboards[i+1]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; //bb.color = zone.ambientColor; bb.enabled = zone.enabled; } debugIconsSetZones.Commit(); } } if (debugIconsSetSplinesPoints !is null) { debugIconsSetSplinesPoints.enabled = debugIconsShow; // Collect all scene's SplinePath and add it Array<Node@> nodes = editorScene.GetChildrenWithComponent("SplinePath", true); if (nodes.length > 0) { debugIconsSetSplinesPoints.numBillboards = nodes.length * splinePathResolution; float splineStep = 1.0f / splinePathResolution; for(int i=0; i < nodes.length; i++) { SplinePath@ sp = nodes[i].GetComponent("SplinePath"); if(sp !is null) { Vector3 splinePoint; // Create path for(int step=0; step < splinePathResolution; step++) { splinePoint = sp.GetPoint(splineStep * step); float distance = (camPos - splinePoint).length; int index = (i * splinePathResolution) + step; Billboard@ bb = debugIconsSetSplinesPoints.billboards[index]; bb.position = splinePoint; bb.size = debugIconsSizeSmall * distance; //bb.color = Color(1,1,0); bb.enabled = sp.enabled; } } } debugIconsSetSplinesPoints.Commit(); } } timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate; }
// Editor debug icons BillboardSet@ debugIconsSetDirectionalLights; BillboardSet@ debugIconsSetSpotLights; BillboardSet@ debugIconsSetPointLights; BillboardSet@ debugIconsSetCameras; BillboardSet@ debugIconsSetSoundSources; BillboardSet@ debugIconsSetSoundSources3D; BillboardSet@ debugIconsSetSoundListeners; BillboardSet@ debugIconsSetZones; BillboardSet@ debugIconsSetSplinesPoints; Node@ debugIconsNode = null; int stepDebugIconsUpdate = 40; //ms int timeToNextDebugIconsUpdate = 0; const int splinePathResolution = 16; bool debugIconsShow = true; Vector2 debugIconsSize = Vector2(0.025, 0.025); Vector2 debugIconsSizeSmall = debugIconsSize / 2.0; void CreateDebugIcons() { if (editorScene is null) return; debugIconsSetDirectionalLights = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetDirectionalLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconLight.xml"); debugIconsSetDirectionalLights.material.renderOrder = 255; debugIconsSetDirectionalLights.sorted = true; debugIconsSetDirectionalLights.temporary = true; debugIconsSetDirectionalLights.viewMask = 0x80000000; debugIconsSetSpotLights = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSpotLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconSpotLight.xml"); debugIconsSetSpotLights.material.renderOrder = 255; debugIconsSetSpotLights.sorted = true; debugIconsSetSpotLights.temporary = true; debugIconsSetSpotLights.viewMask = 0x80000000; debugIconsSetPointLights = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetPointLights.material = cache.GetResource("Material", "Materials/Editor/DebugIconPointLight.xml"); debugIconsSetPointLights.material.renderOrder = 255; debugIconsSetPointLights.sorted = true; debugIconsSetPointLights.temporary = true; debugIconsSetPointLights.viewMask = 0x80000000; debugIconsSetCameras = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetCameras.material = cache.GetResource("Material", "Materials/Editor/DebugIconCamera.xml"); debugIconsSetCameras.material.renderOrder = 255; debugIconsSetCameras.sorted = true; debugIconsSetCameras.temporary = true; debugIconsSetCameras.viewMask = 0x80000000; debugIconsSetSoundSources = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSoundSources.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundSource.xml"); debugIconsSetSoundSources.material.renderOrder = 255; debugIconsSetSoundSources.sorted = true; debugIconsSetSoundSources.temporary = true; debugIconsSetSoundSources.viewMask = 0x80000000; debugIconsSetSoundSources3D = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSoundSources3D.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundSource.xml"); debugIconsSetSoundSources3D.material.renderOrder = 255; debugIconsSetSoundSources3D.sorted = true; debugIconsSetSoundSources3D.temporary = true; debugIconsSetSoundSources3D.viewMask = 0x80000000; debugIconsSetSoundListeners = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSoundListeners.material = cache.GetResource("Material", "Materials/Editor/DebugIconSoundListener.xml"); debugIconsSetSoundListeners.material.renderOrder = 255; debugIconsSetSoundListeners.sorted = true; debugIconsSetSoundListeners.temporary = true; debugIconsSetSoundListeners.viewMask = 0x80000000; debugIconsSetZones = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetZones.material = cache.GetResource("Material", "Materials/Editor/DebugIconZone.xml"); debugIconsSetZones.material.renderOrder = 255; debugIconsSetZones.sorted = true; debugIconsSetZones.temporary = true; debugIconsSetZones.viewMask = 0x80000000; debugIconsSetSplinesPoints = debugIconsNode.CreateComponent("BillboardSet"); debugIconsSetSplinesPoints.material = cache.GetResource("Material", "Materials/Editor/DebugIconSplinePathPoint.xml"); debugIconsSetSplinesPoints.material.renderOrder = 255; debugIconsSetSplinesPoints.sorted = true; debugIconsSetSplinesPoints.temporary = true; debugIconsSetSplinesPoints.viewMask = 0x80000000; } void UpdateViewDebugIcons() { if (timeToNextDebugIconsUpdate > time.systemTime) return; if (editorScene is null) 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 they at once BillboardSet@ bbs = debugIconsNode.GetComponent("BillboardSet"); if (bbs is null) { CreateDebugIcons(); } Vector3 camPos = cameraNode.worldPosition; if (debugIconsSetPointLights !is null) { debugIconsSetDirectionalLights.enabled = debugIconsShow; debugIconsSetSpotLights.enabled = debugIconsShow; debugIconsSetPointLights.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("Light", true); if (nodes.length > 0) { debugIconsSetDirectionalLights.numBillboards = 0; debugIconsSetSpotLights.numBillboards = 0; debugIconsSetPointLights.numBillboards = 0; debugIconsSetPointLights.Commit(); debugIconsSetSpotLights.Commit(); debugIconsSetDirectionalLights.Commit(); debugIconsSetDirectionalLights.numBillboards = nodes.length; debugIconsSetSpotLights.numBillboards = nodes.length; debugIconsSetPointLights.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Light@ light = nodes[i].GetComponent("Light"); if (light.lightType == LIGHT_POINT) { Billboard@ bb = debugIconsSetPointLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } else if (light.lightType == LIGHT_DIRECTIONAL) { Billboard@ bb = debugIconsSetDirectionalLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } else if (light.lightType == LIGHT_SPOT) { Billboard@ bb = debugIconsSetSpotLights.billboards[i]; bb.position = nodes[i].worldPosition; bb.color = light.effectiveColor; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } } debugIconsSetPointLights.Commit(); debugIconsSetSpotLights.Commit(); debugIconsSetDirectionalLights.Commit(); } } if (debugIconsSetCameras !is null) { debugIconsSetCameras.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("Camera", true); if (nodes.length > 0) { debugIconsSetCameras.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Camera@ camera = nodes[i].GetComponent("Camera"); Billboard@ bb = debugIconsSetCameras.billboards[i]; bb.position = nodes[i].worldPosition; // if mainCamera enough closer to selected camera then make bb size relative to distance float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = true; } debugIconsSetCameras.Commit(); } } if (debugIconsSetSoundSources !is null) { debugIconsSetSoundSources.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundSource", true); if (nodes.length > 0) { debugIconsSetSoundSources.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundSource"); Billboard@ bb = debugIconsSetSoundSources.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundSources.Commit(); } } if (debugIconsSetSoundSources3D !is null) { debugIconsSetSoundSources3D.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundSource3D", true); if (nodes.length > 0) { debugIconsSetSoundSources3D.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundSource3D"); Billboard@ bb = debugIconsSetSoundSources3D.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundSources3D.Commit(); } } if (debugIconsSetSoundListeners !is null) { debugIconsSetSoundListeners.enabled = debugIconsShow; Array<Node@> nodes = editorScene.GetChildrenWithComponent("SoundListener" , true); if (nodes.length > 0) { debugIconsSetSoundListeners.numBillboards = nodes.length; for (int i=0;i<nodes.length; i++) { Component@ component = nodes[i].GetComponent("SoundListener"); Billboard@ bb = debugIconsSetSoundListeners.billboards[i]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; bb.enabled = component.enabled; } debugIconsSetSoundListeners.Commit(); } } if (debugIconsSetZones !is null) { debugIconsSetZones.enabled = debugIconsShow; // Collect all scene's Zones and add it Array<Node@> nodes = editorScene.GetChildrenWithComponent("Zone", true); Zone@ zone = editorScene.GetComponent("Zone"); if (zone !is null) { debugIconsSetZones.numBillboards = 1; Billboard@ bb = debugIconsSetZones.billboards[0]; bb.position = Vector3(0,0,0); float distance = (camPos - bb.position).length; bb.size = debugIconsSize * distance; //bb.color = zone.ambientColor; bb.enabled = zone.enabled; } if (nodes.length > 0) { debugIconsSetZones.numBillboards = 1 + nodes.length; for (int i=0;i<nodes.length; i++) { Zone@ zone = nodes[i].GetComponent("Zone"); Billboard@ bb = debugIconsSetZones.billboards[i+1]; bb.position = nodes[i].worldPosition; float distance = (camPos - nodes[i].worldPosition).length; bb.size = debugIconsSize * distance; //bb.color = zone.ambientColor; bb.enabled = zone.enabled; } debugIconsSetZones.Commit(); } } if (debugIconsSetSplinesPoints !is null) { debugIconsSetSplinesPoints.enabled = debugIconsShow; // Collect all scene's SplinePath and add it Array<Node@> nodes = editorScene.GetChildrenWithComponent("SplinePath", true); if (nodes.length > 0) { debugIconsSetSplinesPoints.numBillboards = nodes.length * splinePathResolution; float splineStep = 1.0f / splinePathResolution; for(int i=0; i < nodes.length; i++) { SplinePath@ sp = nodes[i].GetComponent("SplinePath"); if(sp !is null) { Vector3 splinePoint; // Create path for(int step=0; step < splinePathResolution; step++) { splinePoint = sp.GetPoint(splineStep * step); float distance = (camPos - splinePoint).length; int index = (i * splinePathResolution) + step; Billboard@ bb = debugIconsSetSplinesPoints.billboards[index]; bb.position = splinePoint; bb.size = debugIconsSizeSmall * distance; if (step == 0) { bb.color = Color(1,1,0); bb.size = debugIconsSize * distance; } else if ((step+1) >= (splinePathResolution - splineStep)) { bb.color = Color(0,1,0); bb.size = debugIconsSize * distance; } else { bb.color = Color(1,1,1); bb.size = debugIconsSizeSmall * distance; } bb.enabled = sp.enabled; } } } debugIconsSetSplinesPoints.Commit(); } } timeToNextDebugIconsUpdate = time.systemTime + stepDebugIconsUpdate; }
add begin and end of splinepath coloring
add begin and end of splinepath coloring
ActionScript
mit
bacsmar/Urho3D,xiliu98/Urho3D,weitjong/Urho3D,cosmy1/Urho3D,fire/Urho3D-1,fire/Urho3D-1,victorholt/Urho3D,SirNate0/Urho3D,c4augustus/Urho3D,cosmy1/Urho3D,carnalis/Urho3D,orefkov/Urho3D,xiliu98/Urho3D,SuperWangKai/Urho3D,weitjong/Urho3D,PredatorMF/Urho3D,fire/Urho3D-1,kostik1337/Urho3D,helingping/Urho3D,kostik1337/Urho3D,xiliu98/Urho3D,tommy3/Urho3D,urho3d/Urho3D,codedash64/Urho3D,xiliu98/Urho3D,abdllhbyrktr/Urho3D,PredatorMF/Urho3D,kostik1337/Urho3D,bacsmar/Urho3D,rokups/Urho3D,eugeneko/Urho3D,orefkov/Urho3D,carnalis/Urho3D,MeshGeometry/Urho3D,rokups/Urho3D,299299/Urho3D,299299/Urho3D,henu/Urho3D,helingping/Urho3D,tommy3/Urho3D,MeshGeometry/Urho3D,SuperWangKai/Urho3D,SirNate0/Urho3D,orefkov/Urho3D,urho3d/Urho3D,iainmerrick/Urho3D,299299/Urho3D,codemon66/Urho3D,weitjong/Urho3D,urho3d/Urho3D,c4augustus/Urho3D,SirNate0/Urho3D,victorholt/Urho3D,bacsmar/Urho3D,SuperWangKai/Urho3D,henu/Urho3D,codemon66/Urho3D,299299/Urho3D,299299/Urho3D,codemon66/Urho3D,SirNate0/Urho3D,codemon66/Urho3D,abdllhbyrktr/Urho3D,henu/Urho3D,victorholt/Urho3D,luveti/Urho3D,rokups/Urho3D,victorholt/Urho3D,rokups/Urho3D,kostik1337/Urho3D,rokups/Urho3D,henu/Urho3D,PredatorMF/Urho3D,iainmerrick/Urho3D,luveti/Urho3D,carnalis/Urho3D,kostik1337/Urho3D,MeshGeometry/Urho3D,MonkeyFirst/Urho3D,MonkeyFirst/Urho3D,MonkeyFirst/Urho3D,codedash64/Urho3D,eugeneko/Urho3D,c4augustus/Urho3D,bacsmar/Urho3D,SuperWangKai/Urho3D,MonkeyFirst/Urho3D,tommy3/Urho3D,codedash64/Urho3D,cosmy1/Urho3D,luveti/Urho3D,helingping/Urho3D,codedash64/Urho3D,MeshGeometry/Urho3D,abdllhbyrktr/Urho3D,SuperWangKai/Urho3D,PredatorMF/Urho3D,urho3d/Urho3D,helingping/Urho3D,cosmy1/Urho3D,carnalis/Urho3D,codedash64/Urho3D,codemon66/Urho3D,299299/Urho3D,MonkeyFirst/Urho3D,tommy3/Urho3D,SirNate0/Urho3D,orefkov/Urho3D,carnalis/Urho3D,fire/Urho3D-1,weitjong/Urho3D,henu/Urho3D,iainmerrick/Urho3D,abdllhbyrktr/Urho3D,MeshGeometry/Urho3D,rokups/Urho3D,luveti/Urho3D,victorholt/Urho3D,c4augustus/Urho3D,eugeneko/Urho3D,eugeneko/Urho3D,fire/Urho3D-1,iainmerrick/Urho3D,xiliu98/Urho3D,tommy3/Urho3D,abdllhbyrktr/Urho3D,cosmy1/Urho3D,helingping/Urho3D,weitjong/Urho3D,c4augustus/Urho3D,iainmerrick/Urho3D,luveti/Urho3D
0032c0811908b4afe2cee5283c49b13f986db37f
src/org/robotlegs/v2/view/impl/StageWatcher.as
src/org/robotlegs/v2/view/impl/StageWatcher.as
//------------------------------------------------------------------------------ // Copyright (c) 2011 the original author or authors. All Rights Reserved. // // NOTICE: You are permitted you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. //------------------------------------------------------------------------------ package org.robotlegs.v2.view.impl { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; import org.robotlegs.v2.view.api.IContainerBinding; import org.robotlegs.v2.view.api.IViewHandler; import org.robotlegs.v2.view.api.IViewWatcher; public class StageWatcher implements IViewWatcher { /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private const _bindingsByContainer:Dictionary = new Dictionary(false); private const _confirmedHandlersByFQCN:Dictionary = new Dictionary(false); private const _removeHandlersByTarget:Dictionary = new Dictionary(true); /*============================================================================*/ /* Constructor */ /*============================================================================*/ public function StageWatcher() { // This page intentionally left blank } /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function addHandler(handler:IViewHandler, container:DisplayObjectContainer):void { if (handler.interests == 0) throw new ArgumentError('A view handler must be interested in something.'); const binding:IContainerBinding = _bindingsByContainer[container] ||= createBindingFor(container); binding.addHandler(handler); } public function removeHandler(handler:IViewHandler, container:DisplayObjectContainer):void { const binding:IContainerBinding = _bindingsByContainer[container]; if (!binding) return; binding.removeHandler(handler); // No point in a binding with no handlers! if (binding.handlers.length == 0) removeBinding(binding); } /*============================================================================*/ /* Private Functions */ /*============================================================================*/ private function addRootBinding(binding:IContainerBinding):void { // The magical, but extremely expensive, capture-phase ADDED_TO_STAGE listener binding.container.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, true); } private function createBindingFor(container:DisplayObjectContainer):IContainerBinding { const binding:IContainerBinding = new ContainerBinding(container); binding.parent = findParentBindingFor(container); // If the new binding doesn't have a parent it is a Root if (binding.parent == null) { addRootBinding(binding); } // Reparent any bindings which are contained within the new binding AND // A. Don't have a parent, OR // B. Have a parent that is not contained within the new binding for each (var childBinding:IContainerBinding in _bindingsByContainer) { if (container.contains(childBinding.container)) { if (!childBinding.parent) { removeRootBinding(childBinding); childBinding.parent = binding; } else if (!container.contains(childBinding.parent.container)) { childBinding.parent = binding; } } } return binding; } private function ensureRemoveHandler(target:DisplayObject, handler:IViewHandler):void { var removeHandlers:Vector.<IViewHandler> = _removeHandlersByTarget[target]; if (!removeHandlers) { removeHandlers = new Vector.<IViewHandler>; _removeHandlersByTarget[target] = removeHandlers; // Just a normal, target-phase REMOVED_FROM_STAGE listener per target target.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage); } removeHandlers.push(handler); } private function findParentBindingFor(target:DisplayObject):IContainerBinding { var parent:DisplayObjectContainer = target.parent; while (parent) { var binding:IContainerBinding = _bindingsByContainer[parent]; if (binding) { return binding; } parent = parent.parent; } return null; } private function handleFreshView( target:DisplayObject, targetFQCN:String, confirmedHandlers:Vector.<IViewHandler>):void { var handlerResponse:uint = 0; var combinedResponse:uint = 0; var handler:IViewHandler; var handlers:Vector.<IViewHandler>; var binding:IContainerBinding = findParentBindingFor(target); // Walk upwards from the nearest binding while (binding) { handlers = binding.handlers; var totalHandlers:uint = handlers.length; for (var i:uint = 0; i < totalHandlers; i++) { handler = handlers[i]; // Have our interests been blocked by a previous handler? // note: this leads to an interesting thought: // Should handlers really be able to have multiple interests (as currently implemented)? // How does blocking work then? if (!((combinedResponse & 0xAAAAAAAA) ^ (handler.interests << 1))) continue; handlerResponse = handler.handleViewAdded(target, null); combinedResponse |= handlerResponse; if (handlerResponse) { ensureRemoveHandler(target, handler); confirmedHandlers.push(handler); } } binding = binding.parent; } } private function handleKnownView( target:DisplayObject, targetFQCN:String, confirmedHandlers:Vector.<IViewHandler>):void { var handlerResponse:uint = 0; var combinedResponse:uint = 0; var handler:IViewHandler; const totalHandlers:uint = confirmedHandlers.length; for (var i:uint = 0; i < totalHandlers; i++) { handler = confirmedHandlers[i]; if (!((combinedResponse & 0xAAAAAAAA) ^ (handler.interests << 1))) { trace('warning: a confirmed handler was blocked - cache purging did not take place when it should have.'); continue; } handlerResponse = handler.handleViewAdded(target, null); combinedResponse |= handlerResponse; if (handlerResponse) { ensureRemoveHandler(target, handler); } else { trace('warning: a confirmed handler did not handle a view - cache purging did not take place when it should have.'); } } } private function onAddedToStage(event:Event):void { const target:DisplayObject = event.target as DisplayObject; const targetFQCN:String = getQualifiedClassName(target); // note: all vectors should actually be linked lists // to prevent mid-iteration errors var confirmedHandlers:Vector.<IViewHandler> = _confirmedHandlersByFQCN[targetFQCN]; if (confirmedHandlers) { handleKnownView(target, targetFQCN, confirmedHandlers); } else { confirmedHandlers = new Vector.<IViewHandler>; _confirmedHandlersByFQCN[targetFQCN] = confirmedHandlers; handleFreshView(target, targetFQCN, confirmedHandlers); } } private function onRemovedFromStage(event:Event):void { // This listener only fires for targets that got picked up by handlers const target:DisplayObject = event.target as DisplayObject; target.removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage); var handler:IViewHandler; const handlers:Vector.<IViewHandler> = _removeHandlersByTarget[target]; const totalHandlers:uint = handlers.length; for (var i:uint = 0; i < totalHandlers; i++) { handler = handlers[i]; handler.handleViewRemoved(target); } delete _removeHandlersByTarget[target]; } private function removeBinding(binding:IContainerBinding):void { delete _bindingsByContainer[binding.container]; if (!binding.parent) { // This binding didn't have a parent, so it was a Root removeRootBinding(binding); } // Re-parent the bindings for each (var childBinding:IContainerBinding in _bindingsByContainer) { if (childBinding.parent == binding) { childBinding.parent = binding.parent; if (!childBinding.parent) { // This binding used to have a parent, // but no longer does, so it is now a Root addRootBinding(childBinding); } } } } private function removeRootBinding(binding:IContainerBinding):void { binding.container.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage, true); } } }
//------------------------------------------------------------------------------ // Copyright (c) 2011 the original author or authors. All Rights Reserved. // // NOTICE: You are permitted you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. //------------------------------------------------------------------------------ package org.robotlegs.v2.view.impl { import flash.display.DisplayObject; import flash.display.DisplayObjectContainer; import flash.events.Event; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName; import org.as3commons.logging.api.ILogger; import org.as3commons.logging.api.getLogger; import org.robotlegs.v2.view.api.IContainerBinding; import org.robotlegs.v2.view.api.IViewHandler; import org.robotlegs.v2.view.api.IViewWatcher; public class StageWatcher implements IViewWatcher { /*============================================================================*/ /* Private Static Properties */ /*============================================================================*/ private static const logger:ILogger = getLogger(StageWatcher); /*============================================================================*/ /* Private Properties */ /*============================================================================*/ private const _bindingsByContainer:Dictionary = new Dictionary(false); private const _confirmedHandlersByFQCN:Dictionary = new Dictionary(false); private const _removeHandlersByTarget:Dictionary = new Dictionary(true); /*============================================================================*/ /* Constructor */ /*============================================================================*/ public function StageWatcher() { // This page intentionally left blank } /*============================================================================*/ /* Public Functions */ /*============================================================================*/ public function addHandler(handler:IViewHandler, container:DisplayObjectContainer):void { if (handler.interests == 0) throw new ArgumentError('A view handler must be interested in something.'); const binding:IContainerBinding = _bindingsByContainer[container] ||= createBindingFor(container); binding.addHandler(handler); } public function removeHandler(handler:IViewHandler, container:DisplayObjectContainer):void { const binding:IContainerBinding = _bindingsByContainer[container]; if (!binding) return; binding.removeHandler(handler); // No point in a binding with no handlers! if (binding.handlers.length == 0) removeBinding(binding); } /*============================================================================*/ /* Private Functions */ /*============================================================================*/ private function addRootBinding(binding:IContainerBinding):void { // The magical, but extremely expensive, capture-phase ADDED_TO_STAGE listener binding.container.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage, true); } private function createBindingFor(container:DisplayObjectContainer):IContainerBinding { const binding:IContainerBinding = new ContainerBinding(container); binding.parent = findParentBindingFor(container); // If the new binding doesn't have a parent it is a Root if (binding.parent == null) { addRootBinding(binding); } // Reparent any bindings which are contained within the new binding AND // A. Don't have a parent, OR // B. Have a parent that is not contained within the new binding for each (var childBinding:IContainerBinding in _bindingsByContainer) { if (container.contains(childBinding.container)) { if (!childBinding.parent) { removeRootBinding(childBinding); childBinding.parent = binding; } else if (!container.contains(childBinding.parent.container)) { childBinding.parent = binding; } } } return binding; } private function ensureRemoveHandler(target:DisplayObject, handler:IViewHandler):void { var removeHandlers:Vector.<IViewHandler> = _removeHandlersByTarget[target]; if (!removeHandlers) { removeHandlers = new Vector.<IViewHandler>; _removeHandlersByTarget[target] = removeHandlers; // Just a normal, target-phase REMOVED_FROM_STAGE listener per target target.addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage); } removeHandlers.push(handler); } private function findParentBindingFor(target:DisplayObject):IContainerBinding { var parent:DisplayObjectContainer = target.parent; while (parent) { var binding:IContainerBinding = _bindingsByContainer[parent]; if (binding) { return binding; } parent = parent.parent; } return null; } private function handleFreshView( target:DisplayObject, targetFQCN:String, confirmedHandlers:Vector.<IViewHandler>):void { var handlerResponse:uint = 0; var combinedResponse:uint = 0; var handler:IViewHandler; var handlers:Vector.<IViewHandler>; var binding:IContainerBinding = findParentBindingFor(target); // Walk upwards from the nearest binding while (binding) { handlers = binding.handlers; var totalHandlers:uint = handlers.length; for (var i:uint = 0; i < totalHandlers; i++) { handler = handlers[i]; // Have our interests been blocked by a previous handler? // note: this leads to an interesting thought: // Should handlers really be able to have multiple interests (as currently implemented)? // How does blocking work then? if (!((combinedResponse & 0xAAAAAAAA) ^ (handler.interests << 1))) continue; handlerResponse = handler.handleViewAdded(target, null); combinedResponse |= handlerResponse; if (handlerResponse) { ensureRemoveHandler(target, handler); confirmedHandlers.push(handler); } } binding = binding.parent; } } private function handleKnownView( target:DisplayObject, targetFQCN:String, confirmedHandlers:Vector.<IViewHandler>):void { var handlerResponse:uint = 0; var combinedResponse:uint = 0; var handler:IViewHandler; const totalHandlers:uint = confirmedHandlers.length; for (var i:uint = 0; i < totalHandlers; i++) { handler = confirmedHandlers[i]; if (!((combinedResponse & 0xAAAAAAAA) ^ (handler.interests << 1))) { logger.warn('a confirmed handler was blocked - cache purging did not take place when it should have'); continue; } handlerResponse = handler.handleViewAdded(target, null); combinedResponse |= handlerResponse; if (handlerResponse) { ensureRemoveHandler(target, handler); } else { logger.warn('a confirmed handler did not handle a view - cache purging did not take place when it should have'); } } } private function onAddedToStage(event:Event):void { const target:DisplayObject = event.target as DisplayObject; const targetFQCN:String = getQualifiedClassName(target); // note: all vectors should actually be linked lists // to prevent mid-iteration errors var confirmedHandlers:Vector.<IViewHandler> = _confirmedHandlersByFQCN[targetFQCN]; if (confirmedHandlers) { handleKnownView(target, targetFQCN, confirmedHandlers); } else { confirmedHandlers = new Vector.<IViewHandler>; _confirmedHandlersByFQCN[targetFQCN] = confirmedHandlers; handleFreshView(target, targetFQCN, confirmedHandlers); } } private function onRemovedFromStage(event:Event):void { // This listener only fires for targets that got picked up by handlers const target:DisplayObject = event.target as DisplayObject; target.removeEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage); var handler:IViewHandler; const handlers:Vector.<IViewHandler> = _removeHandlersByTarget[target]; const totalHandlers:uint = handlers.length; for (var i:uint = 0; i < totalHandlers; i++) { handler = handlers[i]; handler.handleViewRemoved(target); } delete _removeHandlersByTarget[target]; } private function removeBinding(binding:IContainerBinding):void { delete _bindingsByContainer[binding.container]; if (!binding.parent) { // This binding didn't have a parent, so it was a Root removeRootBinding(binding); } // Re-parent the bindings for each (var childBinding:IContainerBinding in _bindingsByContainer) { if (childBinding.parent == binding) { childBinding.parent = binding.parent; if (!childBinding.parent) { // This binding used to have a parent, // but no longer does, so it is now a Root addRootBinding(childBinding); } } } } private function removeRootBinding(binding:IContainerBinding):void { binding.container.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage, true); } } }
put the logger back
put the logger back
ActionScript
mit
robotlegs/robotlegs-framework,eric-stanley/robotlegs-framework,robotlegs/robotlegs-framework,eric-stanley/robotlegs-framework
e8654f2a465c16ce51450a6cc4706409b80860e9
src/aerys/minko/scene/node/AbstractSceneNode.as
src/aerys/minko/scene/node/AbstractSceneNode.as
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.data.TransformDataProvider; import aerys.minko.type.Signal; import aerys.minko.type.math.Matrix4x4; import flash.utils.getQualifiedClassName; /** * The base class to extend in order to create new scene node types. * * @author Jean-Marc Le Roux * */ public class AbstractSceneNode implements ISceneNode { use namespace minko_scene; private static var _id : uint = 0; private var _name : String = null; private var _root : ISceneNode = null; private var _parent : Group = null; private var _transformData : TransformDataProvider = new TransformDataProvider(); private var _transform : Matrix4x4 = new Matrix4x4(); private var _controllers : Vector.<AbstractController> = new <AbstractController>[]; private var _added : Signal = new Signal('AbstractSceneNode.added'); private var _removed : Signal = new Signal('AbstractSceneNode.removed'); private var _addedToScene : Signal = new Signal('AbstractSceneNode.addedToScene'); private var _removedFromScene : Signal = new Signal('AbstractSceneNode.removedFromScene'); private var _controllerAdded : Signal = new Signal('AbstractSceneNode.controllerAdded'); private var _controllerRemoved : Signal = new Signal('AbstractSceneNode.controllerRemoved'); public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } public function get parent() : Group { return _parent; } public function set parent(value : Group) : void { // remove child if (_parent) { var oldParent : Group = _parent; oldParent._children.splice( oldParent.getChildIndex(this), 1 ); parent._numChildren--; oldParent.descendantRemoved.execute(oldParent, this); _parent = null; _removed.execute(this, oldParent); } // set parent _parent = value; // add child if (_parent) { _parent._children[_parent.numChildren] = this; _parent._numChildren++; _parent.descendantAdded.execute(_parent, this); _added.execute(this, _parent); } } public function get root() : ISceneNode { return _root; } public function get transform() : Matrix4x4 { return _transform; } public function get localToWorld() : Matrix4x4 { return _transformData.localToWorld; } public function get worldToLocal() : Matrix4x4 { return _transformData.worldToLocal; } public function get added() : Signal { return _added; } public function get removed() : Signal { return _removed; } public function get addedToScene() : Signal { return _addedToScene; } public function get removedFromScene() : Signal { return _removedFromScene; } public function get numControllers() : uint { return _controllers.length; } public function get controllerAdded() : Signal { return _controllerAdded; } public function get controllerRemoved() : Signal { return _controllerRemoved; } protected function get transformData() : TransformDataProvider { return _transformData; } public function AbstractSceneNode() { initialize(); } private function initialize() : void { _name = getDefaultSceneName(this); _root = this; _added.add(addedHandler); _removed.add(removedHandler); _addedToScene.add(addedToSceneHandler); _removedFromScene.add(removedFromSceneHandler); _transform.changed.add(transformChangedHandler); } protected function addedHandler(child : ISceneNode, parent : Group) : void { _root = _parent ? _parent.root : this; if (_root is Scene) _addedToScene.execute(this, _root); if (child === this) { _parent.localToWorld.changed.add(transformChangedHandler); transformChangedHandler(_parent.transform, null); } } protected function removedHandler(child : ISceneNode, parent : Group) : void { // update root var oldRoot : ISceneNode = _root; _root = _parent ? _parent.root : this; if (oldRoot is Scene) _removedFromScene.execute(this, oldRoot); if (child === this) parent.localToWorld.changed.remove(transformChangedHandler); } protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } protected function transformChangedHandler(transform : Matrix4x4, propertyName : String) : void { if (_parent) { localToWorld.lock() .copyFrom(_transform) .append(_parent.localToWorld) .unlock(); } else localToWorld.copyFrom(_transform); worldToLocal.lock() .copyFrom(localToWorld) .invert() .unlock(); } public function addController(controller : AbstractController) : ISceneNode { _controllers.push(controller); controller.addTarget(this); _controllerAdded.execute(this, controller); return this; } public function removeController(controller : AbstractController) : ISceneNode { var numControllers : uint = _controllers.length - 1; _controllers[_controllers.indexOf(controller)] = _controllers[numControllers]; _controllers.length = numControllers; controller.removeTarget(this); _controllerRemoved.execute(this, controller); return this; } public function removeAllControllers() : ISceneNode { while (numControllers) removeController(getController(0)); return this; } public function getController(index : uint) : AbstractController { return _controllers[index]; } public function getControllersByType(type : Class, controllers : Vector.<AbstractController> = null) : Vector.<AbstractController> { controllers ||= new Vector.<AbstractController>(); var nbControllers : uint = numControllers; for (var i : int = 0; i < nbControllers; ++i) { var ctrl : AbstractController = getController(i); if (ctrl is type) controllers.push(ctrl); } return controllers; } public static function getDefaultSceneName(scene : ISceneNode) : String { var className : String = getQualifiedClassName(scene); return className.substr(className.lastIndexOf(':') + 1) + '_' + (++_id); } public function clone(cloneControllers : Boolean = false) : ISceneNode { throw new Error('The method AbstractSceneNod.clone() must be overriden.'); } protected function copyControllersFrom(source : ISceneNode, target : ISceneNode, cloneControllers : Boolean) : void { var numControllers : uint = target.numControllers; while (numControllers) target.removeController(target.getController(--numControllers)); numControllers = source.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controller : AbstractController = source.getController(controllerId); if (cloneControllers) controller = controller.clone(); target.addController(controller); } } } }
package aerys.minko.scene.node { import aerys.minko.ns.minko_scene; import aerys.minko.scene.controller.AbstractController; import aerys.minko.scene.data.TransformDataProvider; import aerys.minko.type.Signal; import aerys.minko.type.math.Matrix4x4; import flash.utils.getQualifiedClassName; /** * The base class to extend in order to create new scene node types. * * @author Jean-Marc Le Roux * */ public class AbstractSceneNode implements ISceneNode { use namespace minko_scene; private static var _id : uint = 0; private var _name : String = null; private var _root : ISceneNode = null; private var _parent : Group = null; private var _transformData : TransformDataProvider = new TransformDataProvider(); private var _transform : Matrix4x4 = new Matrix4x4(); private var _controllers : Vector.<AbstractController> = new <AbstractController>[]; private var _added : Signal = new Signal('AbstractSceneNode.added'); private var _removed : Signal = new Signal('AbstractSceneNode.removed'); private var _addedToScene : Signal = new Signal('AbstractSceneNode.addedToScene'); private var _removedFromScene : Signal = new Signal('AbstractSceneNode.removedFromScene'); private var _controllerAdded : Signal = new Signal('AbstractSceneNode.controllerAdded'); private var _controllerRemoved : Signal = new Signal('AbstractSceneNode.controllerRemoved'); public function get name() : String { return _name; } public function set name(value : String) : void { _name = value; } public function get parent() : Group { return _parent; } public function set parent(value : Group) : void { // remove child if (_parent) { var oldParent : Group = _parent; oldParent._children.splice( oldParent.getChildIndex(this), 1 ); parent._numChildren--; oldParent.descendantRemoved.execute(oldParent, this); _parent = null; _removed.execute(this, oldParent); } // set parent _parent = value; // add child if (_parent) { _parent._children[_parent.numChildren] = this; _parent._numChildren++; _parent.descendantAdded.execute(_parent, this); _added.execute(this, _parent); } } public function get root() : ISceneNode { return _root; } public function get transform() : Matrix4x4 { return _transform; } public function get localToWorld() : Matrix4x4 { return _transformData.localToWorld; } public function get worldToLocal() : Matrix4x4 { return _transformData.worldToLocal; } public function get added() : Signal { return _added; } public function get removed() : Signal { return _removed; } public function get addedToScene() : Signal { return _addedToScene; } public function get removedFromScene() : Signal { return _removedFromScene; } public function get numControllers() : uint { return _controllers.length; } public function get controllerAdded() : Signal { return _controllerAdded; } public function get controllerRemoved() : Signal { return _controllerRemoved; } protected function get transformData() : TransformDataProvider { return _transformData; } public function AbstractSceneNode() { initialize(); } private function initialize() : void { _name = getDefaultSceneName(this); _root = this; _added.add(addedHandler); _removed.add(removedHandler); _addedToScene.add(addedToSceneHandler); _removedFromScene.add(removedFromSceneHandler); _transform.changed.add(transformChangedHandler); } protected function addedHandler(child : ISceneNode, parent : Group) : void { _root = _parent ? _parent.root : this; if (_root is Scene) _addedToScene.execute(this, _root); if (child === this) { _parent.localToWorld.changed.add(transformChangedHandler); transformChangedHandler(_parent.transform, null); } } protected function removedHandler(child : ISceneNode, parent : Group) : void { // update root var oldRoot : ISceneNode = _root; _root = _parent ? _parent.root : this; if (oldRoot is Scene) _removedFromScene.execute(this, oldRoot); if (child === this) parent.localToWorld.changed.remove(transformChangedHandler); } protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void { // nothing } protected function transformChangedHandler(transform : Matrix4x4, propertyName : String) : void { if (_parent) { localToWorld.lock() .copyFrom(_transform) .append(_parent.localToWorld) .unlock(); } else localToWorld.copyFrom(_transform); worldToLocal.lock() .copyFrom(localToWorld) .invert() .unlock(); } public function addController(controller : AbstractController) : ISceneNode { _controllers.push(controller); controller.addTarget(this); _controllerAdded.execute(this, controller); return this; } public function removeController(controller : AbstractController) : ISceneNode { var numControllers : uint = _controllers.length - 1; _controllers[_controllers.indexOf(controller)] = _controllers[numControllers]; _controllers.length = numControllers; controller.removeTarget(this); _controllerRemoved.execute(this, controller); return this; } public function removeAllControllers() : ISceneNode { while (numControllers) removeController(getController(0)); return this; } public function getController(index : uint) : AbstractController { return _controllers[index]; } public function getControllersByType(type : Class, controllers : Vector.<AbstractController> = null) : Vector.<AbstractController> { controllers ||= new Vector.<AbstractController>(); var nbControllers : uint = numControllers; for (var i : int = 0; i < nbControllers; ++i) { var ctrl : AbstractController = getController(i); if (ctrl is type) controllers.push(ctrl); } return controllers; } public static function getDefaultSceneName(scene : ISceneNode) : String { var className : String = getQualifiedClassName(scene); return className.substr(className.lastIndexOf(':') + 1) + '_' + (++_id); } public function clone(cloneControllers : Boolean = false) : ISceneNode { throw new Error('The method AbstractSceneNode.clone() must be overriden.'); } protected function copyControllersFrom(source : ISceneNode, target : ISceneNode, cloneControllers : Boolean) : void { var numControllers : uint = target.numControllers; while (numControllers) target.removeController(target.getController(--numControllers)); numControllers = source.numControllers; for (var controllerId : uint = 0; controllerId < numControllers; ++controllerId) { var controller : AbstractController = source.getController(controllerId); if (cloneControllers) controller = controller.clone(); target.addController(controller); } } } }
Fix typo.
Fix typo.
ActionScript
mit
aerys/minko-as3
cc479db56f58adb471bef3e238aaa162e260db6c
src/org/mangui/hls/controller/BufferThresholdController.as
src/org/mangui/hls/controller/BufferThresholdController.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.controller { import org.mangui.hls.constant.HLSLoaderTypes; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.event.HLSLoadMetrics; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that manages buffer threshold values (minBufferLength/lowBufferLength) */ public class BufferThresholdController { /** Reference to the HLS controller. **/ private var _hls : HLS; // max nb of samples used for bw checking. the bigger it is, the more conservative it is. private static const MAX_SAMPLES : int = 30; private var _bw : Vector.<Number>; private var _nbSamples : uint; private var _targetduration : Number; private var _minBufferLength : Number; /** Create the loader. **/ public function BufferThresholdController(hls : HLS) : void { _hls = hls; _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler); _hls.addEventListener(HLSEvent.TAGS_LOADED, _fragmentLoadedHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler); }; public function dispose() : void { _hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler); _hls.removeEventListener(HLSEvent.TAGS_LOADED, _fragmentLoadedHandler); _hls.removeEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler); } public function get minBufferLength() : Number { if (HLSSettings.minBufferLength == -1) { return _minBufferLength; } else { return HLSSettings.minBufferLength; } } public function get lowBufferLength() : Number { if (HLSSettings.minBufferLength == -1) { // in automode, low buffer threshold should be less than min auto buffer return Math.min(minBufferLength / 2, HLSSettings.lowBufferLength); } else { return HLSSettings.lowBufferLength; } } private function _manifestLoadedHandler(event : HLSEvent) : void { _nbSamples = 0; _targetduration = event.levels[_hls.startLevel].targetduration; _bw = new Vector.<Number>(MAX_SAMPLES,true); _minBufferLength = _targetduration; }; private function _fragmentLoadedHandler(event : HLSEvent) : void { var metrics : HLSLoadMetrics = event.loadMetrics; // only monitor main fragment metrics for buffer threshold computing if(metrics.type == HLSLoaderTypes.FRAGMENT_MAIN) { var cur_bw : int = metrics.bandwidth; _bw[_nbSamples % MAX_SAMPLES] = cur_bw; _nbSamples++; // compute min bw on MAX_SAMPLES var minBw : Number = Number.POSITIVE_INFINITY; var samples_max : int = Math.min(_nbSamples, MAX_SAMPLES); for (var i : int = 0; i < samples_max; i++) { minBw = Math.min(minBw, _bw[i]); } // give more weight to current bandwidth var bw_ratio : Number = 2 * cur_bw / (minBw + cur_bw); /* predict time to dl next segment using a conservative approach. * * heuristic is as follow : * * time to dl next segment = time to dl current segment * (playlist target duration / current segment duration) * bw_ratio * \---------------------------------------------------------------------------------/ * this part is a simple rule by 3, assuming we keep same dl bandwidth * bw ratio is the conservative factor, assuming that next segment will be downloaded with min bandwidth */ _minBufferLength = metrics.processing_duration * (_targetduration / metrics.duration) * bw_ratio; // avoid min > max if (HLSSettings.maxBufferLength) { _minBufferLength = Math.min(HLSSettings.maxBufferLength, _minBufferLength); } // avoid _minBufferLength > minBufferLengthCapping if (HLSSettings.minBufferLengthCapping > 0) { _minBufferLength = Math.min(HLSSettings.minBufferLengthCapping, _minBufferLength); } CONFIG::LOGGING { Log.debug2("AutoBufferController:minBufferLength:" + _minBufferLength); } }; } } }
/* 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.controller { import org.mangui.hls.constant.HLSLoaderTypes; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.event.HLSLoadMetrics; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Class that manages buffer threshold values (minBufferLength/lowBufferLength) */ public class BufferThresholdController { /** Reference to the HLS controller. **/ private var _hls : HLS; private var _targetduration : Number; private var _minBufferLength : Number; /** Create the loader. **/ public function BufferThresholdController(hls : HLS) : void { _hls = hls; _hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler); _hls.addEventListener(HLSEvent.TAGS_LOADED, _fragmentLoadedHandler); _hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler); }; public function dispose() : void { _hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler); _hls.removeEventListener(HLSEvent.TAGS_LOADED, _fragmentLoadedHandler); _hls.removeEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler); } public function get minBufferLength() : Number { if (HLSSettings.minBufferLength == -1) { return _minBufferLength; } else { return HLSSettings.minBufferLength; } } public function get lowBufferLength() : Number { if (HLSSettings.minBufferLength == -1) { // in automode, low buffer threshold should be less than min auto buffer return Math.min(minBufferLength / 2, HLSSettings.lowBufferLength); } else { return HLSSettings.lowBufferLength; } } private function _manifestLoadedHandler(event : HLSEvent) : void { _targetduration = event.levels[_hls.startLevel].targetduration; _minBufferLength = _targetduration; }; private function _fragmentLoadedHandler(event : HLSEvent) : void { var metrics : HLSLoadMetrics = event.loadMetrics; // only monitor main fragment metrics for buffer threshold computing if(metrics.type == HLSLoaderTypes.FRAGMENT_MAIN) { /* set min buf len to be the time to process a complete segment, using current processing rate */ _minBufferLength = metrics.processing_duration * (_targetduration / metrics.duration); // avoid min > max if (HLSSettings.maxBufferLength) { _minBufferLength = Math.min(HLSSettings.maxBufferLength, _minBufferLength); } // avoid _minBufferLength > minBufferLengthCapping if (HLSSettings.minBufferLengthCapping > 0) { _minBufferLength = Math.min(HLSSettings.minBufferLengthCapping, _minBufferLength); } CONFIG::LOGGING { Log.debug2("AutoBufferController:minBufferLength:" + _minBufferLength); } }; } } }
remove conservative factor as the algorithm is already really conservative... minBufferLength is the time to process a complete segment (of duration EXT-X-TARGETDURATION), using current processing rate
BufferThresholdController: remove conservative factor as the algorithm is already really conservative... minBufferLength is the time to process a complete segment (of duration EXT-X-TARGETDURATION), using current processing rate
ActionScript
mpl-2.0
fixedmachine/flashls,hola/flashls,mangui/flashls,vidible/vdb-flashls,tedconf/flashls,NicolasSiver/flashls,jlacivita/flashls,mangui/flashls,neilrackett/flashls,jlacivita/flashls,codex-corp/flashls,hola/flashls,NicolasSiver/flashls,clappr/flashls,tedconf/flashls,clappr/flashls,fixedmachine/flashls,vidible/vdb-flashls,neilrackett/flashls,codex-corp/flashls
fc6fa636d6e037ae910b1f8e4762a52861496ea2
src/aerys/minko/type/Signal.as
src/aerys/minko/type/Signal.as
package aerys.minko.type { public final class Signal { private var _name : String; private var _enabled : Boolean; private var _disableWhenNoCallbacks : Boolean; private var _callbacks : Vector.<Function>; private var _numCallbacks : uint; private var _executed : Boolean; private var _numAdded : uint; private var _toAdd : Vector.<Function>; private var _numRemoved : uint; private var _toRemove : Vector.<Function>; public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } public function get numCallbacks() : uint { return _numCallbacks; } public function Signal(name : String, enabled : Boolean = true, disableWhenNoCallbacks : Boolean = false) { _name = name; _enabled = enabled; _disableWhenNoCallbacks = disableWhenNoCallbacks; _callbacks = new <Function>[]; } public function add(callback : Function) : void { if (_callbacks.indexOf(callback) >= 0) { var removeIndex : int = _toRemove ? _toRemove.indexOf(callback) : -1; // if that callback is in the temp. remove list, we simply remove it from this list // instead of removing/adding it all over again if (removeIndex >= 0) { --_numRemoved; _toRemove[removeIndex] = _toRemove[_numRemoved]; _toRemove.length = _numRemoved; return; } else throw new Error('The same callback cannot be added twice.'); } if (_executed) { if (_toAdd) _toAdd.push(callback); else _toAdd = new <Function>[callback]; ++_numAdded; return ; } _callbacks[_numCallbacks] = callback; ++_numCallbacks; if (_numCallbacks == 1 && _disableWhenNoCallbacks) _enabled = true; } public function remove(callback : Function) : void { var index : int = _callbacks.indexOf(callback); if (index < 0) { var addIndex : int = _toAdd ? _toAdd.indexOf(callback) : -1; // if that callback is in the temp. add list, we simply remove it from this list // instead of adding/removing it all over again if (addIndex >= 0) { --_numAdded; _toAdd[addIndex] = _toAdd[_numAdded]; _toAdd.length = _numAdded; } else throw new Error('This callback does not exist.'); } if (_executed) { if (_toRemove) _toRemove.push(callback); else _toRemove = new <Function>[callback]; ++_numRemoved; return ; } --_numCallbacks; _callbacks[index] = _callbacks[_numCallbacks]; _callbacks.length = _numCallbacks; if (!_numCallbacks && _disableWhenNoCallbacks) _enabled = false; } public function hasCallback(callback : Function) : Boolean { return _callbacks.indexOf(callback) >= 0; } public function execute(...params) : void { if (_numCallbacks && _enabled) { _executed = true; for (var i : uint = 0; i < _numCallbacks; ++i) _callbacks[i].apply(null, params); _executed = false; for (i = 0; i < _numAdded; ++i) add(_toAdd[i]); _numAdded = 0; _toAdd = null; for (i = 0; i < _numRemoved; ++i) remove(_toRemove[i]); _numRemoved = 0; _toRemove = null; } } } }
package aerys.minko.type { public final class Signal { private var _name : String; private var _enabled : Boolean; private var _disableWhenNoCallbacks : Boolean; private var _callbacks : Vector.<Function>; private var _numCallbacks : uint; private var _executed : Boolean; private var _numAdded : uint; private var _toAdd : Vector.<Function>; private var _numRemoved : uint; private var _toRemove : Vector.<Function>; public function get enabled() : Boolean { return _enabled; } public function set enabled(value : Boolean) : void { _enabled = value; } public function get numCallbacks() : uint { return _numCallbacks; } public function Signal(name : String, enabled : Boolean = true, disableWhenNoCallbacks : Boolean = false) { _name = name; _enabled = enabled; _disableWhenNoCallbacks = disableWhenNoCallbacks; _callbacks = new <Function>[]; } public function add(callback : Function) : void { if (_callbacks.indexOf(callback) >= 0) { var removeIndex : int = _toRemove ? _toRemove.indexOf(callback) : -1; // if that callback is in the temp. remove list, we simply remove it from this list // instead of removing/adding it all over again if (removeIndex >= 0) { --_numRemoved; _toRemove[removeIndex] = _toRemove[_numRemoved]; _toRemove.length = _numRemoved; return; } else throw new Error('The same callback cannot be added twice.'); } if (_executed) { if (_toAdd) _toAdd.push(callback); else _toAdd = new <Function>[callback]; ++_numAdded; return ; } _callbacks[_numCallbacks] = callback; ++_numCallbacks; if (_numCallbacks == 1 && _disableWhenNoCallbacks) _enabled = true; } public function remove(callback : Function) : void { var index : int = _callbacks.indexOf(callback); if (index < 0) { var addIndex : int = _toAdd ? _toAdd.indexOf(callback) : -1; // if that callback is in the temp. add list, we simply remove it from this list // instead of adding/removing it all over again if (addIndex >= 0) { --_numAdded; _toAdd[addIndex] = _toAdd[_numAdded]; _toAdd.length = _numAdded; } else throw new Error('This callback does not exist.'); } if (_executed) { if (_toRemove) _toRemove.push(callback); else _toRemove = new <Function>[callback]; ++_numRemoved; return ; } --_numCallbacks; _callbacks[index] = _callbacks[_numCallbacks]; _callbacks.length = _numCallbacks; if (!_numCallbacks && _disableWhenNoCallbacks) _enabled = false; } public function hasCallback(callback : Function) : Boolean { return _callbacks.indexOf(callback) >= 0; } public function execute(...p) : void { if (_numCallbacks && _enabled) { _executed = true; for (var i : uint = 0; i < _numCallbacks; ++i) { switch (p.length) { case 0: _callbacks[i](); break ; case 1: _callbacks[i](p[0]); break ; case 2: _callbacks[i](p[0], p[1]); break ; case 3: _callbacks[i](p[0], p[1], p[2]); break ; case 4: _callbacks[i](p[0], p[1], p[2], p[3]); break ; case 5: _callbacks[i](p[0], p[1], p[2], p[3], p[4]); break ; case 6: _callbacks[i](p[0], p[1], p[2], p[3], p[4], p[5]); break ; case 7: _callbacks[i](p[0], p[1], p[2], p[3], p[4], p[5], p[6]); break ; case 8: _callbacks[i](p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]); break ; case 9: _callbacks[i](p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]); break ; case 10: _callbacks[i](p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8], p[9]); break ; } // _callbacks[i].apply(null, params); } _executed = false; for (i = 0; i < _numAdded; ++i) add(_toAdd[i]); _numAdded = 0; _toAdd = null; for (i = 0; i < _numRemoved; ++i) remove(_toRemove[i]); _numRemoved = 0; _toRemove = null; } } } }
change Signal.execute to avoid calling Function.apply but drop support for callbacks with more than 10 arguments
change Signal.execute to avoid calling Function.apply but drop support for callbacks with more than 10 arguments
ActionScript
mit
aerys/minko-as3
a83bdd29477ba3f53ef744933a7578cd67b9e068
src/org/mangui/hls/loader/LevelLoader.as
src/org/mangui/hls/loader/LevelLoader.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.loader { import org.mangui.hls.playlist.DataUri; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.playlist.Manifest; import org.mangui.hls.constant.HLSPlayStates; import org.mangui.hls.constant.HLSTypes; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.event.HLSError; import org.mangui.hls.model.Level; import org.mangui.hls.model.Fragment; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; import flash.events.*; import flash.net.*; import flash.utils.*; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Loader for hls manifests. **/ public class LevelLoader { /** Reference to the hls framework controller. **/ private var _hls : HLS; /** levels vector. **/ private var _levels : Vector.<Level>; /** Object that fetches the manifest. **/ private var _urlloader : URLLoader; /** Link to the M3U8 file. **/ private var _url : String; /** are all playlists filled ? **/ private var _canStart : Boolean; /** Timeout ID for reloading live playlists. **/ private var _timeoutID : uint; /** Streaming type (live, ondemand). **/ private var _type : String; /** last reload manifest time **/ private var _reload_playlists_timer : uint; /** current level **/ private var _current_level : int; /** reference to manifest being loaded **/ private var _manifest_loading : Manifest; /** is this loader closed **/ private var _closed : Boolean = false; /* playlist retry timeout */ private var _retry_timeout : Number; private var _retry_count : int; /* alt audio tracks */ private var _alt_audio_tracks : Vector.<AltAudioTrack>; /** Setup the loader. **/ public function LevelLoader(hls : HLS) { _hls = hls; _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); _levels = new Vector.<Level>(); _urlloader = new URLLoader(); _urlloader.addEventListener(Event.COMPLETE, _loaderHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler); }; public function dispose() : void { _close(); _urlloader.removeEventListener(Event.COMPLETE, _loaderHandler); _urlloader.removeEventListener(IOErrorEvent.IO_ERROR, _errorHandler); _urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler); _hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); } /** Loading failed; return errors. **/ private function _errorHandler(event : ErrorEvent) : void { var txt : String; var code : int; if (event is SecurityErrorEvent) { code = HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR; txt = "Cannot load M3U8: crossdomain access denied:" + event.text; } else if (event is IOErrorEvent && _levels.length && (HLSSettings.manifestLoadMaxRetry == -1 || _retry_count < HLSSettings.manifestLoadMaxRetry)) { CONFIG::LOGGING { Log.warn("I/O Error while trying to load Playlist, retry in " + _retry_timeout + " ms"); } _timeoutID = setTimeout(_loadActiveLevelPlaylist, _retry_timeout); /* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */ _retry_timeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retry_timeout); _retry_count++; return; } else { code = HLSError.MANIFEST_LOADING_IO_ERROR; txt = "Cannot load M3U8: " + event.text; } var hlsError : HLSError = new HLSError(code, _url, txt); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); }; /** Return the current manifest. **/ public function get levels() : Vector.<Level> { return _levels; }; /** Return the stream type. **/ public function get type() : String { return _type; }; public function get altAudioTracks() : Vector.<AltAudioTrack> { return _alt_audio_tracks; } /** Load the manifest file. **/ public function load(url : String) : void { _close(); _closed = false; _url = url; _levels = new Vector.<Level>(); _canStart = false; _reload_playlists_timer = getTimer(); _retry_timeout = 1000; _retry_count = 0; _alt_audio_tracks = null; _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, url)); if (DataUri.isDataUri(url)) { CONFIG::LOGGING { Log.debug("Identified main manifest <" + url + "> as a data URI."); } var data : String = new DataUri(url).extractData(); _parseManifest(data || ""); } else { _urlloader.load(new URLRequest(url)); } }; /** Manifest loaded; check and parse it **/ private function _loaderHandler(event : Event) : void { // successful loading, reset retry counter _retry_timeout = 1000; _retry_count = 0; var loader : URLLoader = URLLoader(event.target); _parseManifest(String(loader.data)); }; /** parse a playlist **/ private function _parseLevelPlaylist(string : String, url : String, level : int) : void { if (string != null && string.length != 0) { CONFIG::LOGGING { Log.debug("level " + level + " playlist:\n" + string); } var frags : Vector.<Fragment> = Manifest.getFragments(string, url, level); // set fragment and update sequence number range _levels[level].updateFragments(frags); _levels[level].targetduration = Manifest.getTargetDuration(string); _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYLIST_DURATION_UPDATED, _levels[level].duration)); } // Check whether the stream is live or not finished yet if (Manifest.hasEndlist(string)) { _type = HLSTypes.VOD; _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_ENDLIST, level)); } else { _type = HLSTypes.LIVE; /* in order to determine playlist reload timer, check playback position against playlist duration. if we are near the edge of a live playlist, reload playlist quickly to discover quicker new fragments and avoid buffer starvation. */ var reload_interval : Number = 1000*Math.min((_levels[level].duration - _hls.position)/2,_levels[level].averageduration); // avoid spamming the server if we are at the edge ... wait 500ms between 2 reload at least var timeout : Number = Math.max(500, _reload_playlists_timer + reload_interval - getTimer()); CONFIG::LOGGING { Log.debug("Level " + level + " Live Playlist parsing finished: reload in " + timeout.toFixed(0) + " ms"); } _timeoutID = setTimeout(_loadActiveLevelPlaylist, timeout); } if (!_canStart) { _canStart = (_levels[level].fragments.length > 0); if (_canStart) { CONFIG::LOGGING { Log.debug("first level filled with at least 1 fragment, notify event"); } _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADED, _levels)); } } _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADED, level)); _manifest_loading = null; }; /** Parse First Level Playlist **/ private function _parseManifest(string : String) : void { // Check for M3U8 playlist or manifest. if (string.indexOf(Manifest.HEADER) == 0) { // 1 level playlist, create unique level and parse playlist if (string.indexOf(Manifest.FRAGMENT) > 0) { var level : Level = new Level(); level.url = _url; _levels.push(level); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels)); _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, 0)); CONFIG::LOGGING { Log.debug("1 Level Playlist, load it"); } _current_level = 0; _parseLevelPlaylist(string, _url, 0); } else if (string.indexOf(Manifest.LEVEL) > 0) { CONFIG::LOGGING { Log.debug("adaptive playlist:\n" + string); } // adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(_hls, string, _url); // retrieve start level from helper function _current_level = _hls.startlevel; _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels)); _loadActiveLevelPlaylist(); if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) { CONFIG::LOGGING { Log.debug("alternate audio level found"); } // parse alternate audio tracks _alt_audio_tracks = Manifest.extractAltAudioTracks(string, _url); CONFIG::LOGGING { if (_alt_audio_tracks.length > 0) { Log.debug(_alt_audio_tracks.length + " alternate audio tracks found"); } } } } } else { var hlsError : HLSError = new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, "Manifest is not a valid M3U8 file"); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); } }; /** load/reload active M3U8 playlist **/ private function _loadActiveLevelPlaylist() : void { if (_closed) { return; } _reload_playlists_timer = getTimer(); // load active M3U8 playlist only _manifest_loading = new Manifest(); _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, _current_level)); _manifest_loading.loadPlaylist(_levels[_current_level].url, _parseLevelPlaylist, _errorHandler, _current_level, _type, HLSSettings.flushLiveURLCache); }; /** When level switch occurs, assess the need of (re)loading new level playlist **/ private function _levelSwitchHandler(event : HLSEvent) : void { if (_current_level != event.level) { _current_level = event.level; CONFIG::LOGGING { Log.debug("switch to level " + _current_level); } if (_type == HLSTypes.LIVE || _levels[_current_level].fragments.length == 0) { _closed = false; CONFIG::LOGGING { Log.debug("(re)load Playlist"); } clearTimeout(_timeoutID); _timeoutID = setTimeout(_loadActiveLevelPlaylist, 0); } } }; private function _close() : void { CONFIG::LOGGING { Log.debug("cancel any manifest load in progress"); } _closed = true; clearTimeout(_timeoutID); try { _urlloader.close(); if (_manifest_loading) { _manifest_loading.close(); } } catch(e : Error) { } } /** When the framework idles out, stop reloading manifest **/ private function _stateHandler(event : HLSEvent) : void { if (event.state == HLSPlayStates.IDLE) { _close(); } }; } }
/* 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.loader { import org.mangui.hls.playlist.DataUri; import org.mangui.hls.playlist.AltAudioTrack; import org.mangui.hls.playlist.Manifest; import org.mangui.hls.constant.HLSPlayStates; import org.mangui.hls.constant.HLSTypes; import org.mangui.hls.event.HLSEvent; import org.mangui.hls.event.HLSError; import org.mangui.hls.model.Level; import org.mangui.hls.model.Fragment; import org.mangui.hls.HLS; import org.mangui.hls.HLSSettings; import flash.events.*; import flash.net.*; import flash.utils.*; CONFIG::LOGGING { import org.mangui.hls.utils.Log; } /** Loader for hls manifests. **/ public class LevelLoader { /** Reference to the hls framework controller. **/ private var _hls : HLS; /** levels vector. **/ private var _levels : Vector.<Level>; /** Object that fetches the manifest. **/ private var _urlloader : URLLoader; /** Link to the M3U8 file. **/ private var _url : String; /** are all playlists filled ? **/ private var _canStart : Boolean; /** Timeout ID for reloading live playlists. **/ private var _timeoutID : uint; /** Streaming type (live, ondemand). **/ private var _type : String; /** last reload manifest time **/ private var _reload_playlists_timer : uint; /** current level **/ private var _current_level : int; /** reference to manifest being loaded **/ private var _manifest_loading : Manifest; /** is this loader closed **/ private var _closed : Boolean = false; /* playlist retry timeout */ private var _retry_timeout : Number; private var _retry_count : int; /* alt audio tracks */ private var _alt_audio_tracks : Vector.<AltAudioTrack>; /** Setup the loader. **/ public function LevelLoader(hls : HLS) { _hls = hls; _hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); _levels = new Vector.<Level>(); _urlloader = new URLLoader(); _urlloader.addEventListener(Event.COMPLETE, _loaderHandler); _urlloader.addEventListener(IOErrorEvent.IO_ERROR, _errorHandler); _urlloader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler); }; public function dispose() : void { _close(); _urlloader.removeEventListener(Event.COMPLETE, _loaderHandler); _urlloader.removeEventListener(IOErrorEvent.IO_ERROR, _errorHandler); _urlloader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, _errorHandler); _hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler); _hls.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler); } /** Loading failed; return errors. **/ private function _errorHandler(event : ErrorEvent) : void { var txt : String; var code : int; if (event is SecurityErrorEvent) { code = HLSError.MANIFEST_LOADING_CROSSDOMAIN_ERROR; txt = "Cannot load M3U8: crossdomain access denied:" + event.text; } else if (event is IOErrorEvent && _levels.length && (HLSSettings.manifestLoadMaxRetry == -1 || _retry_count < HLSSettings.manifestLoadMaxRetry)) { CONFIG::LOGGING { Log.warn("I/O Error while trying to load Playlist, retry in " + _retry_timeout + " ms"); } _timeoutID = setTimeout(_loadActiveLevelPlaylist, _retry_timeout); /* exponential increase of retry timeout, capped to manifestLoadMaxRetryTimeout */ _retry_timeout = Math.min(HLSSettings.manifestLoadMaxRetryTimeout, 2 * _retry_timeout); _retry_count++; return; } else { code = HLSError.MANIFEST_LOADING_IO_ERROR; txt = "Cannot load M3U8: " + event.text; } var hlsError : HLSError = new HLSError(code, _url, txt); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); }; /** Return the current manifest. **/ public function get levels() : Vector.<Level> { return _levels; }; /** Return the stream type. **/ public function get type() : String { return _type; }; public function get altAudioTracks() : Vector.<AltAudioTrack> { return _alt_audio_tracks; } /** Load the manifest file. **/ public function load(url : String) : void { _close(); _closed = false; _url = url; _levels = new Vector.<Level>(); _canStart = false; _reload_playlists_timer = getTimer(); _retry_timeout = 1000; _retry_count = 0; _alt_audio_tracks = null; _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADING, url)); if (DataUri.isDataUri(url)) { CONFIG::LOGGING { Log.debug("Identified main manifest <" + url + "> as a data URI."); } var data : String = new DataUri(url).extractData(); _parseManifest(data || ""); } else { _urlloader.load(new URLRequest(url)); } }; /** Manifest loaded; check and parse it **/ private function _loaderHandler(event : Event) : void { // successful loading, reset retry counter _retry_timeout = 1000; _retry_count = 0; var loader : URLLoader = URLLoader(event.target); _parseManifest(String(loader.data)); }; /** parse a playlist **/ private function _parseLevelPlaylist(string : String, url : String, level : int) : void { if (string != null && string.length != 0) { CONFIG::LOGGING { Log.debug("level " + level + " playlist:\n" + string); } var frags : Vector.<Fragment> = Manifest.getFragments(string, url, level); // set fragment and update sequence number range _levels[level].updateFragments(frags); _levels[level].targetduration = Manifest.getTargetDuration(string); _hls.dispatchEvent(new HLSEvent(HLSEvent.PLAYLIST_DURATION_UPDATED, _levels[level].duration)); } // Check whether the stream is live or not finished yet if (Manifest.hasEndlist(string)) { _type = HLSTypes.VOD; _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_ENDLIST, level)); } else { _type = HLSTypes.LIVE; /* in order to determine playlist reload timer, check playback position against playlist duration. if we are near the edge of a live playlist, reload playlist quickly to discover quicker new fragments and avoid buffer starvation. */ var reload_interval : Number = 1000*Math.min((_levels[level].duration - _hls.position)/2,_levels[level].averageduration); // avoid spamming the server if we are at the edge ... wait 500ms between 2 reload at least var timeout : Number = Math.max(500, _reload_playlists_timer + reload_interval - getTimer()); CONFIG::LOGGING { Log.debug("Level " + level + " Live Playlist parsing finished: reload in " + timeout.toFixed(0) + " ms"); } _timeoutID = setTimeout(_loadActiveLevelPlaylist, timeout); } if (!_canStart) { _canStart = (_levels[level].fragments.length > 0); if (_canStart) { CONFIG::LOGGING { Log.debug("first level filled with at least 1 fragment, notify event"); } _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_LOADED, _levels)); } } _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADED, level)); _manifest_loading = null; }; /** Parse First Level Playlist **/ private function _parseManifest(string : String) : void { // Check for M3U8 playlist or manifest. if (string.indexOf(Manifest.HEADER) == 0) { // 1 level playlist, create unique level and parse playlist if (string.indexOf(Manifest.FRAGMENT) > 0) { var level : Level = new Level(); level.url = _url; _levels.push(level); _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels)); _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, 0)); CONFIG::LOGGING { Log.debug("1 Level Playlist, load it"); } _current_level = 0; _parseLevelPlaylist(string, _url, 0); } else if (string.indexOf(Manifest.LEVEL) > 0) { CONFIG::LOGGING { Log.debug("adaptive playlist:\n" + string); } // adaptative playlist, extract levels from playlist, get them and parse them _levels = Manifest.extractLevels(_hls, string, _url); // retrieve start level from helper function _current_level = _hls.startlevel; _hls.dispatchEvent(new HLSEvent(HLSEvent.MANIFEST_PARSED, _levels)); _loadActiveLevelPlaylist(); if (string.indexOf(Manifest.ALTERNATE_AUDIO) > 0) { CONFIG::LOGGING { Log.debug("alternate audio level found"); } // parse alternate audio tracks _alt_audio_tracks = Manifest.extractAltAudioTracks(string, _url); CONFIG::LOGGING { if (_alt_audio_tracks.length > 0) { Log.debug(_alt_audio_tracks.length + " alternate audio tracks found"); } } } } } else { var hlsError : HLSError = new HLSError(HLSError.MANIFEST_PARSING_ERROR, _url, "Manifest is not a valid M3U8 file"); _hls.dispatchEvent(new HLSEvent(HLSEvent.ERROR, hlsError)); } }; /** load/reload active M3U8 playlist **/ private function _loadActiveLevelPlaylist() : void { if (_closed) { return; } _reload_playlists_timer = getTimer(); // load active M3U8 playlist only _manifest_loading = new Manifest(); _hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_LOADING, _current_level)); _manifest_loading.loadPlaylist(_levels[_current_level].url, _parseLevelPlaylist, _errorHandler, _current_level, _type, HLSSettings.flushLiveURLCache); }; /** When level switch occurs, assess the need of (re)loading new level playlist **/ private function _levelSwitchHandler(event : HLSEvent) : void { if (_current_level != event.level) { _current_level = event.level; CONFIG::LOGGING { Log.debug("switch to level " + _current_level); } if (_type == HLSTypes.LIVE || _levels[_current_level].fragments.length == 0) { _closed = false; CONFIG::LOGGING { Log.debug("(re)load Playlist"); } clearTimeout(_timeoutID); _timeoutID = setTimeout(_loadActiveLevelPlaylist, 0); } } }; private function _close() : void { CONFIG::LOGGING { Log.debug("cancel any manifest load in progress"); } _closed = true; clearTimeout(_timeoutID); try { _urlloader.close(); if (_manifest_loading) { _manifest_loading.close(); } } catch(e : Error) { } } /** When the framework idles out, stop reloading manifest **/ private function _stateHandler(event : HLSEvent) : void { if (event.state == HLSPlayStates.IDLE) { _close(); } }; } }
trim white space
trim white space
ActionScript
mpl-2.0
aevange/flashls,Corey600/flashls,Boxie5/flashls,thdtjsdn/flashls,dighan/flashls,NicolasSiver/flashls,jlacivita/flashls,fixedmachine/flashls,loungelogic/flashls,mangui/flashls,suuhas/flashls,dighan/flashls,suuhas/flashls,Boxie5/flashls,suuhas/flashls,suuhas/flashls,NicolasSiver/flashls,Corey600/flashls,Peer5/flashls,tedconf/flashls,thdtjsdn/flashls,clappr/flashls,JulianPena/flashls,mangui/flashls,vidible/vdb-flashls,JulianPena/flashls,Peer5/flashls,neilrackett/flashls,loungelogic/flashls,aevange/flashls,Peer5/flashls,hola/flashls,fixedmachine/flashls,vidible/vdb-flashls,jlacivita/flashls,aevange/flashls,codex-corp/flashls,aevange/flashls,codex-corp/flashls,clappr/flashls,hola/flashls,Peer5/flashls,neilrackett/flashls,tedconf/flashls
785e98c042f9ea1289bd50b8171b72ab1e1ecf3e
WEB-INF/lps/lfc/kernel/swf9/LzInputTextSprite.as
WEB-INF/lps/lfc/kernel/swf9/LzInputTextSprite.as
/** * LzInputTextSprite.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 */ /** * @shortdesc Used for input text. * */ public class LzInputTextSprite extends LzTextSprite { #passthrough (toplevel:true) { import flash.display.InteractiveObject; import flash.events.Event; import flash.events.FocusEvent; import flash.text.TextField; import flash.text.TextFieldType; }# #passthrough { function LzInputTextSprite (newowner:LzView = null, args:Object = null) { super(newowner); } var enabled :Boolean = true; var focusable :Boolean = true; var hasFocus :Boolean = false; override public function __initTextProperties (args:Object) :void { super.__initTextProperties(args); // We do not support html in input fields. this.html = false; if (this.enabled) { textfield.type = TextFieldType.INPUT; } else { textfield.type = TextFieldType.DYNAMIC; } /* TODO [hqm 2008-01] these handlers need to be implemented via Flash native event listenters: focusIn , focusOut change -- dispatched after text input is modified textInput -- dispatched before the content is modified Do we need to use this for intercepting when we have a pattern restriction on input? */ textfield.addEventListener(Event.CHANGE , __onChanged); //textfield.addEventListener(TextEvent.TEXT_INPUT, __onTextInput); textfield.addEventListener(FocusEvent.FOCUS_IN , __gotFocus); textfield.addEventListener(FocusEvent.FOCUS_OUT, __lostFocus); this.hasFocus = false; } /** * Called from LzInputText#_gotFocusEvent() after focus was set by lz.Focus * @access private */ public function gotFocus () :void { if ( this.hasFocus ) { return; } // assign keyboard control LFCApplication.stage.focus = this.textfield; this.select(); this.hasFocus = true; } /** * Called from LzInputText#_gotBlurEvent() after focus was cleared by lz.Focus * @access private */ function gotBlur () :void { this.hasFocus = false; this.deselect(); if (LFCApplication.stage.focus === this.textfield) { // remove keyboard control LFCApplication.stage.focus = LFCApplication.stage; } } function select () :void { textfield.setSelection(0, textfield.text.length); } function deselect () :void { textfield.setSelection(0, 0); } /** * TODO [hqm 2008-01] I have no idea whether this comment * still applies: * Register for update on every frame when the text field gets the focus. * Set the behavior of the enter key depending on whether the field is * multiline or not. * * @access private */ function __gotFocus (event:FocusEvent) :void { // scroll text fields horizontally back to start if (owner) owner.inputtextevent('onfocus'); } /** * @access private * TODO [hqm 2008-01] Does we still need this workaround??? */ function __lostFocus (event:FocusEvent) :void { // defer execution, see swf8 kernel LzTimeKernel.setTimeout(this.__handlelostFocus, 1, event); } /** * TODO [hqm 2008-01] Does this comment still apply? Do we still need this workaround??? * * must be called after an idle event to prevent the selection from being * cleared prematurely, e.g. before a button click. If the selection is * cleared, the button doesn't send mouse events. * @access private */ function __handlelostFocus (event:Event) :void { if (owner) owner.inputtextevent('onblur'); } /** * Register to be called when the text field is modified. Convert this * into a LFC ontext event. * @access private */ function __onChanged (event:Event) :void { this.text = this.getText(); if (owner) owner.inputtextevent('onchange', this.text); } /** * Get the current text for this inputtext-sprite. * @protected */ override public function getText() :String { // We normalize swf's \r to \n return this.textfield.text.replace(/\r/g, '\n'); } /** * Sets whether user can modify input text field * @param Boolean enabled: true if the text field can be edited */ function setEnabled (enabled:Boolean) :void { this.enabled = enabled; if (enabled) { textfield.type = 'input'; } else { textfield.type = 'dynamic'; } } /** * If a mouse event occurs in an input text field, find the focused view */ static function findSelection() :LzInputText { var f:InteractiveObject = LFCApplication.stage.focus; if (f is TextField && f.parent is LzInputTextSprite) { return (f.parent as LzInputTextSprite).owner; } return null; } }# // #passthrough } // End of LzInputTextSprite
/** * LzInputTextSprite.as * * @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved. * Use is subject to license terms. * * @topic Kernel * @subtopic swf9 */ /** * @shortdesc Used for input text. * */ public class LzInputTextSprite extends LzTextSprite { #passthrough (toplevel:true) { import flash.display.InteractiveObject; import flash.events.Event; import flash.events.FocusEvent; import flash.text.TextField; import flash.text.TextFormat; import flash.text.TextFieldType; }# #passthrough { function LzInputTextSprite (newowner:LzView = null, args:Object = null) { super(newowner); } var enabled :Boolean = true; var focusable :Boolean = true; var hasFocus :Boolean = false; override public function __initTextProperties (args:Object) :void { super.__initTextProperties(args); // We do not support html in input fields. this.html = false; if (this.enabled) { textfield.type = TextFieldType.INPUT; } else { textfield.type = TextFieldType.DYNAMIC; } /* TODO [hqm 2008-01] these handlers need to be implemented via Flash native event listenters: focusIn , focusOut change -- dispatched after text input is modified textInput -- dispatched before the content is modified Do we need to use this for intercepting when we have a pattern restriction on input? */ textfield.addEventListener(Event.CHANGE , __onChanged); //textfield.addEventListener(TextEvent.TEXT_INPUT, __onTextInput); textfield.addEventListener(FocusEvent.FOCUS_IN , __gotFocus); textfield.addEventListener(FocusEvent.FOCUS_OUT, __lostFocus); this.hasFocus = false; } /** * Called from LzInputText#_gotFocusEvent() after focus was set by lz.Focus * @access private */ public function gotFocus () :void { if ( this.hasFocus ) { return; } // assign keyboard control LFCApplication.stage.focus = this.textfield; this.select(); this.hasFocus = true; } /** * Called from LzInputText#_gotBlurEvent() after focus was cleared by lz.Focus * @access private */ function gotBlur () :void { this.hasFocus = false; this.deselect(); if (LFCApplication.stage.focus === this.textfield) { // remove keyboard control LFCApplication.stage.focus = LFCApplication.stage; } } function select () :void { textfield.setSelection(0, textfield.text.length); } function deselect () :void { textfield.setSelection(0, 0); } /** * TODO [hqm 2008-01] I have no idea whether this comment * still applies: * Register for update on every frame when the text field gets the focus. * Set the behavior of the enter key depending on whether the field is * multiline or not. * * @access private */ function __gotFocus (event:FocusEvent) :void { // scroll text fields horizontally back to start if (owner) owner.inputtextevent('onfocus'); } /** * @access private * TODO [hqm 2008-01] Does we still need this workaround??? */ function __lostFocus (event:FocusEvent) :void { // defer execution, see swf8 kernel LzTimeKernel.setTimeout(this.__handlelostFocus, 1, event); } /** * TODO [hqm 2008-01] Does this comment still apply? Do we still need this workaround??? * * must be called after an idle event to prevent the selection from being * cleared prematurely, e.g. before a button click. If the selection is * cleared, the button doesn't send mouse events. * @access private */ function __handlelostFocus (event:Event) :void { if (owner) owner.inputtextevent('onblur'); } /** * Register to be called when the text field is modified. Convert this * into a LFC ontext event. * @access private */ function __onChanged (event:Event) :void { this.text = this.getText(); if (owner) owner.inputtextevent('onchange', this.text); } /** * Get the current text for this inputtext-sprite. * @protected */ override public function getText() :String { // We normalize swf's \r to \n return this.textfield.text.replace(/\r/g, '\n'); } /** * Sets whether user can modify input text field * @param Boolean enabled: true if the text field can be edited */ function setEnabled (enabled:Boolean) :void { this.enabled = enabled; if (enabled) { textfield.type = TextFieldType.INPUT; } else { textfield.type = TextFieldType.DYNAMIC; } var df:TextFormat = textfield.defaultTextFormat; // reset textformat to workaround flash player bug (FP-77) textfield.defaultTextFormat = df; } /** * If a mouse event occurs in an input text field, find the focused view */ static function findSelection() :LzInputText { var f:InteractiveObject = LFCApplication.stage.focus; if (f is TextField && f.parent is LzInputTextSprite) { return (f.parent as LzInputTextSprite).owner; } return null; } }# // #passthrough } // End of LzInputTextSprite
Change 20091028-hqm-2 by [email protected] on 2009-10-28 15:53:59 EDT in /Users/hqm/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
Change 20091028-hqm-2 by [email protected] on 2009-10-28 15:53:59 EDT in /Users/hqm/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk Summary: fix bug with disable/enable input text in swf10 New Features: Bugs Fixed: LPP-8574 Technical Reviewer: andre QA Reviewer: max Doc Reviewer: (pending) Documentation: Release Notes: Details: Use the workaround suggested by Flash Player bug FP-77, reset the defaultTextFormat manually. Tests: test case from bug report works git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@15073 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
ActionScript
epl-1.0
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
ee53a0253c3012d5673767ec32fd7fabf73c324d
src/laml/display/Skin.as
src/laml/display/Skin.as
package laml.display { import flash.display.DisplayObject; import flash.display.Sprite; public class Skin extends Sprite implements ISkin { public function getBitmapByName(alias:String):DisplayObject { if(hasOwnProperty(alias)) { return new this[alias]() as DisplayObject; } return null; } } }
package laml.display { import flash.display.DisplayObject; import flash.display.Sprite; import mx.core.BitmapAsset; import mx.core.FontAsset; import mx.core.IFlexAsset; import mx.core.IFlexDisplayObject; import mx.core.SpriteAsset; public class Skin extends Sprite implements ISkin { private var bitmapAsset:BitmapAsset; private var fontAsset:FontAsset; private var iFlexAsset:IFlexAsset; private var iFlexDisplayObject:IFlexDisplayObject; private var spriteAsset:SpriteAsset; public function getBitmapByName(alias:String):DisplayObject { if(hasOwnProperty(alias)) { return new this[alias]() as DisplayObject; } return null; } } }
Put MX dependencies in skin
Put MX dependencies in skin git-svn-id: 02605e11d3a461bc7e12f3f3880edf4b0c8dcfd0@4281 3e7533ad-8678-4d30-8e38-00a379d3f0d0
ActionScript
mit
lukebayes/laml