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
|
---|---|---|---|---|---|---|---|---|---|
91346fa2b8848f4fb9609bcfe9dbd8fe45b0f12e
|
src/goplayer/StreamioAPI.as
|
src/goplayer/StreamioAPI.as
|
package goplayer
{
public class StreamioAPI implements MovieEventReporter
{
private static const VERSION : String = "/v1"
private var baseURL : String
private var http : HTTP
private var trackerID : String
public function StreamioAPI
(baseURL : String, http : HTTP, trackerID : String)
{
this.baseURL = baseURL
this.http = http
this.trackerID = trackerID
}
// -----------------------------------------------------
public function fetchMovie
(id : String, handler : MovieHandler) : void
{ fetch(getMoviePath(id), new MovieJSONHandler(handler)) }
public function reportMovieViewed(movieID : String) : void
{ reportMovieEvent(movieID, "views", {}) }
public function reportMoviePlayed(movieID : String) : void
{ reportMovieEvent(movieID, "plays", {}) }
public function reportMovieHeatmapData
(movieID : String, time : Number) : void
{ reportMovieEvent(movieID, "heat", { time: time }) }
private function reportMovieEvent
(movieID : String, event : String, parameters : Object) : void
{ post(statsPath, getStatsParameters(movieID, event, parameters)) }
private function getStatsParameters
(movieID : String, event : String, parameters : Object) : Object
{
const result : Object = new Object
result.tracker_id = trackerID
result.movie_id = movieID
result.event = event
for (var name : String in parameters)
result[name] = parameters[name]
return result
}
// -----------------------------------------------------
private function getMoviePath(id : String) : String
{ return "/videos/" + id + "/public_show.json" }
private function get statsPath() : String
{ return "/stats" }
// -----------------------------------------------------
private function fetch(path : String, handler : JSONHandler) : void
{ http.fetchJSON(getURL(path), handler) }
private function post(path : String, parameters : Object) : void
{ http.post(getURL(path), parameters, new NullHTTPHandler) }
private function getURL(path : String) : URL
{ return URL.parse(baseURL + VERSION + path) }
}
}
import goplayer.*
class MovieJSONHandler implements JSONHandler
{
private var handler : MovieHandler
public function MovieJSONHandler(handler : MovieHandler)
{ this.handler = handler }
public function handleJSON(json : Object) : void
{ handler.handleMovie(new StreamioMovie(json)) }
}
class NullHTTPHandler implements HTTPResponseHandler
{ public function handleHTTPResponse(text : String) : void {} }
|
package goplayer
{
public class StreamioAPI implements MovieEventReporter
{
private static const VERSION : String = "/v1"
private var baseURL : String
private var http : HTTP
private var trackerID : String
public function StreamioAPI
(baseURL : String, http : HTTP, trackerID : String)
{
this.baseURL = baseURL
this.http = http
this.trackerID = trackerID
}
// -----------------------------------------------------
public function fetchMovie
(id : String, handler : MovieHandler) : void
{ fetch(getMoviePath(id), new MovieJSONHandler(handler)) }
public function reportMovieViewed(movieID : String) : void
{ reportMovieEvent(movieID, "views", {}) }
public function reportMoviePlayed(movieID : String) : void
{ reportMovieEvent(movieID, "plays", {}) }
public function reportMovieHeatmapData
(movieID : String, time : Number) : void
{ reportMovieEvent(movieID, "heat", { time: time }) }
private function reportMovieEvent
(movieID : String, event : String, parameters : Object) : void
{
if (trackerID != null && trackerID != "")
post(statsPath, getStatsParameters(movieID, event, parameters))
}
private function getStatsParameters
(movieID : String, event : String, parameters : Object) : Object
{
const result : Object = new Object
result.tracker_id = trackerID
result.movie_id = movieID
result.event = event
for (var name : String in parameters)
result[name] = parameters[name]
return result
}
// -----------------------------------------------------
private function getMoviePath(id : String) : String
{ return "/videos/" + id + "/public_show.json" }
private function get statsPath() : String
{ return "/stats" }
// -----------------------------------------------------
private function fetch(path : String, handler : JSONHandler) : void
{ http.fetchJSON(getURL(path), handler) }
private function post(path : String, parameters : Object) : void
{ http.post(getURL(path), parameters, new NullHTTPHandler) }
private function getURL(path : String) : URL
{ return URL.parse(baseURL + VERSION + path) }
}
}
import goplayer.*
class MovieJSONHandler implements JSONHandler
{
private var handler : MovieHandler
public function MovieJSONHandler(handler : MovieHandler)
{ this.handler = handler }
public function handleJSON(json : Object) : void
{ handler.handleMovie(new StreamioMovie(json)) }
}
class NullHTTPHandler implements HTTPResponseHandler
{ public function handleHTTPResponse(text : String) : void {} }
|
Disable tracking when `streamio:tracker' is empty.
|
Disable tracking when `streamio:tracker' is empty.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
be6296c51b0bc18c805c8029993b3dcfea3ee636
|
externs/GCL/src/goog/events/EventTarget.as
|
externs/GCL/src/goog/events/EventTarget.as
|
package goog.events {
import goog.Disposable;
/**
* An implementation of {@code goog.events.Listenable} with full W3C
* EventTarget-like support (capture/bubble mechanism, stopping event
* propagation, preventing default actions).
*
* You may subclass this class to turn your class into a Listenable.
*
* Unless propagation is stopped, an event dispatched by an
* EventTarget will bubble to the parent returned by
* {@code getParentEventTarget}. To set the parent, call
* {@code setParentEventTarget}. Subclasses that don't support
* changing the parent can override the setter to throw an error.
*
* Example usage:
* <pre>
* var source = new goog.events.EventTarget();
* function handleEvent(e) {
* alert('Type: ' + e.type + '; Target: ' + e.target);
* }
* source.listen('foo', handleEvent);
* // Or: goog.events.listen(source, 'foo', handleEvent);
* ...
* source.dispatchEvent('foo'); // will call handleEvent
* ...
* source.unlisten('foo', handleEvent);
* // Or: goog.events.unlisten(source, 'foo', handleEvent);
* </pre>
*
* @see [eventtarget]
*/
public class EventTarget extends Disposable implements Listenable {
/**
* Marks a given class (constructor) as an implementation of
* Listenable, do that we can query that fact at runtime. The class
* must have already implemented the interface.
*
* @param cls [Function] The class constructor. The corresponding class must have already implemented the interface.
* @see [listenable]
*/
public static function addImplementation(cls:Class /* Function */):void {}
/**
* @param obj [(Object|null)] The object to check.
* @see [listenable]
* @returns {boolean} Whether a given instance implements Listenable. The class/superclass of the instance must call addImplementation.
*/
public static function isImplementedBy(obj:Object):Boolean {return false}
/**
* An implementation of {@code goog.events.Listenable} with full W3C
* EventTarget-like support (capture/bubble mechanism, stopping event
* propagation, preventing default actions).
*
* You may subclass this class to turn your class into a Listenable.
*
* Unless propagation is stopped, an event dispatched by an
* EventTarget will bubble to the parent returned by
* {@code getParentEventTarget}. To set the parent, call
* {@code setParentEventTarget}. Subclasses that don't support
* changing the parent can override the setter to throw an error.
*
* Example usage:
* <pre>
* var source = new goog.events.EventTarget();
* function handleEvent(e) {
* alert('Type: ' + e.type + '; Target: ' + e.target);
* }
* source.listen('foo', handleEvent);
* // Or: goog.events.listen(source, 'foo', handleEvent);
* ...
* source.dispatchEvent('foo'); // will call handleEvent
* ...
* source.unlisten('foo', handleEvent);
* // Or: goog.events.unlisten(source, 'foo', handleEvent);
* </pre>
*
* @see [eventtarget]
*/
public function EventTarget() {
super();
}
/**
* @see [eventtarget]
*/
public function removeAllListeners(type:String = null):Number { return 0 }
/**
* Sets the target to be used for {@code event.target} when firing
* event. Mainly used for testing. For example, see
* {@code goog.testing.events.mixinListenable}.
*
* @param target [Object] The target.
* @see [eventtarget]
*/
public function setTargetForTesting(target:Object):void { }
/**
* Adds an event listener to the event target. The same handler can only be
* added once per the type. Even if you add the same handler multiple times
* using the same type then it will only be called once when the event is
* dispatched.
*
* @param type [string] The type of the event to listen for.
* @param handler [(function (?): ?|null|{handleEvent: function (?): ?})] The function to handle the event. The handler can also be an object that implements the handleEvent method which takes the event object as argument.
* @param opt_capture [(boolean|undefined)] In DOM-compliant browsers, this determines whether the listener is fired during the capture or bubble phase of the event.
* @param opt_handlerScope [(Object|null|undefined)] Object in whose scope to call the listener.
* @see [eventtarget]
*/
public function addEventListener(type:String, handler:Object, opt_capture:Boolean = false, opt_handlerScope:Object = null):void { }
/**
* Returns the parent of this event target to use for bubbling.
*
* @see [eventtarget]
* @returns {(goog.events.EventTarget|null)} The parent EventTarget or null if there is no parent.
*/
public function getParentEventTarget():EventTarget { return null; }
/**
* Removes an event listener from the event target. The handler must be the
* same object as the one added. If the handler has not been added then
* nothing is done.
*
* @param type [string] The type of the event to listen for.
* @param handler [(function (?): ?|null|{handleEvent: function (?): ?})] The function to handle the event. The handler can also be an object that implements the handleEvent method which takes the event object as argument.
* @param opt_capture [(boolean|undefined)] In DOM-compliant browsers, this determines whether the listener is fired during the capture or bubble phase of the event.
* @param opt_handlerScope [(Object|null|undefined)] Object in whose scope to call the listener.
* @see [eventtarget]
*/
public function removeEventListener(type:String, handler:Object, opt_capture:Boolean = false, opt_handlerScope:Object = null):void { }
/**
* Asserts that the event target instance is initialized properly.
*
* @see [eventtarget]
*/
public function assertInitialized_():void { }
/**
* @see [eventtarget]
*/
public function unlisten(type:Object, listener:Object, opt_useCapture:Boolean = false, opt_listenerScope:Object = null):void { }
/**
* @see [eventtarget]
*/
public function fireListeners(type:Object, capture:Boolean, eventObject:Object):Boolean { return false }
/**
* @see [eventtarget]
*/
public function listenOnce(type:Object, listener:Object, opt_useCapture:Boolean = false, opt_listenerScope:Object = null):ListenableKey { return null }
/**
* @see [eventtarget]
*/
public function unlistenByKey(key:ListenableKey):Boolean { return false }
/**
* @see [eventtarget]
*/
public function dispatchEvent(e:Object):Boolean { return false }
/**
* @see [eventtarget]
*/
public function hasListener(opt_type:Object = null, opt_capture:Boolean = false):Boolean { return false }
/**
* @see [eventtarget]
*/
public function getListener(type:Object, listener:Object, opt_useCapture:Boolean = false, opt_listenerScope:Object = null):goog.events.ListenableKey { return null }
/**
* @see [eventtarget]
*/
public function listen(type:Object, listener:Object, opt_useCapture:Boolean = false, opt_listenerScope:Object = null):goog.events.ListenableKey { return null }
/**
* Dispatches the given event on the ancestorsTree.
*
* @param target [Object] The target to dispatch on.
* @param e [(Object|goog.events.Event|null|string)] The event object.
* @param opt_ancestorsTree [(Array<(goog.events.Listenable|null)>|null|undefined)] The ancestors tree of the target, in reverse order from the closest ancestor to the root event target. May be null if the target has no ancestor.
* @see [eventtarget]
* @returns {boolean} If anyone called preventDefault on the event object (or if any of the listeners returns false) this will also return false.
*/
public static function dispatchEventInternal_(target:Object, e:Object, opt_ancestorsTree:Array = null):Boolean { return false }
/**
* @see [eventtarget]
*/
public function getListeners(type:Object, capture:Boolean):Array { return null }
/**
* Sets the parent of this event target to use for capture/bubble
* mechanism.
*
* @param parent [(goog.events.EventTarget|null)] Parent listenable (null if none).
* @see [eventtarget]
*/
public function setParentEventTarget(parent:EventTarget):void { }
}
}
|
package goog.events {
import goog.Disposable;
/**
* An implementation of {@code goog.events.Listenable} with full W3C
* EventTarget-like support (capture/bubble mechanism, stopping event
* propagation, preventing default actions).
*
* You may subclass this class to turn your class into a Listenable.
*
* Unless propagation is stopped, an event dispatched by an
* EventTarget will bubble to the parent returned by
* {@code getParentEventTarget}. To set the parent, call
* {@code setParentEventTarget}. Subclasses that don't support
* changing the parent can override the setter to throw an error.
*
* Example usage:
* <pre>
* var source = new goog.events.EventTarget();
* function handleEvent(e) {
* alert('Type: ' + e.type + '; Target: ' + e.target);
* }
* source.listen('foo', handleEvent);
* // Or: goog.events.listen(source, 'foo', handleEvent);
* ...
* source.dispatchEvent('foo'); // will call handleEvent
* ...
* source.unlisten('foo', handleEvent);
* // Or: goog.events.unlisten(source, 'foo', handleEvent);
* </pre>
*
* @see [eventtarget]
*/
public class EventTarget extends Disposable implements Listenable {
/**
* Marks a given class (constructor) as an implementation of
* Listenable, do that we can query that fact at runtime. The class
* must have already implemented the interface.
*
* @param cls [Function] The class constructor. The corresponding class must have already implemented the interface.
* @see [listenable]
*/
public static function addImplementation(cls:Function):void {}
/**
* @param obj [(Object|null)] The object to check.
* @see [listenable]
* @returns {boolean} Whether a given instance implements Listenable. The class/superclass of the instance must call addImplementation.
*/
public static function isImplementedBy(obj:Object):Boolean {return false}
/**
* An implementation of {@code goog.events.Listenable} with full W3C
* EventTarget-like support (capture/bubble mechanism, stopping event
* propagation, preventing default actions).
*
* You may subclass this class to turn your class into a Listenable.
*
* Unless propagation is stopped, an event dispatched by an
* EventTarget will bubble to the parent returned by
* {@code getParentEventTarget}. To set the parent, call
* {@code setParentEventTarget}. Subclasses that don't support
* changing the parent can override the setter to throw an error.
*
* Example usage:
* <pre>
* var source = new goog.events.EventTarget();
* function handleEvent(e) {
* alert('Type: ' + e.type + '; Target: ' + e.target);
* }
* source.listen('foo', handleEvent);
* // Or: goog.events.listen(source, 'foo', handleEvent);
* ...
* source.dispatchEvent('foo'); // will call handleEvent
* ...
* source.unlisten('foo', handleEvent);
* // Or: goog.events.unlisten(source, 'foo', handleEvent);
* </pre>
*
* @see [eventtarget]
*/
public function EventTarget() {
super();
}
/**
* @see [eventtarget]
*/
public function removeAllListeners(type:String = null):Number { return 0 }
/**
* Sets the target to be used for {@code event.target} when firing
* event. Mainly used for testing. For example, see
* {@code goog.testing.events.mixinListenable}.
*
* @param target [Object] The target.
* @see [eventtarget]
*/
public function setTargetForTesting(target:Object):void { }
/**
* Adds an event listener to the event target. The same handler can only be
* added once per the type. Even if you add the same handler multiple times
* using the same type then it will only be called once when the event is
* dispatched.
*
* @param type [string] The type of the event to listen for.
* @param handler [(function (?): ?|null|{handleEvent: function (?): ?})] The function to handle the event. The handler can also be an object that implements the handleEvent method which takes the event object as argument.
* @param opt_capture [(boolean|undefined)] In DOM-compliant browsers, this determines whether the listener is fired during the capture or bubble phase of the event.
* @param opt_handlerScope [(Object|null|undefined)] Object in whose scope to call the listener.
* @see [eventtarget]
*/
public function addEventListener(type:String, handler:Object, opt_capture:Boolean = false, opt_handlerScope:Object = null):void { }
/**
* Returns the parent of this event target to use for bubbling.
*
* @see [eventtarget]
* @returns {(goog.events.EventTarget|null)} The parent EventTarget or null if there is no parent.
*/
public function getParentEventTarget():EventTarget { return null; }
/**
* Removes an event listener from the event target. The handler must be the
* same object as the one added. If the handler has not been added then
* nothing is done.
*
* @param type [string] The type of the event to listen for.
* @param handler [(function (?): ?|null|{handleEvent: function (?): ?})] The function to handle the event. The handler can also be an object that implements the handleEvent method which takes the event object as argument.
* @param opt_capture [(boolean|undefined)] In DOM-compliant browsers, this determines whether the listener is fired during the capture or bubble phase of the event.
* @param opt_handlerScope [(Object|null|undefined)] Object in whose scope to call the listener.
* @see [eventtarget]
*/
public function removeEventListener(type:String, handler:Object, opt_capture:Boolean = false, opt_handlerScope:Object = null):void { }
/**
* Asserts that the event target instance is initialized properly.
*
* @see [eventtarget]
*/
public function assertInitialized_():void { }
/**
* @see [eventtarget]
*/
public function unlisten(type:Object, listener:Object, opt_useCapture:Boolean = false, opt_listenerScope:Object = null):void { }
/**
* @see [eventtarget]
*/
public function fireListeners(type:Object, capture:Boolean, eventObject:Object):Boolean { return false }
/**
* @see [eventtarget]
*/
public function listenOnce(type:Object, listener:Object, opt_useCapture:Boolean = false, opt_listenerScope:Object = null):ListenableKey { return null }
/**
* @see [eventtarget]
*/
public function unlistenByKey(key:ListenableKey):Boolean { return false }
/**
* @see [eventtarget]
*/
public function dispatchEvent(e:Object):Boolean { return false }
/**
* @see [eventtarget]
*/
public function hasListener(opt_type:Object = null, opt_capture:Boolean = false):Boolean { return false }
/**
* @see [eventtarget]
*/
public function getListener(type:Object, listener:Object, opt_useCapture:Boolean = false, opt_listenerScope:Object = null):goog.events.ListenableKey { return null }
/**
* @see [eventtarget]
*/
public function listen(type:Object, listener:Object, opt_useCapture:Boolean = false, opt_listenerScope:Object = null):goog.events.ListenableKey { return null }
/**
* Dispatches the given event on the ancestorsTree.
*
* @param target [Object] The target to dispatch on.
* @param e [(Object|goog.events.Event|null|string)] The event object.
* @param opt_ancestorsTree [(Array<(goog.events.Listenable|null)>|null|undefined)] The ancestors tree of the target, in reverse order from the closest ancestor to the root event target. May be null if the target has no ancestor.
* @see [eventtarget]
* @returns {boolean} If anyone called preventDefault on the event object (or if any of the listeners returns false) this will also return false.
*/
public static function dispatchEventInternal_(target:Object, e:Object, opt_ancestorsTree:Array = null):Boolean { return false }
/**
* @see [eventtarget]
*/
public function getListeners(type:Object, capture:Boolean):Array { return null }
/**
* Sets the parent of this event target to use for capture/bubble
* mechanism.
*
* @param parent [(goog.events.EventTarget|null)] Parent listenable (null if none).
* @see [eventtarget]
*/
public function setParentEventTarget(parent:EventTarget):void { }
}
}
|
switch back to Function instead of Class
|
switch back to Function instead of Class
|
ActionScript
|
apache-2.0
|
greg-dove/flex-falcon,adufilie/flex-falcon,adufilie/flex-falcon,greg-dove/flex-falcon,adufilie/flex-falcon,greg-dove/flex-falcon,greg-dove/flex-falcon,adufilie/flex-falcon
|
be52e9a23c3b6e1d7b67bdd42b4b49563da0e976
|
test/basic.as
|
test/basic.as
|
package test {
class Literal {
function test() {
call(1, 1, 200, 200, -1, -50, 32767, 32768, -32760, -500000);
}
}
class Arithmetics {
function b() {
var a:int = 0;
var b:int;
b = (a += 1);
return (b -= (a += 1));
}
function a() {
var a:int = 0;
var b:int = ++a;
var c:int = a++;
return a;
}
}
class Logic {
function P_a_or_b_p_and_P_c_and_d_p_or_e(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
var v:Boolean = (a || b) && (c && d) || e;
away();
return v;
}
function a_or_b(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
if(a || b) {
yes();
} else {
no();
}
}
function a_and_b_and_c(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return a && (b && c);
}
function P_a_and_b_p_and_c(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return (a && b) && c;
}
function a_and_b(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return a && b;
}
}
class Ternary {
function hardcore(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
if(((a && b) ? (c || d) && e : b) && (a || b)) {
return pow();
} else {
weeee();
}
duh();
}
function q(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return ((a ? b : c) ? (b ? c : d) : (c ? d : e));
}
function a_I_b_E_c_I_d_E_e(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return a ? b : (c ? d : e);
}
function a_I_b_I_c_E_d_E_e(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return a ? (b ? c : d) : e;
}
function a_I_b_E_c(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return (1 > 2) ? b : c;
}
}
class Conditionals {
function elsif(param1:Boolean, param2:Boolean) : Boolean {
if(param1) {
return true;
} else if(param2) {
return false;
} else {
return null;
}
}
function els(param1:Object, param2:String, param3:String) : Boolean {
var _loc_4:Object = null;
if (param1 != null)
{
_loc_4 = param1[param2];
if (_loc_4 != null)
{
if (_loc_4[param3] != null)
{
return true;
}
a();
}
b();
}
heys();
return false;
}
function els2(param1:Object, param2:String, param3:String) : Boolean {
var _loc_4:Object = null;
if (param1 != null)
{
_loc_4 = param1[param2];
if (_loc_4 != null)
{
if (_loc_4[param3] != null)
{
return true;
}
}
}
heys();
return false;
}
function b(a:Boolean) {
if(a)
return foo();
else
return 1;
}
function q(a:Boolean, b:Boolean) {
if(b) {
if(a) {
foo();
}
}
baz();
}
function a(a:Boolean) {
baz();
if(a) {
foge();
} else {
huga();
}
piyo();
}
function nested(a:Boolean, b:Boolean) {
if(a) {
foo();
} else {
if(b) {
bar();
} else {
baz();
}
}
}
}
class Loops {
function e(f:Boolean) {
do { f = tttest();
} while(f);
}
function d() {
while(true) {
pow();
if(frak()) { a(); break; b(); }
weee();
}
}
function b() {
weee();
for(var q:int = 1; q > 0; q++) {
frak();
}
}
}
class Switch {
function improper_switch(q:int):Boolean {
switch(q) {
case 0x10:
hoge();
break;
case "test":
fuga();
break;
case 0x30:
piyo();
break;
case 0x40:
fuck();
break;
}
return false;
}
function proper_switch(q:int):Boolean {
switch(q) {
case 1:
hoge();
break;
case 2:
fuga();
break;
case 3:
piyo();
break;
case 5:
bar();
break;
default:
baz();
break;
}
return false;
}
function fallthrough_switch(q:int):Boolean {
switch(q) {
case 0x10:
hoge();
case 0x20:
fuga();
break;
case 0x30:
piyo();
break;
default:
baz();
break;
}
return false;
}
}
class Closures {
function a() {
var a:int = 1;
var f = function(param) {
var b:int = 10;
return a + this.fuga() + hoge() + param;
};
var q = function() {
test123();
};
q();
return f;
}
}
class Exceptions {
function e() {
if(a) {
try {
try {
a();
} catch(e) {
b();
}
hoge();
} finally {
piyo();
}
}
}
function d() {
if(a) {
try {
hoge();
} finally {
piyo();
}
}
}
function c() {
try {
hoge();
} finally {
piyo();
}
}
function b() {
try {
hoge();
throw 1;
fuga();
} catch(e: SecurityError) {
piyo(e);
}
}
function a() {
try {
hoge();
throw 1;
fuga();
} catch(e: SecurityError) {
piyo(e);
} catch(e: Error) {
throw e;
}
}
}
}
|
package test {
class Literal {
function test() {
call(1, 1, 200, 200, -1, -50, 32767, 32768, -32760, -500000);
}
}
class Arithmetics {
function b() {
var a:int = 0;
var b:int;
b = (a += 1);
return (b -= (a += 1));
}
function a() {
var a:int = 0;
var b:int = ++a;
var c:int = a++;
return a;
}
}
class Logic {
function P_a_or_b_p_and_P_c_and_d_p_or_e(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
var v:Boolean = (a || b) && (c && d) || e;
away();
return v;
}
function a_or_b(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
if(a || b) {
yes();
} else {
no();
}
}
function a_and_b_and_c(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return a && (b && c);
}
function P_a_and_b_p_and_c(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return (a && b) && c;
}
function a_and_b(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return a && b;
}
}
class Ternary {
function hardcore(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
if(((a && b) ? (c || d) && e : b) && (a || b)) {
return pow();
} else {
weeee();
}
duh();
}
function q(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return ((a ? b : c) ? (b ? c : d) : (c ? d : e));
}
function a_I_b_E_c_I_d_E_e(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return a ? b : (c ? d : e);
}
function a_I_b_I_c_E_d_E_e(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return a ? (b ? c : d) : e;
}
function a_I_b_E_c(a: Boolean, b:Boolean, c:Boolean, d:Boolean, e:Boolean) : Boolean {
return (1 > 2) ? b : c;
}
}
class Conditionals {
function elsif(param1:Boolean, param2:Boolean) : Boolean {
if(param1) {
return true;
} else if(param2) {
return false;
} else {
return null;
}
}
function els(param1:Object, param2:String, param3:String) : Boolean {
var _loc_4:Object = null;
if (param1 != null)
{
_loc_4 = param1[param2];
if (_loc_4 != null)
{
if (_loc_4[param3] != null)
{
return true;
}
a();
}
b();
}
heys();
return false;
}
function els2(param1:Object, param2:String, param3:String) : Boolean {
var _loc_4:Object = null;
if (param1 != null)
{
_loc_4 = param1[param2];
if (_loc_4 != null)
{
if (_loc_4[param3] != null)
{
return true;
}
}
}
heys();
return false;
}
function b(a:Boolean) {
if(a)
return foo();
else
return 1;
}
function q(a:Boolean, b:Boolean) {
if(b) {
if(a) {
foo();
}
}
baz();
}
function a(a:Boolean) {
baz();
if(a) {
foge();
} else {
huga();
}
piyo();
}
function nested(a:Boolean, b:Boolean) {
if(a) {
foo();
} else {
if(b) {
bar();
} else {
baz();
}
}
}
}
class Loops {
function e(f:Boolean) {
do { f = tttest();
} while(f);
}
function d() {
while(true) {
pow();
if(frak()) { a(); break; b(); }
weee();
}
}
function b() {
weee();
for(var q:int = 1; q > 0; q++) {
frak();
}
}
function a() {
var i:int = 0;
while(i++ < 5) {
hello();
}
return i;
}
}
class Switch {
function improper_switch(q:int):Boolean {
switch(q) {
case 0x10:
hoge();
break;
case "test":
fuga();
break;
case 0x30:
piyo();
break;
case 0x40:
fuck();
break;
}
return false;
}
function proper_switch(q:int):Boolean {
switch(q) {
case 1:
hoge();
break;
case 2:
fuga();
break;
case 3:
piyo();
break;
case 4:
bar();
break;
default:
baz();
break;
}
return false;
}
function fallthrough_switch(q:int):Boolean {
switch(q) {
case 0x10:
hoge();
case 0x20:
fuga();
break;
case 0x30:
piyo();
break;
default:
baz();
break;
}
return false;
}
}
class Closures {
function a() {
var a:int = 1;
var f = function(param) {
var b:int = 10;
return a + this.fuga() + hoge() + param;
};
var q = function() {
test123();
};
q();
return f;
}
}
class Exceptions {
function e() {
if(a) {
try {
try {
a();
} catch(e) {
b();
}
hoge();
} finally {
piyo();
}
}
}
function d() {
if(a) {
try {
hoge();
} finally {
piyo();
}
}
}
function c() {
try {
hoge();
} finally {
piyo();
}
}
function b() {
try {
hoge();
throw 1;
fuga();
} catch(e: SecurityError) {
piyo(e);
}
}
function a() {
try {
hoge();
throw 1;
fuga();
} catch(e: SecurityError) {
piyo(e);
} catch(e: Error) {
throw e;
}
}
}
}
|
Adjust testcases.
|
Adjust testcases.
|
ActionScript
|
mit
|
chris1201/furnace-avm2,whitequark/furnace-avm2
|
06e690e17adb2df18066681518cf83547fd72955
|
src/com/axis/rtspclient/RTSPoverHTTPHandle.as
|
src/com/axis/rtspclient/RTSPoverHTTPHandle.as
|
package com.axis.rtspclient {
import com.axis.ClientEvent;
import com.axis.ErrorManager;
import com.axis.http.auth;
import com.axis.http.request;
import com.axis.http.url;
import com.axis.Logger;
import com.axis.rtspclient.GUID;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.net.SecureSocket;
import flash.utils.ByteArray;
import flash.utils.*;
import mx.utils.Base64Encoder;
public class RTSPoverHTTPHandle extends EventDispatcher implements IRTSPHandle {
private var getChannel:Socket = null;
private var urlParsed:Object = {};
private var sessioncookie:String = "";
private var base64encoder:Base64Encoder;
private var secure:Boolean;
private var datacb:Function = null;
private var connectcb:Function = null;
private var authState:String = "none";
private var authOpts:Object = {};
private var digestNC:uint = 1;
private var getChannelData:ByteArray;
public function RTSPoverHTTPHandle(urlParsed:Object, secure:Boolean) {
this.sessioncookie = GUID.create();
this.urlParsed = urlParsed;
this.base64encoder = new Base64Encoder();
this.secure = secure;
}
private function setupSockets():void {
getChannel = this.secure ? new SecureSocket() : new Socket();
getChannel.timeout = 5000;
getChannel.addEventListener(Event.CONNECT, onGetChannelConnect);
getChannel.addEventListener(ProgressEvent.SOCKET_DATA, onGetChannelData);
getChannel.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
getChannel.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
getChannelData = new ByteArray();
}
private function base64encode(str:String):String {
base64encoder.reset();
base64encoder.insertNewLines = false;
base64encoder.encode(str);
return base64encoder.toString();
}
public function writeUTFBytes(value:String):void {
var data:String = base64encode(value);
var authHeader:String = auth.authorizationHeader("POST", authState, authOpts, urlParsed, digestNC++);
var socket:Socket = this.secure ? new SecureSocket() : new Socket();
socket.timeout = 5000;
socket.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
socket.addEventListener(Event.CONNECT, function ():void {
socket.writeUTFBytes("POST " + urlParsed.urlpath + " HTTP/1.0\r\n");
socket.writeUTFBytes("X-Sessioncookie: " + sessioncookie + "\r\n");
socket.writeUTFBytes("Content-Length: 32767" + "\r\n");
socket.writeUTFBytes("Content-Type: application/x-rtsp-tunnelled" + "\r\n");
socket.writeUTFBytes(authHeader);
socket.writeUTFBytes("\r\n");
socket.writeUTFBytes(data);
socket.flush();
// Timeout required before close to let the data actually be written to
// the socket. Flush appears to be asynchronous...
setTimeout(socket.close, 5000);
});
socket.connect(this.urlParsed.host, this.urlParsed.port);
}
public function readBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void {
getChannel.readBytes(bytes, offset, length);
}
public function disconnect():void {
if (getChannel.connected) {
getChannel.close();
getChannel.removeEventListener(Event.CONNECT, onGetChannelConnect);
getChannel.removeEventListener(ProgressEvent.SOCKET_DATA, onGetChannelData);
getChannel.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
getChannel.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
}
/* should probably wait for close, but it doesn't seem to fire properly */
dispatchEvent(new Event('closed'));
}
public function connect():void {
setupSockets();
Logger.log('RTSP+HTTP' + (this.secure ? 'S' : '') + 'connecting to', this.urlParsed.host + ':' + this.urlParsed.port);
getChannel.connect(this.urlParsed.host, this.urlParsed.port);
}
public function reconnect():void {
if (getChannel.connected) {
getChannel.close();
}
connect();
}
private function onGetChannelConnect(event:Event):void {
initializeGetChannel();
}
public function stop():void {
disconnect();
}
private function onGetChannelData(event:ProgressEvent):void {
var parsed:* = request.readHeaders(getChannel, getChannelData);
if (false === parsed) {
return;
}
if (401 === parsed.code) {
Logger.log('Unauthorized using auth method: ' + authState);
/* Unauthorized, change authState and (possibly) try again */
authOpts = parsed.headers['www-authenticate'];
var newAuthState:String = auth.nextMethod(authState, authOpts);
if (authState === newAuthState) {
ErrorManager.dispatchError(parsed.code);
return;
}
Logger.log('switching http-authorization from ' + authState + ' to ' + newAuthState);
authState = newAuthState;
getChannelData = new ByteArray();
getChannel.close();
getChannel.connect(this.urlParsed.host, this.urlParsed.port);
return;
}
if (200 !== parsed.code) {
ErrorManager.dispatchError(parsed.code);
return;
}
getChannel.removeEventListener(ProgressEvent.SOCKET_DATA, onGetChannelData);
getChannel.addEventListener(ProgressEvent.SOCKET_DATA, function(ev:ProgressEvent):void {
dispatchEvent(new Event('data'));
});
dispatchEvent(new Event('connected'));
}
private function initializeGetChannel():void {
getChannel.writeUTFBytes("GET " + urlParsed.urlpath + " HTTP/1.0\r\n");
getChannel.writeUTFBytes("X-Sessioncookie: " + sessioncookie + "\r\n");
getChannel.writeUTFBytes("Accept: application/x-rtsp-tunnelled\r\n");
getChannel.writeUTFBytes(auth.authorizationHeader("GET", authState, authOpts, urlParsed, digestNC++));
getChannel.writeUTFBytes("\r\n");
getChannel.flush();
}
private function onIOError(event:IOErrorEvent):void {
ErrorManager.dispatchError(732, [event.text]);
dispatchEvent(new Event('closed'));
}
private function onSecurityError(event:SecurityErrorEvent):void {
ErrorManager.dispatchError(731, [event.text]);
dispatchEvent(new Event('closed'));
}
}
}
|
package com.axis.rtspclient {
import com.axis.ClientEvent;
import com.axis.ErrorManager;
import com.axis.http.auth;
import com.axis.http.request;
import com.axis.http.url;
import com.axis.Logger;
import com.axis.rtspclient.GUID;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.net.SecureSocket;
import flash.utils.ByteArray;
import flash.utils.*;
import mx.utils.Base64Encoder;
public class RTSPoverHTTPHandle extends EventDispatcher implements IRTSPHandle {
private var getChannel:Socket = null;
private var urlParsed:Object = {};
private var sessioncookie:String = "";
private var base64encoder:Base64Encoder;
private var secure:Boolean;
private var datacb:Function = null;
private var connectcb:Function = null;
private var authState:String = "none";
private var authOpts:Object = {};
private var digestNC:uint = 1;
private var getChannelData:ByteArray;
public function RTSPoverHTTPHandle(urlParsed:Object, secure:Boolean) {
this.sessioncookie = GUID.create();
this.urlParsed = urlParsed;
this.base64encoder = new Base64Encoder();
this.secure = secure;
}
private function setupSockets():void {
getChannel = this.secure ? new SecureSocket() : new Socket();
getChannel.timeout = 5000;
getChannel.addEventListener(Event.CONNECT, onGetChannelConnect);
getChannel.addEventListener(ProgressEvent.SOCKET_DATA, onGetChannelData);
getChannel.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
getChannel.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
getChannelData = new ByteArray();
}
private function base64encode(str:String):String {
base64encoder.reset();
base64encoder.insertNewLines = false;
base64encoder.encode(str);
return base64encoder.toString();
}
public function writeUTFBytes(value:String):void {
var data:String = base64encode(value);
var authHeader:String = auth.authorizationHeader("POST", authState, authOpts, urlParsed, digestNC++);
var socket:Socket = this.secure ? new SecureSocket() : new Socket();
socket.timeout = 5000;
socket.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
socket.addEventListener(Event.CONNECT, function ():void {
socket.writeUTFBytes("POST " + urlParsed.urlpath + " HTTP/1.0\r\n");
socket.writeUTFBytes("X-Sessioncookie: " + sessioncookie + "\r\n");
socket.writeUTFBytes("Content-Length: " + data.length + "\r\n");
socket.writeUTFBytes("Content-Type: application/x-rtsp-tunnelled" + "\r\n");
socket.writeUTFBytes(authHeader);
socket.writeUTFBytes("\r\n");
socket.writeUTFBytes(data);
socket.flush();
// Timeout required before close to let the data actually be written to
// the socket. Flush appears to be asynchronous...
setTimeout(socket.close, 5000);
});
socket.connect(this.urlParsed.host, this.urlParsed.port);
}
public function readBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0):void {
getChannel.readBytes(bytes, offset, length);
}
public function disconnect():void {
if (getChannel.connected) {
getChannel.close();
getChannel.removeEventListener(Event.CONNECT, onGetChannelConnect);
getChannel.removeEventListener(ProgressEvent.SOCKET_DATA, onGetChannelData);
getChannel.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
getChannel.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
}
/* should probably wait for close, but it doesn't seem to fire properly */
dispatchEvent(new Event('closed'));
}
public function connect():void {
setupSockets();
Logger.log('RTSP+HTTP' + (this.secure ? 'S' : '') + 'connecting to', this.urlParsed.host + ':' + this.urlParsed.port);
getChannel.connect(this.urlParsed.host, this.urlParsed.port);
}
public function reconnect():void {
if (getChannel.connected) {
getChannel.close();
}
connect();
}
private function onGetChannelConnect(event:Event):void {
initializeGetChannel();
}
public function stop():void {
disconnect();
}
private function onGetChannelData(event:ProgressEvent):void {
var parsed:* = request.readHeaders(getChannel, getChannelData);
if (false === parsed) {
return;
}
if (401 === parsed.code) {
Logger.log('Unauthorized using auth method: ' + authState);
/* Unauthorized, change authState and (possibly) try again */
authOpts = parsed.headers['www-authenticate'];
var newAuthState:String = auth.nextMethod(authState, authOpts);
if (authState === newAuthState) {
ErrorManager.dispatchError(parsed.code);
return;
}
Logger.log('switching http-authorization from ' + authState + ' to ' + newAuthState);
authState = newAuthState;
getChannelData = new ByteArray();
getChannel.close();
getChannel.connect(this.urlParsed.host, this.urlParsed.port);
return;
}
if (200 !== parsed.code) {
ErrorManager.dispatchError(parsed.code);
return;
}
getChannel.removeEventListener(ProgressEvent.SOCKET_DATA, onGetChannelData);
getChannel.addEventListener(ProgressEvent.SOCKET_DATA, function(ev:ProgressEvent):void {
dispatchEvent(new Event('data'));
});
dispatchEvent(new Event('connected'));
}
private function initializeGetChannel():void {
getChannel.writeUTFBytes("GET " + urlParsed.urlpath + " HTTP/1.0\r\n");
getChannel.writeUTFBytes("X-Sessioncookie: " + sessioncookie + "\r\n");
getChannel.writeUTFBytes("Accept: application/x-rtsp-tunnelled\r\n");
getChannel.writeUTFBytes(auth.authorizationHeader("GET", authState, authOpts, urlParsed, digestNC++));
getChannel.writeUTFBytes("\r\n");
getChannel.flush();
}
private function onIOError(event:IOErrorEvent):void {
ErrorManager.dispatchError(732, [event.text]);
dispatchEvent(new Event('closed'));
}
private function onSecurityError(event:SecurityErrorEvent):void {
ErrorManager.dispatchError(731, [event.text]);
dispatchEvent(new Event('closed'));
}
}
}
|
Fix correct content length header in RTSP over HTTP
|
Fix correct content length header in RTSP over HTTP
|
ActionScript
|
bsd-3-clause
|
gaetancollaud/locomote-video-player,AxisCommunications/locomote-video-player
|
da5088a5258bab2c5744db4221b17cb2ba8cbe5b
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/accessories/NumericOnlyTextInputBead.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/html/accessories/NumericOnlyTextInputBead.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.accessories
{
import flash.events.TextEvent;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.html.beads.ITextFieldView;
/**
* The NumericOnlyTextInputBead class is a specialty bead that can be used with
* any TextInput control. The bead prevents non-numeric entry into the text input
* area.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class NumericOnlyTextInputBead implements IBead
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function NumericOnlyTextInputBead()
{
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener("viewChanged",viewChangeHandler);
}
private var _decimalSeparator:String = ".";
/**
* The character used to separate the integer and fraction parts of numbers.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get decimalSeparator():String
{
return _decimalSeparator;
}
public function set decimalSeparator(value:String):void
{
if (_decimalSeparator != value) {
_decimalSeparator = value;
}
}
/**
* @private
*/
private function viewChangeHandler(event:Event):void
{
// get the ITextFieldView bead, which is required for this bead to work
var textView:ITextFieldView = _strand.getBeadByType(ITextFieldView) as ITextFieldView;
if (textView) {
var textField:CSSTextField = textView.textField;
textField.restrict = "0-9" + decimalSeparator;
// listen for changes to this textField and prevent non-numeric values, such
// as 34.09.94
textField.addEventListener(TextEvent.TEXT_INPUT, handleTextInput);
}
else {
throw new Error("NumericOnlyTextInputBead requires strand to have an ITextFieldView bead");
}
}
/**
* @private
*/
private function handleTextInput(event:TextEvent):void
{
var insert:String = event.text;
var caretIndex:int = (event.target as CSSTextField).caretIndex;
var current:String = (event.target as CSSTextField).text;
var value:String = current.substring(0,caretIndex) + insert + current.substr(caretIndex);
var n:Number = Number(value);
if (isNaN(n)) event.preventDefault();
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.accessories
{
import flash.events.TextEvent;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.html.beads.ITextFieldView;
/**
* The NumericOnlyTextInputBead class is a specialty bead that can be used with
* any TextInput control. The bead prevents non-numeric entry into the text input
* area.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class NumericOnlyTextInputBead implements IBead
{
/**
* constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function NumericOnlyTextInputBead()
{
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener("viewChanged",viewChangeHandler);
}
private var _decimalSeparator:String = ".";
/**
* The character used to separate the integer and fraction parts of numbers.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get decimalSeparator():String
{
return _decimalSeparator;
}
public function set decimalSeparator(value:String):void
{
if (_decimalSeparator != value) {
_decimalSeparator = value;
}
}
private var _maxChars:int = 0;
/**
* The character used to separate the integer and fraction parts of numbers.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get maxChars():int
{
return _maxChars;
}
public function set maxChars(value:int):void
{
if (_maxChars != value) {
_maxChars = value;
}
}
/**
* @private
*/
private function viewChangeHandler(event:Event):void
{
// get the ITextFieldView bead, which is required for this bead to work
var textView:ITextFieldView = _strand.getBeadByType(ITextFieldView) as ITextFieldView;
if (textView) {
var textField:CSSTextField = textView.textField;
textField.restrict = "0-9" + decimalSeparator;
textField.maxChars = maxChars;
// listen for changes to this textField and prevent non-numeric values, such
// as 34.09.94
textField.addEventListener(TextEvent.TEXT_INPUT, handleTextInput);
}
else {
throw new Error("NumericOnlyTextInputBead requires strand to have an ITextFieldView bead");
}
}
/**
* @private
*/
private function handleTextInput(event:TextEvent):void
{
var insert:String = event.text;
var caretIndex:int = (event.target as CSSTextField).caretIndex;
var current:String = (event.target as CSSTextField).text;
var value:String = current.substring(0,caretIndex) + insert + current.substr(caretIndex);
var n:Number = Number(value);
if (isNaN(n)) event.preventDefault();
}
}
}
|
add maxChars
|
add maxChars
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
d5b2dab84ae07c9794ab9454a23a9e42f0960be6
|
tests/examplefiles/as3_test.as
|
tests/examplefiles/as3_test.as
|
import flash.events.MouseEvent;
import com.example.programmingas3.playlist.PlayList;
import com.example.programmingas3.playlist.Song;
import com.example.programmingas3.playlist.SortProperty;
// constants for the different "states" of the song form
private static const ADD_SONG:uint = 1;
private static const SONG_DETAIL:uint = 2;
private var playList:PlayList = new PlayList();
private function initApp():void
{
// set the initial state of the song form, for adding a new song
setFormState(ADD_SONG);
// prepopulate the list with a few songs
playList.addSong(new Song("Nessun Dorma", "Luciano Pavarotti", 1990, "nessundorma.mp3", ["90's", "Opera"]));
playList.addSong(new Song("Come Undone", "Duran Duran", 1993, "comeundone.mp3", ["90's", "Pop"]));
playList.addSong(new Song("Think of Me", "Sarah Brightman", 1987, "thinkofme.mp3", ["Showtunes"]));
playList.addSong(new Song("Unbelievable", "EMF", 1991, "unbelievable.mp3", ["90's", "Pop"]));
songList.dataProvider = playList.songList;
}
private function sortList(sortField:SortProperty):void
{
// Make all the sort type buttons enabled.
// The active one will be grayed-out below
sortByTitle.selected = false;
sortByArtist.selected = false;
sortByYear.selected = false;
switch (sortField)
{
case SortProperty.TITLE:
sortByTitle.selected = true;
break;
case SortProperty.ARTIST:
sortByArtist.selected = true;
break;
case SortProperty.YEAR:
sortByYear.selected = true;
break;
}
playList.sortList(sortField);
refreshList();
}
private function refreshList():void
{
// remember which song was selected
var selectedSong:Song = Song(songList.selectedItem);
// re-assign the song list as the dataprovider to get the newly sorted list
// and force the List control to refresh itself
songList.dataProvider = playList.songList;
// reset the song selection
if (selectedSong != null)
{
songList.selectedItem = selectedSong;
}
}
private function songSelectionChange():void
{
if (songList.selectedIndex != -1)
{
setFormState(SONG_DETAIL);
}
else
{
setFormState(ADD_SONG);
}
}
private function addNewSong():void
{
// gather the values from the form and add the new song
var title:String = newSongTitle.text;
var artist:String = newSongArtist.text;
var year:uint = newSongYear.value;
var filename:String = newSongFilename.text;
var genres:Array = newSongGenres.selectedItems;
playList.addSong(new Song(title, artist, year, filename, genres));
refreshList();
// clear out the "add song" form fields
setFormState(ADD_SONG);
}
private function songListLabel(item:Object):String
{
return item.toString();
}
private function setFormState(state:uint):void
{
// set the form title and control state
switch (state)
{
case ADD_SONG:
formTitle.text = "Add New Song";
// show the submit button
submitSongData.visible = true;
showAddControlsBtn.visible = false;
// clear the form fields
newSongTitle.text = "";
newSongArtist.text = "";
newSongYear.value = (new Date()).fullYear;
newSongFilename.text = "";
newSongGenres.selectedIndex = -1;
// deselect the currently selected song (if any)
songList.selectedIndex = -1;
break;
case SONG_DETAIL:
formTitle.text = "Song Details";
// populate the form with the selected item's data
var selectedSong:Song = Song(songList.selectedItem);
newSongTitle.text = selectedSong.title;
newSongArtist.text = selectedSong.artist;
newSongYear.value = selectedSong.year;
newSongFilename.text = selectedSong.filename;
newSongGenres.selectedItems = selectedSong.genres;
// hide the submit button
submitSongData.visible = false;
showAddControlsBtn.visible = true;
break;
}
}
|
import flash.events.MouseEvent;
import com.example.programmingas3.playlist.PlayList;
import com.example.programmingas3.playlist.Song;
import com.example.programmingas3.playlist.SortProperty;
// constants for the different "states" of the song form
private static const ADD_SONG:uint = 1;
private static const SONG_DETAIL:uint = 2;
private var playList:PlayList = new PlayList.<T>();
private function initApp():void
{
// set the initial state of the song form, for adding a new song
setFormState(ADD_SONG);
// prepopulate the list with a few songs
playList.addSong(new Song("Nessun Dorma", "Luciano Pavarotti", 1990, "nessundorma.mp3", ["90's", "Opera"]));
playList.addSong(new Song("Come Undone", "Duran Duran", 1993, "comeundone.mp3", ["90's", "Pop"]));
playList.addSong(new Song("Think of Me", "Sarah Brightman", 1987, "thinkofme.mp3", ["Showtunes"]));
playList.addSong(new Song("Unbelievable", "EMF", 1991, "unbelievable.mp3", ["90's", "Pop"]));
songList.dataProvider = playList.songList;
}
private function sortList(sortField:SortProperty.<T>):void
{
// Make all the sort type buttons enabled.
// The active one will be grayed-out below
sortByTitle.selected = false;
sortByArtist.selected = false;
sortByYear.selected = false;
switch (sortField)
{
case SortProperty.TITLE:
sortByTitle.selected = true;
break;
case SortProperty.ARTIST:
sortByArtist.selected = true;
break;
case SortProperty.YEAR:
sortByYear.selected = true;
break;
}
playList.sortList(sortField);
refreshList();
}
private function refreshList():void
{
// remember which song was selected
var selectedSong:Song = Song(songList.selectedItem);
// re-assign the song list as the dataprovider to get the newly sorted list
// and force the List control to refresh itself
songList.dataProvider = playList.songList;
// reset the song selection
if (selectedSong != null)
{
songList.selectedItem = selectedSong;
}
}
private function songSelectionChange():void
{
if (songList.selectedIndex != -1)
{
setFormState(SONG_DETAIL);
}
else
{
setFormState(ADD_SONG);
}
}
private function addNewSong():void
{
// gather the values from the form and add the new song
var title:String = newSongTitle.text;
var artist:String = newSongArtist.text;
var year:uint = newSongYear.value;
var filename:String = newSongFilename.text;
var genres:Array = newSongGenres.selectedItems;
playList.addSong(new Song(title, artist, year, filename, genres));
refreshList();
// clear out the "add song" form fields
setFormState(ADD_SONG);
}
private function songListLabel(item:Object):String
{
return item.toString();
}
private function setFormState(state:uint):void
{
// set the form title and control state
switch (state)
{
case ADD_SONG:
formTitle.text = "Add New Song";
// show the submit button
submitSongData.visible = true;
showAddControlsBtn.visible = false;
// clear the form fields
newSongTitle.text = "";
newSongArtist.text = "";
newSongYear.value = (new Date()).fullYear;
newSongFilename.text = "";
newSongGenres.selectedIndex = -1;
// deselect the currently selected song (if any)
songList.selectedIndex = -1;
break;
case SONG_DETAIL:
formTitle.text = "Song Details";
// populate the form with the selected item's data
var selectedSong:Song = Song(songList.selectedItem);
newSongTitle.text = selectedSong.title;
newSongArtist.text = selectedSong.artist;
newSongYear.value = selectedSong.year;
newSongFilename.text = selectedSong.filename;
newSongGenres.selectedItems = selectedSong.genres;
// hide the submit button
submitSongData.visible = false;
showAddControlsBtn.visible = true;
break;
}
}
|
Add type generics to AS3 test file.
|
Add type generics to AS3 test file.
|
ActionScript
|
bsd-2-clause
|
pygments/pygments,dscorbett/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,pygments/pygments,pygments/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,dscorbett/pygments,dscorbett/pygments,pygments/pygments,dscorbett/pygments,pygments/pygments
|
04474d03e6c5a549eb2a8e8e52690cc5519e5948
|
src/aerys/minko/render/shader/compiler/CRC32.as
|
src/aerys/minko/render/shader/compiler/CRC32.as
|
package aerys.minko.render.shader.compiler
{
import flash.utils.ByteArray;
/**
* The CRC32 class provides a set of static methods to create CRC32 values.
* @author promethe
*
*/
public class CRC32
{
private static const POLYNOMIAL : uint = 0x04c11db7;
private static const CRC_TABLE : Vector.<uint> = new Vector.<uint>(256, true);
private static const TMP_BYTEARRAY : ByteArray = new ByteArray();
private static var CRC_TABLE_READY : Boolean = false;
private static function generateCrcTable() : void
{
for (var i : uint = 0; i < 256; ++i)
{
var crcAccum : uint = (i << 24) & 0xffffffff;
for (var j : uint = 0; j < 8; ++j)
{
if (crcAccum & 0x80000000)
crcAccum = (crcAccum << 1) ^ POLYNOMIAL;
else
crcAccum = (crcAccum << 1);
}
CRC_TABLE[i] = crcAccum;
}
CRC_TABLE_READY = true;
}
public static function computeForByteArrayChunk(source : ByteArray, length : uint) : uint
{
if (!CRC_TABLE_READY)
generateCrcTable();
var crcTable : Vector.<uint> = CRC_TABLE;
var crcAccum : uint = uint(-1);
var length1 : uint = (length >> 2) << 2;
var j : uint = 0;
var i : uint;
for (; j < length1; j += 4)
{
var data : uint = source.readUnsignedInt();
i = ((crcAccum >> 24) ^ data) & 0xFF;
crcAccum = (crcAccum << 8) ^ crcTable[i];
data >>>= 8;
i = ((crcAccum >> 24) ^ data) & 0xFF;
crcAccum = (crcAccum << 8) ^ crcTable[i];
data >>>= 8;
i = ((crcAccum >> 24) ^ data) & 0xFF;
crcAccum = (crcAccum << 8) ^ crcTable[i];
data >>>= 8;
i = ((crcAccum >> 24) ^ data) & 0xFF;
crcAccum = (crcAccum << 8) ^ crcTable[i];
data >>>= 8;
}
for (; j < length; ++j)
{
i = ((crcAccum >> 24) ^ source.readUnsignedByte()) & 0xFF;
crcAccum = (crcAccum << 8) ^ crcTable[i];
}
crcAccum = ~crcAccum;
return crcAccum;
}
public static function computeForByteArray(source : ByteArray) : uint
{
source.position = 0;
return computeForByteArrayChunk(source, source.length);
}
public static function computeForString(s : String) : uint
{
TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0;
TMP_BYTEARRAY.writeUTFBytes(s);
return computeForByteArray(TMP_BYTEARRAY);
}
public static function computeForNumberVector(v : Vector.<Number>) : uint
{
var length : uint = v.length;
TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0;
for (var i : uint = 0; i < length; ++i)
TMP_BYTEARRAY.writeDouble(v[i]);
return computeForByteArray(TMP_BYTEARRAY);
}
}
}
|
package aerys.minko.render.shader.compiler
{
import flash.utils.ByteArray;
/**
* The CRC32 class provides a set of static methods to create CRC32 values.
* @author promethe
*
*/
public class CRC32
{
private static const POLYNOMIAL : uint = 0x04c11db7;
private static const CRC_TABLE : Vector.<uint> = new Vector.<uint>(256, true);
private static const TMP_BYTEARRAY : ByteArray = new ByteArray();
private static var CRC_TABLE_READY : Boolean = false;
private static function generateCrcTable() : void
{
for (var i : uint = 0; i < 256; ++i)
{
var crcAccum : uint = (i << 24) & 0xffffffff;
for (var j : uint = 0; j < 8; ++j)
{
if (crcAccum & 0x80000000)
crcAccum = (crcAccum << 1) ^ POLYNOMIAL;
else
crcAccum = (crcAccum << 1);
}
CRC_TABLE[i] = crcAccum;
}
CRC_TABLE_READY = true;
}
public static function computeForByteArrayChunk(source : ByteArray, length : uint) : uint
{
if (!CRC_TABLE_READY)
generateCrcTable();
var crcTable : Vector.<uint> = CRC_TABLE;
var crcAccum : uint = uint(-1);
var length1 : uint = (length >> 2) << 2;
var j : uint = 0;
var i : uint;
for (; j < length1; j += 4)
{
var data : uint = source.readUnsignedInt();
i = ((crcAccum >> 24) ^ data) & 0xFF;
crcAccum = (crcAccum << 8) ^ crcTable[i];
data >>>= 8;
i = ((crcAccum >> 24) ^ data) & 0xFF;
crcAccum = (crcAccum << 8) ^ crcTable[i];
data >>>= 8;
i = ((crcAccum >> 24) ^ data) & 0xFF;
crcAccum = (crcAccum << 8) ^ crcTable[i];
data >>>= 8;
i = ((crcAccum >> 24) ^ data) & 0xFF;
crcAccum = (crcAccum << 8) ^ crcTable[i];
data >>>= 8;
}
for (; j < length; ++j)
{
i = ((crcAccum >> 24) ^ source.readUnsignedByte()) & 0xFF;
crcAccum = (crcAccum << 8) ^ crcTable[i];
}
crcAccum = ~crcAccum;
return crcAccum;
}
public static function computeForByteArray(source : ByteArray) : uint
{
source.position = 0;
return computeForByteArrayChunk(source, source.length);
}
public static function computeForString(s : String) : uint
{
TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0;
TMP_BYTEARRAY.writeUTFBytes(s);
return computeForByteArray(TMP_BYTEARRAY);
}
public static function computeForUintVector(v : Vector.<uint>) : uint
{
var length : uint = v.length;
TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0;
for (var i : uint = 0; i < length; ++i)
TMP_BYTEARRAY.writeUnsignedInt(v[i]);
return computeForByteArray(TMP_BYTEARRAY);
}
public static function computeForNumberVector(v : Vector.<Number>) : uint
{
var length : uint = v.length;
TMP_BYTEARRAY.length = TMP_BYTEARRAY.position = 0;
for (var i : uint = 0; i < length; ++i)
TMP_BYTEARRAY.writeDouble(v[i]);
return computeForByteArray(TMP_BYTEARRAY);
}
}
}
|
Add CRC32 for uint vector
|
Add CRC32 for uint vector
|
ActionScript
|
mit
|
aerys/minko-as3
|
b0cb1a7dfadb834e735de3c007c9c2c3dbe940cf
|
src/com/merlinds/miracle_tool/services/FileSystemService.as
|
src/com/merlinds/miracle_tool/services/FileSystemService.as
|
/**
* User: MerlinDS
* Date: 13.07.2014
* Time: 17:11
*/
package com.merlinds.miracle_tool.services {
import com.merlinds.debug.log;
import com.merlinds.miracle.utils.serializers.MTFSerializer;
import com.merlinds.miracle_tool.events.EditorEvent;
import com.merlinds.miracle_tool.models.AppModel;
import com.merlinds.unitls.structures.QueueFIFO;
import flash.events.Event;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.FileFilter;
import flash.utils.ByteArray;
import org.robotlegs.mvcs.Actor;
public class FileSystemService extends Actor {
public static const PROJECT_EXTENSION:String = ".mtp"; /** Miracle tools project **/
public static const TEXTURE_EXTENSION:String = ".mtf"; /** Miracle texture format **/
public static const ANIMATION_EXTENSION:String = ".maf"; /** Miracle animation format **/
public static const ATF_EXTENSION:String = ".atf"; /** Miracle animation format **/
public static const PNG_EXTENSION:String = ".png"; /** Miracle animation format **/
[Inject]
public var appModel:AppModel;
[Inject]
public var actionService:ActionService;
private var _target:File;
private var _output:ByteArray;
private var _publishBuilder:PublishBuilder;
private var _queue:QueueFIFO;
private var _projectLoader:ProjectLoader;
//==============================================================================
//{region PUBLIC METHODS
public function FileSystemService() {
super();
_queue = new QueueFIFO();
_publishBuilder = new PublishBuilder();
}
public function readSource():void{
log(this, "readSource");
var filters:Array = [
new FileFilter("SWF file", "*.swf"),
new FileFilter("PNG Image file", "*.png"),
new FileFilter("JPG Image file", "*.jpg")
];
this.selectSource("Attach source file to project", filters);
}
public function readAnimation():void{
log(this, "readAnimation");
var filters:Array = [
new FileFilter("FLA file", "*.fla"),
new FileFilter("XML file with animation description", "*.xml")
];
this.selectSource("Attach animation file to project", filters);
}
public function readProject():void{
log(this, "readAnimation");
var filters:Array = [
new FileFilter("FLA file", "*" + PROJECT_EXTENSION)
];
this.selectSource("Open project", filters);
}
public function readProjectSources(sources:Array):void{
if(_projectLoader == null){
_projectLoader = new ProjectLoader(this.projectLoadedCallback);
}
if(sources != null){
_projectLoader.read(sources);
}
}
public function writeProject(name:String, data:Object):void{
log(this, "writeProject", name);
_output = new ByteArray();
//add signature
_output.position = 0;
_output.writeUTFBytes(PROJECT_EXTENSION.substr(1).toUpperCase());
_output.position = 4;
_output.writeObject(data);
name = name + PROJECT_EXTENSION;
_target = this.appModel.lastFileDirection.resolvePath(name);
_target.addEventListener(Event.SELECT, this.selectProjectForSaveHandler);
_target.browseForSave("Save project");
}
public function writeTexture(name:String, png:ByteArray, mesh:ByteArray):void{
log(this, "writeTexture", name);
_queue.push(new SaveHelper(png, PNG_EXTENSION));
name = name + ATF_EXTENSION;
/*//create file
var output:ByteArray = new ByteArray();
//add signature
output.position = 0;
output.writeUTFBytes(TEXTURE_EXTENSION.substr(1).toUpperCase());
output.position = 4;
var meshHeaderBlocks:int = Math.ceil( mesh.length / 512 );
output.writeUnsignedInt( meshHeaderBlocks );
output.position = 8;
output.writeBytes(mesh);
output.position = 8 + meshHeaderBlocks * 512;*/
_queue.push(new SaveHelper(mesh, TEXTURE_EXTENSION));
_target = this.appModel.lastFileDirection.resolvePath(name);
_publishBuilder.createATFFile(png, 0, this.publishBuilderATFHandler);
}
public function writeAnimation(animation:ByteArray):void{
var output:ByteArray = new ByteArray();
//add signature
output.position = 0;
output.writeUTFBytes(ANIMATION_EXTENSION.substr(1).toUpperCase());
output.position = 4;
output.writeBytes(animation);
_queue.push(new SaveHelper(output, ANIMATION_EXTENSION));
}
public function clear():void {
_target = null;
_output.clear();
_output = null;
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function selectSource(title:String, filters:Array = null):void {
_target = this.appModel.lastFileDirection;
_target.addEventListener(Event.SELECT, this.selectSourceHandler);
_target.browseForOpen(title, filters);
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function projectLoadedCallback(event:EditorEvent = null):void {
this.eventDispatcher.removeEventListener(EditorEvent.SOURCE_ATTACHED, this.projectLoadedCallback);
this.eventDispatcher.removeEventListener(EditorEvent.ANIMATION_ATTACHED, this.projectLoadedCallback);
if(_projectLoader.fileHelpers.length > 0){
log(this, "projectLoadedCallback");
var fileHelper:Object = _projectLoader.fileHelpers.shift();
_target = fileHelper.file;
_output = fileHelper.bytes;
this.eventDispatcher.addEventListener(EditorEvent.SOURCE_ATTACHED, this.projectLoadedCallback);
this.eventDispatcher.addEventListener(EditorEvent.ANIMATION_ATTACHED, this.projectLoadedCallback);
this.dispatch(new EditorEvent(EditorEvent.FILE_READ));
}
}
private function selectSourceHandler(event:Event):void {
_target.removeEventListener(event.type, this.selectSourceHandler);
this.appModel.lastFileDirection = _target.parent;
log(this, "selectSourceHandler", _target.name);
//start to download
var fileStream:FileStream = new FileStream();
fileStream.addEventListener(Event.COMPLETE, this.completeReadHandler);
fileStream.openAsync(_target, FileMode.READ);
}
private function completeReadHandler(event:Event):void {
var fileStream:FileStream = event.target as FileStream;
fileStream.removeEventListener(event.type, this.completeReadHandler);
log(this, "completeReadHandler");
_output = new ByteArray();
fileStream.readBytes(_output);
fileStream.close();
this.dispatch(new EditorEvent(EditorEvent.FILE_READ));
}
private function selectProjectForSaveHandler(event:Event):void {
_target.removeEventListener(event.type, this.selectSourceHandler);
this.appModel.lastFileDirection = _target.parent;
log(this, "selectProjectForSaveHandler", _target.name);
var fileStream:FileStream = new FileStream();
fileStream.open(_target, FileMode.WRITE);
fileStream.writeBytes(_output);
fileStream.close();
_output.clear();
_output = null;
if(!_queue.empty){
var saveHelper:SaveHelper = _queue.pop();
_output = saveHelper.bytes;
var name:String = _target.name.substr(0, -4) + saveHelper.ext;
_target = this.appModel.lastFileDirection.resolvePath(name);
_target.addEventListener(Event.SELECT, this.selectProjectForSaveHandler);
_target.browseForSave("Publish animation");
}
log(this, "selectProjectForSaveHandler", "Project Saved");
this.actionService.done();
}
private function publishBuilderATFHandler():void {
_output = new ByteArray();
_output.writeBytes(_publishBuilder.output);
_target.addEventListener(Event.SELECT, this.selectProjectForSaveHandler);
_target.browseForSave("Publish texture");
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
public function get target():File {
return _target;
}
public function get output():ByteArray {
return _output;
}
//} endregion GETTERS/SETTERS ==================================================
}
}
import flash.utils.ByteArray;
class SaveHelper{
public var bytes:ByteArray;
public var ext:String;
public function SaveHelper(bytes:ByteArray, ext:String)
{
this.bytes = bytes;
this.ext = ext;
}
}
|
/**
* User: MerlinDS
* Date: 13.07.2014
* Time: 17:11
*/
package com.merlinds.miracle_tool.services {
import com.merlinds.debug.log;
import com.merlinds.miracle.utils.serializers.MTFSerializer;
import com.merlinds.miracle_tool.events.EditorEvent;
import com.merlinds.miracle_tool.models.AppModel;
import com.merlinds.unitls.structures.QueueFIFO;
import flash.events.Event;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.FileFilter;
import flash.utils.ByteArray;
import org.robotlegs.mvcs.Actor;
public class FileSystemService extends Actor {
public static const PROJECT_EXTENSION:String = ".mtp"; /** Miracle tools project **/
public static const TEXTURE_EXTENSION:String = ".mtf"; /** Miracle texture format **/
public static const ANIMATION_EXTENSION:String = ".maf"; /** Miracle animation format **/
public static const ATF_EXTENSION:String = ".atf"; /** Miracle animation format **/
public static const PNG_EXTENSION:String = ".png"; /** Miracle animation format **/
[Inject]
public var appModel:AppModel;
[Inject]
public var actionService:ActionService;
private var _target:File;
private var _output:ByteArray;
private var _publishBuilder:PublishBuilder;
private var _queue:QueueFIFO;
private var _projectLoader:ProjectLoader;
//==============================================================================
//{region PUBLIC METHODS
public function FileSystemService() {
super();
_queue = new QueueFIFO();
_publishBuilder = new PublishBuilder();
}
public function readSource():void{
log(this, "readSource");
var filters:Array = [
new FileFilter("SWF file", "*.swf"),
new FileFilter("PNG Image file", "*.png"),
new FileFilter("JPG Image file", "*.jpg")
];
this.selectSource("Attach source file to project", filters);
}
public function readAnimation():void{
log(this, "readAnimation");
var filters:Array = [
new FileFilter("FLA file", "*.fla"),
new FileFilter("XML file with animation description", "*.xml")
];
this.selectSource("Attach animation file to project", filters);
}
public function readProject():void{
log(this, "readAnimation");
var filters:Array = [
new FileFilter("FLA file", "*" + PROJECT_EXTENSION)
];
this.selectSource("Open project", filters);
}
public function readProjectSources(sources:Array):void{
if(_projectLoader == null){
_projectLoader = new ProjectLoader(this.projectLoadedCallback);
}
if(sources != null){
_projectLoader.read(sources);
}
}
public function writeProject(name:String, data:Object):void{
log(this, "writeProject", name);
_output = new ByteArray();
//add signature
_output.position = 0;
_output.writeUTFBytes(PROJECT_EXTENSION.substr(1).toUpperCase());
_output.position = 4;
_output.writeObject(data);
name = name + PROJECT_EXTENSION;
_target = this.appModel.lastFileDirection.resolvePath(name);
_target.addEventListener(Event.SELECT, this.selectProjectForSaveHandler);
_target.browseForSave("Save project");
}
public function writeTexture(name:String, png:ByteArray, mesh:ByteArray):void{
log(this, "writeTexture", name);
_queue.push(new SaveHelper(png, PNG_EXTENSION));
_queue.push(new SaveHelper(mesh, TEXTURE_EXTENSION));
_target = this.appModel.lastFileDirection.resolvePath(name + ATF_EXTENSION);
_publishBuilder.createATFFile(png, 0, this.publishBuilderATFHandler);
}
public function writeAnimation(animation:ByteArray):void{
var output:ByteArray = new ByteArray();
//add signature
output.position = 0;
output.writeUTFBytes(ANIMATION_EXTENSION.substr(1).toUpperCase());
output.position = 4;
output.writeBytes(animation);
_queue.push(new SaveHelper(output, ANIMATION_EXTENSION));
}
public function clear():void {
_target = null;
_output.clear();
_output = null;
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function selectSource(title:String, filters:Array = null):void {
_target = this.appModel.lastFileDirection;
_target.addEventListener(Event.SELECT, this.selectSourceHandler);
_target.browseForOpen(title, filters);
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function projectLoadedCallback(event:EditorEvent = null):void {
this.eventDispatcher.removeEventListener(EditorEvent.SOURCE_ATTACHED, this.projectLoadedCallback);
this.eventDispatcher.removeEventListener(EditorEvent.ANIMATION_ATTACHED, this.projectLoadedCallback);
if(_projectLoader.fileHelpers.length > 0){
log(this, "projectLoadedCallback");
var fileHelper:Object = _projectLoader.fileHelpers.shift();
_target = fileHelper.file;
_output = fileHelper.bytes;
this.eventDispatcher.addEventListener(EditorEvent.SOURCE_ATTACHED, this.projectLoadedCallback);
this.eventDispatcher.addEventListener(EditorEvent.ANIMATION_ATTACHED, this.projectLoadedCallback);
this.dispatch(new EditorEvent(EditorEvent.FILE_READ));
}
}
private function selectSourceHandler(event:Event):void {
_target.removeEventListener(event.type, this.selectSourceHandler);
this.appModel.lastFileDirection = _target.parent;
log(this, "selectSourceHandler", _target.name);
//start to download
var fileStream:FileStream = new FileStream();
fileStream.addEventListener(Event.COMPLETE, this.completeReadHandler);
fileStream.openAsync(_target, FileMode.READ);
}
private function completeReadHandler(event:Event):void {
var fileStream:FileStream = event.target as FileStream;
fileStream.removeEventListener(event.type, this.completeReadHandler);
log(this, "completeReadHandler");
_output = new ByteArray();
fileStream.readBytes(_output);
fileStream.close();
this.dispatch(new EditorEvent(EditorEvent.FILE_READ));
}
private function selectProjectForSaveHandler(event:Event):void {
_target.removeEventListener(event.type, this.selectSourceHandler);
this.appModel.lastFileDirection = _target.parent;
log(this, "selectProjectForSaveHandler", _target.name);
var fileStream:FileStream = new FileStream();
fileStream.open(_target, FileMode.WRITE);
fileStream.writeBytes(_output);
fileStream.close();
_output.clear();
_output = null;
if(!_queue.empty){
var saveHelper:SaveHelper = _queue.pop();
_output = saveHelper.bytes;
var name:String = _target.name.substr(0, -4) + saveHelper.ext;
_target = this.appModel.lastFileDirection.resolvePath(name);
_target.addEventListener(Event.SELECT, this.selectProjectForSaveHandler);
_target.browseForSave("Publish animation");
}
log(this, "selectProjectForSaveHandler", "Project Saved");
this.actionService.done();
}
private function publishBuilderATFHandler():void {
_output = new ByteArray();
_output.writeBytes(_publishBuilder.output);
_target.addEventListener(Event.SELECT, this.selectProjectForSaveHandler);
_target.browseForSave("Publish texture");
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
public function get target():File {
return _target;
}
public function get output():ByteArray {
return _output;
}
//} endregion GETTERS/SETTERS ==================================================
}
}
import flash.utils.ByteArray;
class SaveHelper{
public var bytes:ByteArray;
public var ext:String;
public function SaveHelper(bytes:ByteArray, ext:String)
{
this.bytes = bytes;
this.ext = ext;
}
}
|
Remove old code
|
Remove old code
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
e96a05f808b8423de589b66363062332191aea87
|
src/main/actionscript/com/castlabs/dash/descriptors/index/SegmentTimeline.as
|
src/main/actionscript/com/castlabs/dash/descriptors/index/SegmentTimeline.as
|
/*
* Copyright (c) 2014 castLabs GmbH
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.castlabs.dash.descriptors.index {
import com.castlabs.dash.DashContext;
import com.castlabs.dash.descriptors.segments.Segment;
public class SegmentTimeline extends SegmentTemplate implements SegmentIndex {
private var _segments:Vector.<Object> = new Vector.<Object>();
public function SegmentTimeline(context:DashContext, representation:XML) {
super(context, representation);
update(representation);
}
public override function getSegment(timestamp:Number, representationId:String, bandwidth:Number, baseUrl:String,
duration:Number, internalRepresentationId:Number):Segment {
if (_segments.length == 0) {
return null;
}
if (_live && isLast(timestamp)) {
return _context.buildWaitSegment(internalRepresentationId);
}
var segment:Object = null;
//TODO simplify this condition
if (timestamp == 0) {
if (_live) {
var last:Object = _segments[_segments.length - 1];
timestamp = seconds(last.time + last.duration) - _minBufferTime;
segment = findSegment(timestamp);
} else {
segment = _segments[0];
}
} else {
segment = findSegment(timestamp);
}
if (segment == null) {
return null;
}
var url:String = String(_segmentFilename);
url = url.replace("$Time$", segment.time);
url = url.replace("$RepresentationID$", representationId);
var startTimestamp:Number = seconds(segment.time);
var endTimestamp:Number = startTimestamp + seconds(segment.duration);
return _context.buildMediaDataSegment(internalRepresentationId, baseUrl + url, "0-", startTimestamp,
endTimestamp);
}
private function findSegment(timestamp:Number):Object {
for (var i:uint = 0; i < _segments.length; i++) {
var end:Number = seconds(_segments[i].time) + seconds(_segments[i].duration);
if (timestamp < end) {
return _segments[i];
}
}
return null;
}
public override function update(representation:XML):void {
super.update(representation);
if (_live) {
removeOutdatedSegments();
}
appendNewSegments(representation);
}
private function appendNewSegments(xml:XML):void {
var items:XMLList = traverseAndBuildTimeline(xml);
var time:Number = 0;
for (var i:uint = 0; i < items.length(); i++) {
// read time if present
if (items[i].hasOwnProperty("@t")) {
time = Number(items[i][email protected]());
}
// read duration
var duration:Number = Number(items[i][email protected]());
// read repeats if present
var repeats:Number = 0;
if (items[i].hasOwnProperty("@r")) {
repeats = Number(items[i][email protected]());
}
// add duplicates if repeats > 0
for (var j:uint = 0; j <= repeats; j++) {
if (!isTimeExists(time)) { // unique
_segments.push({ time: time, duration: duration});
}
time += duration;
}
}
}
private function isTimeExists(time:Number):Object {
for (var i:uint = 0; i < _segments.length; i++) {
if (time == _segments[i].time) {
return true;
}
}
return false;
}
private function removeOutdatedSegments():void {
while (seconds(calculateBufferDepth()) > _timeShiftBuffer) {
_segments.shift();
}
}
private function calculateBufferDepth():Number {
var sum:uint = 0;
for each (var segment:Object in _segments) {
sum += segment.duration;
}
return sum;
}
private function seconds(value:Number):Number {
return value / _timescale;
}
private function isLast(timestmap:Number):Boolean {
if (_segments.length == 0) {
return false;
}
var last:uint = _segments.length - 1;
// #31 workaround for rounding issue; TODO solve this issue more elegant
return (seconds(_segments[last].time) - timestmap) < 0.1;
}
private function traverseAndBuildTimeline(node:XML):XMLList {
if (node == null) {
throw _context.console.logAndBuildError("Couldn't find any S tag");
}
if (node.SegmentTemplate.length() == 1
&& node.SegmentTemplate.SegmentTimeline.length() == 1
&& node.SegmentTemplate.SegmentTimeline.S.length() > 0) {
return node.SegmentTemplate.SegmentTimeline.S;
}
// go up one level in hierarchy, e.g. adaptionSet and period
return traverseAndBuildTimeline(node.parent());
}
protected override function traverseAndBuildDuration(node:XML):Number {
return NaN;
}
protected override function traverseAndBuildStartNumber(node:XML):Number {
return NaN;
}
override public function toString():String {
var a:String = "isLive='" + _live;
var b:String = "";
var c:String = "', segmentsCount='" + _segments.length + "'";
if (_live) {
b = ", minBufferTime[s]='" + _minBufferTime + ", timeShiftBuffer[s]='" + _timeShiftBuffer;
}
return a + b + c;
}
}
}
|
/*
* Copyright (c) 2014 castLabs GmbH
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.castlabs.dash.descriptors.index {
import com.castlabs.dash.DashContext;
import com.castlabs.dash.descriptors.segments.Segment;
public class SegmentTimeline extends SegmentTemplate implements SegmentIndex {
private var _segments:Vector.<Object> = new Vector.<Object>();
public function SegmentTimeline(context:DashContext, representation:XML) {
super(context, representation);
update(representation);
}
public override function getSegment(timestamp:Number, representationId:String, bandwidth:Number, baseUrl:String,
duration:Number, internalRepresentationId:Number):Segment {
if (_segments.length == 0) {
return null;
}
if (_live && isLast(timestamp)) {
return _context.buildWaitSegment(internalRepresentationId);
}
var segment:Object = null;
//TODO simplify this condition
if (timestamp == 0) {
if (_live) {
var last:Object = _segments[_segments.length - 1];
timestamp = seconds(last.time + last.duration) - _minBufferTime;
segment = findSegment(timestamp);
} else {
segment = _segments[0];
}
} else {
segment = findSegment(timestamp);
}
if (segment == null) {
return null;
}
var url:String = String(_segmentFilename);
url = url.replace("$Time$", segment.time);
url = url.replace("$Number$", segment.num);
url = url.replace("$RepresentationID$", representationId);
var startTimestamp:Number = seconds(segment.time);
var endTimestamp:Number = startTimestamp + seconds(segment.duration);
return _context.buildMediaDataSegment(internalRepresentationId, baseUrl + url, "0-", startTimestamp,
endTimestamp);
}
private function findSegment(timestamp:Number):Object {
for (var i:uint = 0; i < _segments.length; i++) {
var end:Number = seconds(_segments[i].time) + seconds(_segments[i].duration);
if (timestamp < end) {
return _segments[i];
}
}
return null;
}
public override function update(representation:XML):void {
super.update(representation);
if (_live) {
removeOutdatedSegments();
}
appendNewSegments(representation);
}
private function appendNewSegments(xml:XML):void {
var items:XMLList = traverseAndBuildTimeline(xml);
var time:Number = 0;
var num:Number = _startNumber;
for (var i:uint = 0; i < items.length(); i++) {
// read time if present
if (items[i].hasOwnProperty("@t")) {
time = Number(items[i][email protected]());
}
// read duration
var duration:Number = Number(items[i][email protected]());
// read repeats if present
var repeats:Number = 0;
if (items[i].hasOwnProperty("@r")) {
repeats = Number(items[i][email protected]());
}
// add duplicates if repeats > 0
for (var j:uint = 0; j <= repeats; j++) {
if (!isTimeExists(time)) { // unique
_segments.push({ time: time, duration: duration, num: num});
}
time += duration;
num++;
}
}
}
private function isTimeExists(time:Number):Object {
for (var i:uint = 0; i < _segments.length; i++) {
if (time == _segments[i].time) {
return true;
}
}
return false;
}
private function removeOutdatedSegments():void {
while (seconds(calculateBufferDepth()) > _timeShiftBuffer) {
_segments.shift();
}
}
private function calculateBufferDepth():Number {
var sum:uint = 0;
for each (var segment:Object in _segments) {
sum += segment.duration;
}
return sum;
}
private function seconds(value:Number):Number {
return value / _timescale;
}
private function isLast(timestmap:Number):Boolean {
if (_segments.length == 0) {
return false;
}
var last:uint = _segments.length - 1;
// #31 workaround for rounding issue; TODO solve this issue more elegant
return (seconds(_segments[last].time) - timestmap) < 0.1;
}
private function traverseAndBuildTimeline(node:XML):XMLList {
if (node == null) {
throw _context.console.logAndBuildError("Couldn't find any S tag");
}
if (node.SegmentTemplate.length() == 1
&& node.SegmentTemplate.SegmentTimeline.length() == 1
&& node.SegmentTemplate.SegmentTimeline.S.length() > 0) {
return node.SegmentTemplate.SegmentTimeline.S;
}
// go up one level in hierarchy, e.g. adaptionSet and period
return traverseAndBuildTimeline(node.parent());
}
protected override function traverseAndBuildDuration(node:XML):Number {
return NaN;
}
override public function toString():String {
var a:String = "isLive='" + _live;
var b:String = "";
var c:String = "', segmentsCount='" + _segments.length + "'";
if (_live) {
b = ", minBufferTime[s]='" + _minBufferTime + ", timeShiftBuffer[s]='" + _timeShiftBuffer;
}
return a + b + c;
}
}
}
|
Allow to use $Number$ with SegmentTimeline
|
Allow to use $Number$ with SegmentTimeline
|
ActionScript
|
mpl-2.0
|
castlabs/dashas,castlabs/dashas,castlabs/dashas
|
1e2295dd09d67a4556aad1f44714de818a95ccdb
|
src/as/com/threerings/presents/net/AuthRequest.as
|
src/as/com/threerings/presents/net/AuthRequest.as
|
//
// $Id$
package com.threerings.presents.net {
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.TypedArray;
import com.threerings.util.StringUtil;
public class AuthRequest extends UpstreamMessage
{
public function AuthRequest (creds :Credentials, version :String, bootGroups :Array)
{
_creds = creds;
_version = version;
_bootGroups = new TypedArray("[Ljava.lang.String;");
_bootGroups.addAll(bootGroups);
// magic up a timezone in the format "GMT+XX:XX"
// Of course, the sign returned from getTimezoneOffset() is wrong
var minsOffset :int = -1 * new Date().getTimezoneOffset();
var hoursFromUTC :int = Math.abs(minsOffset) / 60;
var minsFromUTC :int = Math.abs(minsOffset) % 60;
_zone = "GMT" + ((minsOffset < 0) ? "-" : "+") +
StringUtil.prepad(String(hoursFromUTC), 2, "0") + ":" +
StringUtil.prepad(String(minsFromUTC), 2, "0");
}
// documentation inherited
override public function writeObject (out :ObjectOutputStream) :void
{
super.writeObject(out);
out.writeObject(_creds);
out.writeField(_version);
out.writeField(_zone);
out.writeObject(_bootGroups);
}
protected var _creds :Credentials;
protected var _version :String;
protected var _zone :String;
protected var _bootGroups :TypedArray;
}
}
|
//
// $Id$
package com.threerings.presents.net {
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.TypedArray;
import com.threerings.util.StringUtil;
public class AuthRequest extends UpstreamMessage
{
public function AuthRequest (creds :Credentials, version :String, bootGroups :Array)
{
_creds = creds;
_version = version;
_bootGroups = TypedArray.create(String);
_bootGroups.addAll(bootGroups);
// magic up a timezone in the format "GMT+XX:XX"
// Of course, the sign returned from getTimezoneOffset() is wrong
var minsOffset :int = -1 * new Date().getTimezoneOffset();
var hoursFromUTC :int = Math.abs(minsOffset) / 60;
var minsFromUTC :int = Math.abs(minsOffset) % 60;
_zone = "GMT" + ((minsOffset < 0) ? "-" : "+") +
StringUtil.prepad(String(hoursFromUTC), 2, "0") + ":" +
StringUtil.prepad(String(minsFromUTC), 2, "0");
}
// documentation inherited
override public function writeObject (out :ObjectOutputStream) :void
{
super.writeObject(out);
out.writeObject(_creds);
out.writeField(_version);
out.writeField(_zone);
out.writeObject(_bootGroups);
}
protected var _creds :Credentials;
protected var _version :String;
protected var _zone :String;
protected var _bootGroups :TypedArray;
}
}
|
Use cleaner TypedArray factory method.
|
Use cleaner TypedArray factory method.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4566 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
b964f68fa8a8ffd577dab7c167d0b666d17877a9
|
src/com/ryanberdeen/echonest/api/v4/ApiSupport.as
|
src/com/ryanberdeen/echonest/api/v4/ApiSupport.as
|
/*
* Copyright 2011 Ryan Berdeen. All rights reserved.
* Distributed under the terms of the MIT License.
* See accompanying file LICENSE.txt
*/
package com.ryanberdeen.echonest.api.v4 {
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLVariables;
import com.adobe.serialization.json.JSON;
/**
* Base class for Echo Nest API classes.
*/
public class ApiSupport {
public static const API_VERSION:int = 3;
/**
* @private
*/
protected var _baseUrl:String = 'http://developer.echonest.com/api/v4/';
public var apiKey:String;
/**
* Creates a request for an Echo Nest API method call with a set of
* parameters.
*
* @param method The method to call.
* @param parameters The parameters to include in the request.
*
* @return The request to use to call the method.
*/
public function createRequest(method:String, parameters:Object):URLRequest {
var variables:URLVariables = new URLVariables;
variables.api_key = apiKey;
for (var name:String in parameters) {
variables[name] = parameters[name];
}
var request:URLRequest = new URLRequest();
request.url = _baseUrl + method;
request.data = variables;
return request;
}
/**
* Creates a loader with event listeners.
*
* <p>The following options are supported:</p>
*
* <table><thead><tr><th>Option</th><th>Event</th></tr></thead><tbody>
* <tr>
* <td>onComplete</td>
* <td><code>Event.COMPLETE</code></td>
* </tr>
* <tr>
* <td>onResponse</td>
* <td>Called with the processed response.</td>
* </tr>
* <tr>
* <td>onEchoNestError</td>
* <td>Called with an <code>EchoNestError</code> if the status code is nonzero</td>
* </tr>
* <tr>
* <td>onProgress</td>
* <td><code>ProgressEvent.PROGRESS</code></td>
* </tr>
* <tr>
* <td>onSecurityError</td>
* <td><code>SecurityErrorEvent.SECURITY_ERROR</code></td>
* </tr>
* <tr>
* <td>onIoError</td>
* <td><code>IOErrorEvent.IO_ERROR</code></td>
* </tr>
* <tr>
* <td>onError</td>
* <td><code>IOErrorEvent.IO_ERROR</code><br/> <code>SecurityErrorEvent.SECURITY_ERROR</code></td>
* </tr>
* <tr>
* <td>onHttpStatus</td>
* <td><code>HTTPStatusEvent.HTTP_STATUS</code></td>
* </tr>
* </tbody></table>
*
* @param options The event listener options for the loader.
* @param responseProcessor The function that processes the XML response.
* @param responseProcessorArgs The arguments to pass to the response
* processor function.
*/
public function createLoader(options:Object, responseProcessor:Function, ...responseProcessorArgs):URLLoader {
var loader:URLLoader = new URLLoader();
if (options.onComplete) {
loader.addEventListener(Event.COMPLETE, options.onComplete);
}
if (options.onResponse) {
loader.addEventListener(Event.COMPLETE, function(e:Event):void {
try {
var parsedResponse:Object = parseRawResponse(loader.data);
responseProcessorArgs.push(parsedResponse);
var response:Object = responseProcessor.apply(responseProcessor, responseProcessorArgs);
if (options.onResponseArgument) {
options.onResponse(options.onResponseArgument, response);
}
else {
options.onResponse(response);
}
}
catch (e:EchoNestError) {
if (options.onEchoNestError) {
options.onEchoNestError(e);
}
}
});
}
addEventListeners(options, loader);
return loader;
}
protected function parseRawResponse(data:String):Object {
var responseObject:* = JSON.decode(data).response;
checkStatus(responseObject);
return responseObject;
}
/**
* Adds the standard Echo Nest Flash API event listeners to the event
* dispatcher.
*
* <p>The event dispatcher should be either a <code>URLLoader</code> or a
* <code>FileReference</code>.</p>
*
* <p>This method does not add the <code>onComplete</code> or
* <code>onResponse</code> event listeners. They are added by
* <code>createLoader()</code>.</p>
*
* @private
*
* @param options The event listener options. See
* <code>createLoader()</code> for the list of available options.
* @param dispatcher The event dispatcher to add the event listeners to.
*/
protected function addEventListeners(options:Object, dispatcher:EventDispatcher):void {
if (options.onProgress) {
dispatcher.addEventListener(ProgressEvent.PROGRESS, options.onProgress);
}
if (options.onSecurityError) {
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, options.onSecurityError);
}
if (options.onIoError) {
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, options.onIoError);
}
if (options.onError) {
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, options.onError);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, options.onError);
}
if (options.onHttpStatus) {
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, options.onHttpStatus);
}
}
/**
* Throws an <code>EchoNestError</code> if the status indicates an error.
*
* @param The XML result of an Echo Nest API call.
*
* @throws EchoNestError When the status code is nonzero.
*/
public function checkStatus(response:Object):void {
if (response.status.code != 0) {
throw new EchoNestError(response.status.code, response.status.message);
}
}
}
}
|
/*
* Copyright 2011 Ryan Berdeen. All rights reserved.
* Distributed under the terms of the MIT License.
* See accompanying file LICENSE.txt
*/
package com.ryanberdeen.echonest.api.v4 {
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLVariables;
import com.adobe.serialization.json.JSON;
/**
* Base class for Echo Nest API classes.
*/
public class ApiSupport {
/**
* @private
*/
protected var _baseUrl:String = 'http://developer.echonest.com/api/v4/';
public var apiKey:String;
/**
* Creates a request for an Echo Nest API method call with a set of
* parameters.
*
* @param method The method to call.
* @param parameters The parameters to include in the request.
*
* @return The request to use to call the method.
*/
public function createRequest(method:String, parameters:Object):URLRequest {
var variables:URLVariables = new URLVariables;
variables.api_key = apiKey;
for (var name:String in parameters) {
variables[name] = parameters[name];
}
var request:URLRequest = new URLRequest();
request.url = _baseUrl + method;
request.data = variables;
return request;
}
/**
* Creates a loader with event listeners.
*
* <p>The following options are supported:</p>
*
* <table><thead><tr><th>Option</th><th>Event</th></tr></thead><tbody>
* <tr>
* <td>onComplete</td>
* <td><code>Event.COMPLETE</code></td>
* </tr>
* <tr>
* <td>onResponse</td>
* <td>Called with the processed response.</td>
* </tr>
* <tr>
* <td>onEchoNestError</td>
* <td>Called with an <code>EchoNestError</code> if the status code is nonzero</td>
* </tr>
* <tr>
* <td>onProgress</td>
* <td><code>ProgressEvent.PROGRESS</code></td>
* </tr>
* <tr>
* <td>onSecurityError</td>
* <td><code>SecurityErrorEvent.SECURITY_ERROR</code></td>
* </tr>
* <tr>
* <td>onIoError</td>
* <td><code>IOErrorEvent.IO_ERROR</code></td>
* </tr>
* <tr>
* <td>onError</td>
* <td><code>IOErrorEvent.IO_ERROR</code><br/> <code>SecurityErrorEvent.SECURITY_ERROR</code></td>
* </tr>
* <tr>
* <td>onHttpStatus</td>
* <td><code>HTTPStatusEvent.HTTP_STATUS</code></td>
* </tr>
* </tbody></table>
*
* @param options The event listener options for the loader.
* @param responseProcessor The function that processes the XML response.
* @param responseProcessorArgs The arguments to pass to the response
* processor function.
*/
public function createLoader(options:Object, responseProcessor:Function, ...responseProcessorArgs):URLLoader {
var loader:URLLoader = new URLLoader();
if (options.onComplete) {
loader.addEventListener(Event.COMPLETE, options.onComplete);
}
if (options.onResponse) {
loader.addEventListener(Event.COMPLETE, function(e:Event):void {
try {
var parsedResponse:Object = parseRawResponse(loader.data);
responseProcessorArgs.push(parsedResponse);
var response:Object = responseProcessor.apply(responseProcessor, responseProcessorArgs);
if (options.onResponseArgument) {
options.onResponse(options.onResponseArgument, response);
}
else {
options.onResponse(response);
}
}
catch (e:EchoNestError) {
if (options.onEchoNestError) {
options.onEchoNestError(e);
}
}
});
}
addEventListeners(options, loader);
return loader;
}
protected function parseRawResponse(data:String):Object {
var responseObject:* = JSON.decode(data).response;
checkStatus(responseObject);
return responseObject;
}
/**
* Adds the standard Echo Nest Flash API event listeners to the event
* dispatcher.
*
* <p>The event dispatcher should be either a <code>URLLoader</code> or a
* <code>FileReference</code>.</p>
*
* <p>This method does not add the <code>onComplete</code> or
* <code>onResponse</code> event listeners. They are added by
* <code>createLoader()</code>.</p>
*
* @private
*
* @param options The event listener options. See
* <code>createLoader()</code> for the list of available options.
* @param dispatcher The event dispatcher to add the event listeners to.
*/
protected function addEventListeners(options:Object, dispatcher:EventDispatcher):void {
if (options.onProgress) {
dispatcher.addEventListener(ProgressEvent.PROGRESS, options.onProgress);
}
if (options.onSecurityError) {
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, options.onSecurityError);
}
if (options.onIoError) {
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, options.onIoError);
}
if (options.onError) {
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, options.onError);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, options.onError);
}
if (options.onHttpStatus) {
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, options.onHttpStatus);
}
}
/**
* Throws an <code>EchoNestError</code> if the status indicates an error.
*
* @param The XML result of an Echo Nest API call.
*
* @throws EchoNestError When the status code is nonzero.
*/
public function checkStatus(response:Object):void {
if (response.status.code != 0) {
throw new EchoNestError(response.status.code, response.status.message);
}
}
}
}
|
remove outdated version constant
|
remove outdated version constant
|
ActionScript
|
mit
|
also/echo-nest-flash-api
|
3710af06aa89758e1f9032d0ccf3c31a659aeeb0
|
src/com/google/analytics/components/FlashTracker.as
|
src/com/google/analytics/components/FlashTracker.as
|
package com.google.analytics.components
{
import com.google.analytics.API;
import com.google.analytics.AnalyticsTracker;
import com.google.analytics.core.Buffer;
import com.google.analytics.core.EventTracker;
import com.google.analytics.core.GIFRequest;
import com.google.analytics.core.ServerOperationMode;
import com.google.analytics.core.TrackerMode;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.Layout;
import com.google.analytics.external.AdSenseGlobals;
import com.google.analytics.external.HTMLDOM;
import com.google.analytics.external.JavascriptProxy;
import com.google.analytics.utils.Environment;
import com.google.analytics.utils.Version;
import com.google.analytics.v4.Bridge;
import com.google.analytics.v4.Configuration;
import com.google.analytics.v4.GoogleAnalyticsAPI;
import com.google.analytics.v4.Tracker;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.getQualifiedClassName;
EventTracker;
ServerOperationMode;
/**
* The Flash visual component.
*/
[IconFile("analytics.png")]
public class FlashTracker extends Sprite implements AnalyticsTracker
{
private var _display:DisplayObject;
private var _tracker:GoogleAnalyticsAPI;
//factory
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _env:Environment;
private var _buffer:Buffer;
private var _gifRequest:GIFRequest;
private var _jsproxy:JavascriptProxy;
private var _dom:HTMLDOM;
private var _adSense:AdSenseGlobals;
//component properties
private var _account:String = "";
private var _mode:String = "AS3";
private var _visualDebug:Boolean = false;
//component
private var _componentInspectorSetting:Boolean;
private var isLivePreview:Boolean;
private var livePreviewWidth:Number;
private var livePreviewHeight:Number;
private var preview:MovieClip;
private var _width:Number = 0;
private var _height:Number = 0;
public var boundingBox_mc:DisplayObject;
public static var version:Version = API.version;
[IconFile("analytics.png")]
public function FlashTracker()
{
super();
isLivePreview = (parent != null && getQualifiedClassName(parent) == "fl.livepreview::LivePreviewParent");
_componentInspectorSetting = false;
boundingBox_mc.visible = false;
removeChild( boundingBox_mc );
boundingBox_mc = null;
if( isLivePreview )
{
_createLivePreview();
}
/* note:
we have to use the ENTER_FRAME event
to wait 1 frame so we can add to the display list
and get the values declared in the component inspector.
*/
addEventListener( Event.ENTER_FRAME, _factory );
}
private function _createLivePreview():void
{
preview = new MovieClip();
var g:Graphics = preview.graphics;
g.beginFill(0x000000);
g.moveTo(0, 0);
g.lineTo(0, 100);
g.lineTo(100, 100);
g.lineTo(100, 0);
g.lineTo(0, 0);
g.endFill();
//decalred in the FLA
// preview.icon_mc = new Icon();
// preview.icon_mc.name = "icon_mc";
// preview.addChild(preview.icon_mc);
addChild( preview );
}
public function set componentInspectorSetting( value:Boolean ):void
{
_componentInspectorSetting = value;
}
public function setSize( w:Number, h:Number ):void
{
}
/**
* @private
* Factory to build the different trackers
*/
private function _factory( event:Event ):void
{
if( isLivePreview )
{
return;
}
removeEventListener( Event.ENTER_FRAME, _factory );
_display = this;
if( !debug )
{
this.debug = new DebugConfiguration();
}
if( !config )
{
this.config = new Configuration( debug );
}
if( visualDebug )
{
debug.layout = new Layout( debug, _display );
debug.active = visualDebug;
}
_jsproxy = new JavascriptProxy( debug );
switch( mode )
{
case TrackerMode.BRIDGE :
{
_tracker = _bridgeFactory();
break;
}
case TrackerMode.AS3 :
default:
{
_tracker = _trackerFactory();
}
}
}
/**
* @private
* Factory method for returning a Tracker object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _trackerFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (AS3) v" + version +"\naccount: " + account );
_adSense = new AdSenseGlobals( debug );
_dom = new HTMLDOM( debug );
_dom.cacheProperties();
_env = new Environment( "", "", "", debug, _dom );
_buffer = new Buffer( config, debug, false );
_gifRequest = new GIFRequest( config, debug, _buffer, _env );
use namespace ga_internal;
_env.url = _display.stage.loaderInfo.url;
return new Tracker( account, config, debug, _env, _buffer, _gifRequest, _adSense );
}
/**
* @private
* Factory method for returning a Bridge object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _bridgeFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (Bridge) v" + version +"\naccount: " + account );
return new Bridge( account, _debug, _jsproxy );
}
/**
* Indicates the account value of the tracking.
*/
[Inspectable]
public function get account():String
{
return _account ;
}
/**
* @private
*/
public function set account(value:String):void
{
_account = value;
}
public function get config():Configuration
{
return _config;
}
public function set config(value:Configuration):void
{
_config = value;
}
public function get debug():DebugConfiguration
{
return _debug;
}
public function set debug(value:DebugConfiguration):void
{
_debug = value;
}
[Inspectable(defaultValue="AS3", enumeration="AS3,Bridge", type="String")]
public function get mode():String
{
return _mode;
}
/**
* @private
*/
public function set mode( value:String ):void
{
_mode = value;
}
/**
* Indicates if the tracker use a visual debug.
*/
[Inspectable(defaultValue="false", type="Boolean")]
public function get visualDebug():Boolean
{
return _visualDebug;
}
/**
* @private
*/
public function set visualDebug( value:Boolean ):void
{
_visualDebug = value;
}
include "../common.txt"
}
}
|
package com.google.analytics.components
{
import com.google.analytics.API;
import com.google.analytics.AnalyticsTracker;
import com.google.analytics.core.Buffer;
import com.google.analytics.core.EventTracker;
import com.google.analytics.core.GIFRequest;
import com.google.analytics.core.ServerOperationMode;
import com.google.analytics.core.TrackerMode;
import com.google.analytics.core.ga_internal;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.Layout;
import com.google.analytics.external.AdSenseGlobals;
import com.google.analytics.external.HTMLDOM;
import com.google.analytics.external.JavascriptProxy;
import com.google.analytics.utils.Environment;
import com.google.analytics.utils.Version;
import com.google.analytics.v4.Bridge;
import com.google.analytics.v4.Configuration;
import com.google.analytics.v4.GoogleAnalyticsAPI;
import com.google.analytics.v4.Tracker;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.getQualifiedClassName;
import flash.utils.getDefinitionByName;
/* force import for type in the includes */
EventTracker;
ServerOperationMode;
/**
* The Flash visual component.
*/
[IconFile("analytics.png")]
public class FlashTracker extends Sprite implements AnalyticsTracker
{
private var _display:DisplayObject;
private var _tracker:GoogleAnalyticsAPI;
//factory
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _env:Environment;
private var _buffer:Buffer;
private var _gifRequest:GIFRequest;
private var _jsproxy:JavascriptProxy;
private var _dom:HTMLDOM;
private var _adSense:AdSenseGlobals;
//component properties
private var _account:String = "";
private var _mode:String = "AS3";
private var _visualDebug:Boolean = false;
//component
protected var preview:MovieClip;
protected var isLivePreview:Boolean;
protected var livePreviewWidth:Number;
protected var livePreviewHeight:Number;
protected var _width:Number = 100;
protected var _height:Number = 122;
protected var _componentInspectorSetting:Boolean;
public var boundingBox_mc:DisplayObject;
public static var version:Version = API.version;
[IconFile("analytics.png")]
public function FlashTracker()
{
super();
isLivePreview = _checkLivePreview();
_componentInspectorSetting = false;
boundingBox_mc.visible = false;
removeChild( boundingBox_mc );
boundingBox_mc = null;
if( isLivePreview )
{
_createLivePreview();
}
/* note:
we have to use the ENTER_FRAME event
to wait 1 frame so we can add to the display list
and get the values declared in the component inspector.
*/
addEventListener( Event.ENTER_FRAME, _factory );
}
private function _checkLivePreview():Boolean
{
if( parent != null && (getQualifiedClassName(parent) == "fl.livepreview::LivePreviewParent"))
{
return true;
}
return false;
}
private function _createLivePreview():void
{
preview = new MovieClip();
var g:Graphics = preview.graphics;
g.beginFill(0xffffff);
g.moveTo(0, 0);
g.lineTo(0, _width);
g.lineTo(_width, _height);
g.lineTo(_height, 0);
g.lineTo(0, 0);
g.endFill();
/* note:
because the Icon class is declared in the FLA
and the FLA generate it automatically
we need to use reflection to instanciate it
so compc/asdoc does not generate errors
*/
var iconClass:Class = getDefinitionByName( "com.google.analytics.components::Icon" ) as Class;
preview.icon_mc = new iconClass();
preview.icon_mc.name = "icon_mc";
preview.addChild( preview.icon_mc );
addChild( preview );
}
public function set componentInspectorSetting( value:Boolean ):void
{
_componentInspectorSetting = value;
}
public function setSize( w:Number, h:Number ):void
{
/* note:
we don't resize the live preview
we want to keep or default component size
defined in the FLA
*/
}
/**
* @private
* Factory to build the different trackers
*/
private function _factory( event:Event ):void
{
removeEventListener( Event.ENTER_FRAME, _factory );
if( isLivePreview )
{
/* note:
we don't want to init the factory
when we are in live preview
*/
return;
}
_display = this;
if( !debug )
{
this.debug = new DebugConfiguration();
}
if( !config )
{
this.config = new Configuration( debug );
}
if( visualDebug )
{
debug.layout = new Layout( debug, _display );
debug.active = visualDebug;
}
_jsproxy = new JavascriptProxy( debug );
switch( mode )
{
case TrackerMode.BRIDGE :
{
_tracker = _bridgeFactory();
break;
}
case TrackerMode.AS3 :
default:
{
_tracker = _trackerFactory();
}
}
}
/**
* @private
* Factory method for returning a Tracker object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _trackerFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (AS3) v" + version +"\naccount: " + account );
_adSense = new AdSenseGlobals( debug );
_dom = new HTMLDOM( debug );
_dom.cacheProperties();
_env = new Environment( "", "", "", debug, _dom );
_buffer = new Buffer( config, debug, false );
_gifRequest = new GIFRequest( config, debug, _buffer, _env );
use namespace ga_internal;
_env.url = _display.stage.loaderInfo.url;
return new Tracker( account, config, debug, _env, _buffer, _gifRequest, _adSense );
}
/**
* @private
* Factory method for returning a Bridge object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _bridgeFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (Bridge) v" + version +"\naccount: " + account );
return new Bridge( account, _debug, _jsproxy );
}
/**
* The Urchin Account.
* You have to define this parameter to initialize the tracking.
*/
[Inspectable]
public function get account():String
{
return _account ;
}
/**
* @private
*/
public function set account(value:String):void
{
_account = value;
}
/**
* The Tracker configuration.
*/
public function get config():Configuration
{
return _config;
}
/**
* @private
*/
public function set config(value:Configuration):void
{
_config = value;
}
/**
* The Tracker debug configuration.
*/
public function get debug():DebugConfiguration
{
return _debug;
}
/**
* @private
*/
public function set debug(value:DebugConfiguration):void
{
_debug = value;
}
/**
* The Traker mode.
* You can select two modes:
* - AS3: use AS3 only, no dependency on HTML/JS
* - Bridge: use AS3 bridged to HTML/JS which define ga.js
*/
[Inspectable(defaultValue="AS3", enumeration="AS3,Bridge", type="String")]
public function get mode():String
{
return _mode;
}
/**
* @private
*/
public function set mode( value:String ):void
{
_mode = value;
}
/**
* Indicates if the tracker use a visual debug.
* If set to true, at compile time you will
* see a visual debug window with different
* informations about the tracking requests and parameters.
*/
[Inspectable(defaultValue="false", type="Boolean")]
public function get visualDebug():Boolean
{
return _visualDebug;
}
/**
* @private
*/
public function set visualDebug( value:Boolean ):void
{
_visualDebug = value;
}
include "../common.txt"
}
}
|
update to the flash tracker
|
update to the flash tracker
|
ActionScript
|
apache-2.0
|
minimedj/gaforflash,jeremy-wischusen/gaforflash,Vigmar/gaforflash,soumavachakraborty/gaforflash,dli-iclinic/gaforflash,Vigmar/gaforflash,drflash/gaforflash,jisobkim/gaforflash,Miyaru/gaforflash,mrthuanvn/gaforflash,soumavachakraborty/gaforflash,nsdevaraj/gaforflash,jisobkim/gaforflash,nsdevaraj/gaforflash,mrthuanvn/gaforflash,jeremy-wischusen/gaforflash,DimaBaliakin/gaforflash,DimaBaliakin/gaforflash,Miyaru/gaforflash,minimedj/gaforflash,dli-iclinic/gaforflash,drflash/gaforflash
|
d0676c816112f595295573a1ceaf9f254aef8aa8
|
plugins/moderationPlugin/src/ModerationPlugin.as
|
plugins/moderationPlugin/src/ModerationPlugin.as
|
package {
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.plugin.IPlugin;
import com.kaltura.kdpfl.plugin.IPluginFactory;
import com.kaltura.kdpfl.plugin.component.AssetsRefferencer;
import com.kaltura.kdpfl.plugin.component.ModerationMediator;
import com.kaltura.kdpfl.plugin.view.Message;
import com.kaltura.kdpfl.plugin.view.ModerationScreen;
import com.kaltura.kdpfl.view.containers.KHBox;
import com.kaltura.types.KalturaModerationFlagType;
import com.yahoo.astra.fl.containers.HBoxPane;
import com.yahoo.astra.fl.containers.layoutClasses.AdvancedLayoutPane;
import com.yahoo.astra.fl.containers.layoutClasses.BaseLayoutPane;
import fl.containers.BaseScrollPane;
import fl.core.UIComponent;
import flash.events.Event;
import flash.system.Security;
import org.puremvc.as3.interfaces.IFacade;
public class ModerationPlugin extends KHBox implements IPluginFactory, IPlugin {
/**
* defines the value for the type property of the submit event
* dispatched by the screen
*/
public static const SUBMIT:String = "submit";
/**
* defines the value for the type property of the cancel event
* dispatched by the screen
*/
public static const CANCEL:String = "cancel";
/**
* defines the value of the notification which triggers this plugin
*/
public static const FLAG_FOR_REVIEW:String = "flagForReview";
/**
* flagging form header
*/
public var header:String;
/**
* flagging form text (explanation)
*/
public var text:String;
/**
* text to show in combobox for sexual content
*/
public var reasonSex:String = "Sexual content";
/**
* text to show in combobox for violent content
*/
public var reasonViolence:String = "Violent or Repulsive";
/**
* text to show in combobox for harmful content
*/
public var reasonHarmful:String = "Harmful or Dangerous act";
/**
* text to show in combobox for spam content
*/
public var reasonSpam:String = "Spam/Commercials";
/**
* message to show when flagging submition succeeded
*/
public var successMessage:String = "Thank you for sharing your concerns";
/**
* message to show when flagging submition failed
* */
public var failedMessage:String = "submission failed";
/**
* time (in seconds) to wait before hiding end message
*/
public var hideTimeout:int = 3;
/**
* position of close and cancel buttons on flagging form
*/
public var buttonsPosition:String = "right";
/**
* If this is set to flase, the "select report reason" combo-box will be hidden
*/
public var showCombo:Boolean = true;
/**
* This attribute will set the initial selected value of the combobox:
* 0: Sexual content
* 1: Violent or Repulsive
* 2: Harmful or Dangerous act
* 3: Spam/Commercials
*/
public var comboSelectedIndex:Number = 0;
/**
* include the assets class in the app
* */
private var _ar:AssetsRefferencer;
/**
* flagging form
*/
private var _ui:ModerationScreen;
/**
* success / failure message
*/
private var _endMsg:Message;
/**
* plugin mediator
*/
private var _mediator:ModerationMediator;
public function ModerationPlugin() {
Security.allowDomain("*");
this.horizontalAlign = "center";
this.verticalAlign = "middle";
}
/**
* @inheritDoc
* */
public function create(pluginName:String = null):IPlugin {
return this;
}
/**
* @inheritDoc
* */
public function initializePlugin(facade:IFacade):void {
_mediator = new ModerationMediator(this);
facade.registerMediator(_mediator);
}
/**
* set the given style to all visual parts
* */
override public function setSkin(styleName:String, setSkinSize:Boolean = false):void {
if (_ui) {
_ui.setSkin(styleName);
}
if (_endMsg) {
_endMsg.setSkin(styleName);
}
}
/**
* shows the moderation ui over the player
* */
public function showScreen():void {
// disable KDP gui, stop entry from playing, exit fullscreen
_mediator.sendNotification(NotificationType.CLOSE_FULL_SCREEN);
_mediator.sendNotification(NotificationType.ENABLE_GUI, {guiEnabled : false, enableType : "full"});
_mediator.sendNotification(NotificationType.DO_PAUSE);
// show flagging form
if (_ui == null) {
_ui = new ModerationScreen();
_ui.buttonsPosition = buttonsPosition;
if (header) {
_ui.headerText = header;
}
if (text) {
_ui.windowText = text;
}
_ui.reasonsDataProvider = [{label:reasonSex, type:KalturaModerationFlagType.SEXUAL_CONTENT},
{label:reasonViolence, type:KalturaModerationFlagType.VIOLENT_REPULSIVE},
{label:reasonHarmful, type:KalturaModerationFlagType.HARMFUL_DANGEROUS},
{label:reasonSpam, type:KalturaModerationFlagType.SPAM_COMMERCIALS}]
//set custom behaviour for reasons combo
_ui.comboSelectedIndex = comboSelectedIndex;
_ui.showCombo = showCombo;
_ui.addEventListener(ModerationPlugin.CANCEL, clearForm);
_ui.addEventListener(ModerationPlugin.SUBMIT, onSubmitClicked);
}
addChild(_ui);
}
/**
* send data to server
*/
private function onSubmitClicked(e:Event):void {
var o:Object = _ui.data;
var comments:String = o.comments;
var type:int = o.reason;
_mediator.postModeration(comments, type);
}
/**
* close the form panel
*/
private function clearForm(e:Event = null):void {
_ui.clearData();
removeChild(_ui);
end();
}
/**
* remove the end message
* @param e
*/
private function onMessageHide(e:Event):void {
removeChild(_endMsg);
end();
}
/**
* does everything that needs to be done before the plugin is closed
*/
private function end():void {
_mediator.sendNotification(NotificationType.ENABLE_GUI, {guiEnabled : true, enableType : "full"});
}
/**
* notify the user and close panel
* */
public function flagComplete(success:Boolean):void {
clearForm();
if (_endMsg == null) {
_endMsg = new Message();
_endMsg.addEventListener(Message.HIDE, onMessageHide);
}
if (success) {
_endMsg.windowText = successMessage;
}
else {
_endMsg.windowText = failedMessage;
}
addChild(_endMsg);
_endMsg.close(hideTimeout);
}
}
}
|
package {
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.plugin.IPlugin;
import com.kaltura.kdpfl.plugin.IPluginFactory;
import com.kaltura.kdpfl.plugin.component.AssetsRefferencer;
import com.kaltura.kdpfl.plugin.component.ModerationMediator;
import com.kaltura.kdpfl.plugin.view.Message;
import com.kaltura.kdpfl.plugin.view.ModerationScreen;
import com.kaltura.kdpfl.view.containers.KHBox;
import com.kaltura.types.KalturaModerationFlagType;
import com.yahoo.astra.fl.containers.HBoxPane;
import com.yahoo.astra.fl.containers.layoutClasses.AdvancedLayoutPane;
import com.yahoo.astra.fl.containers.layoutClasses.BaseLayoutPane;
import fl.containers.BaseScrollPane;
import fl.core.UIComponent;
import flash.events.Event;
import flash.system.Security;
import org.puremvc.as3.interfaces.IFacade;
public class ModerationPlugin extends KHBox implements IPluginFactory, IPlugin {
/**
* defines the value for the type property of the submit event
* dispatched by the screen
*/
public static const SUBMIT:String = "submit";
/**
* defines the value for the type property of the cancel event
* dispatched by the screen
*/
public static const CANCEL:String = "cancel";
/**
* defines the value of the notification which triggers this plugin
*/
public static const FLAG_FOR_REVIEW:String = "flagForReview";
/**
* defines the value of the notification which turns off the shortcut 508 plugin
*/
public static const DISABLE_SHORTCUT_PLUGIN:String = "disableShortcutPlugin";
/**
* defines the value of the notification which turns on the shortcut 508 plugin
*/
public static const ENABLE_SHORTCUT_PLUGIN:String = "enableShortcutPlugin";
/**
* flagging form header
*/
public var header:String;
/**
* flagging form text (explanation)
*/
public var text:String;
/**
* text to show in combobox for sexual content
*/
public var reasonSex:String = "Sexual content";
/**
* text to show in combobox for violent content
*/
public var reasonViolence:String = "Violent or Repulsive";
/**
* text to show in combobox for harmful content
*/
public var reasonHarmful:String = "Harmful or Dangerous act";
/**
* text to show in combobox for spam content
*/
public var reasonSpam:String = "Spam/Commercials";
/**
* message to show when flagging submition succeeded
*/
public var successMessage:String = "Thank you for sharing your concerns";
/**
* message to show when flagging submition failed
* */
public var failedMessage:String = "submission failed";
/**
* time (in seconds) to wait before hiding end message
*/
public var hideTimeout:int = 3;
/**
* position of close and cancel buttons on flagging form
*/
public var buttonsPosition:String = "right";
/**
* If this is set to flase, the "select report reason" combo-box will be hidden
*/
public var showCombo:Boolean = true;
/**
* This attribute will set the initial selected value of the combobox:
* 0: Sexual content
* 1: Violent or Repulsive
* 2: Harmful or Dangerous act
* 3: Spam/Commercials
*/
public var comboSelectedIndex:Number = 0;
/**
* include the assets class in the app
* */
private var _ar:AssetsRefferencer;
/**
* flagging form
*/
private var _ui:ModerationScreen;
/**
* success / failure message
*/
private var _endMsg:Message;
/**
* plugin mediator
*/
private var _mediator:ModerationMediator;
public function ModerationPlugin() {
Security.allowDomain("*");
this.horizontalAlign = "center";
this.verticalAlign = "middle";
}
/**
* @inheritDoc
* */
public function create(pluginName:String = null):IPlugin {
return this;
}
/**
* @inheritDoc
* */
public function initializePlugin(facade:IFacade):void {
_mediator = new ModerationMediator(this);
facade.registerMediator(_mediator);
}
/**
* set the given style to all visual parts
* */
override public function setSkin(styleName:String, setSkinSize:Boolean = false):void {
if (_ui) {
_ui.setSkin(styleName);
}
if (_endMsg) {
_endMsg.setSkin(styleName);
}
}
/**
* shows the moderation ui over the player
* */
public function showScreen():void {
// disable KDP gui, stop entry from playing, exit fullscreen
_mediator.sendNotification(NotificationType.CLOSE_FULL_SCREEN);
_mediator.sendNotification(NotificationType.ENABLE_GUI, {guiEnabled : false, enableType : "full"});
_mediator.sendNotification(NotificationType.DO_PAUSE);
_mediator.sendNotification(DISABLE_SHORTCUT_PLUGIN);
// show flagging form
if (_ui == null) {
_ui = new ModerationScreen();
_ui.buttonsPosition = buttonsPosition;
if (header) {
_ui.headerText = header;
}
if (text) {
_ui.windowText = text;
}
_ui.reasonsDataProvider = [{label:reasonSex, type:KalturaModerationFlagType.SEXUAL_CONTENT},
{label:reasonViolence, type:KalturaModerationFlagType.VIOLENT_REPULSIVE},
{label:reasonHarmful, type:KalturaModerationFlagType.HARMFUL_DANGEROUS},
{label:reasonSpam, type:KalturaModerationFlagType.SPAM_COMMERCIALS}]
//set custom behaviour for reasons combo
_ui.comboSelectedIndex = comboSelectedIndex;
_ui.showCombo = showCombo;
_ui.addEventListener(ModerationPlugin.CANCEL, clearForm);
_ui.addEventListener(ModerationPlugin.SUBMIT, onSubmitClicked);
}
addChild(_ui);
}
/**
* send data to server
*/
private function onSubmitClicked(e:Event):void {
var o:Object = _ui.data;
var comments:String = o.comments;
var type:int = o.reason;
_mediator.postModeration(comments, type);
}
/**
* close the form panel
*/
private function clearForm(e:Event = null):void {
_ui.clearData();
removeChild(_ui);
end();
_mediator.sendNotification(ENABLE_SHORTCUT_PLUGIN);
}
/**
* remove the end message
* @param e
*/
private function onMessageHide(e:Event):void {
removeChild(_endMsg);
end();
}
/**
* does everything that needs to be done before the plugin is closed
*/
private function end():void {
_mediator.sendNotification(NotificationType.ENABLE_GUI, {guiEnabled : true, enableType : "full"});
}
/**
* notify the user and close panel
* */
public function flagComplete(success:Boolean):void {
clearForm();
if (_endMsg == null) {
_endMsg = new Message();
_endMsg.addEventListener(Message.HIDE, onMessageHide);
}
if (success) {
_endMsg.windowText = successMessage;
}
else {
_endMsg.windowText = failedMessage;
}
addChild(_endMsg);
_endMsg.close(hideTimeout);
}
}
}
|
fix shortcut and moderation collision--
|
fix shortcut and moderation collision--
|
ActionScript
|
agpl-3.0
|
kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp
|
5e97a04402e9e854dd68c6aceb088ed46f0faa6f
|
src/as/com/threerings/crowd/data/ManagerCaller.as
|
src/as/com/threerings/crowd/data/ManagerCaller.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.crowd.data {
public class ManagerCaller
{
public function ManagerCaller (plobj :PlaceObject)
{
_plobj = plobj;
}
/**
* Called to call a method on the manager.
*/
public function invoke (method :String, args :Array = null) :void
{
_plobj.postMessage(method, args);
}
/** The place object we're thingy-ing for. */
protected var _plobj :PlaceObject;
}
}
|
//
// $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.crowd.data {
public class ManagerCaller
{
public function ManagerCaller (plobj :PlaceObject)
{
_plobj = plobj;
}
/**
* Called to call a method on the manager.
*/
public function invoke (method :String, ... args) :void
{
_plobj.postMessage(method, args);
}
/** The place object we're thingy-ing for. */
protected var _plobj :PlaceObject;
}
}
|
Change this instance back. Varargs are still a nightmare and should generally be avoided, but nobody's going to override this method and we're always calling a regular method on the server, not a varargs method.
|
Change this instance back. Varargs are still a nightmare and should
generally be avoided, but nobody's going to override this method and
we're always calling a regular method on the server, not a varargs method.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4622 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
402283a9e85f1db6c93c69422c45c33eaf50e220
|
WEB-INF/lps/lfc/kernel/swf/LzInputTextSprite.as
|
WEB-INF/lps/lfc/kernel/swf/LzInputTextSprite.as
|
/**
* LzInputTextSprite.as
*
* @copyright Copyright 2001-2007 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
/**
* @shortdesc Used for input text.
*
*/
var LzInputTextSprite = function(newowner, args) {
this.__LZdepth = newowner.immediateparent.sprite.__LZsvdepth++;
this.__LZsvdepth = 0;
this.owner = newowner;
// Copied (eep!) from LzTextSprite
//inherited attributes, documented in view
this.fontname = args.font;
this.fontsize = args.fontsize;
this.fontstyle = args.fontstyle;
this.sizeToHeight = false;
this.yscroll = 0;
this.xscroll = 0;
this.resize = false;
////////////////////////////////////////////////////////////////
this.masked = true;
var mc = this.makeContainerResource();
// create the textfield on container movieclip - give it a unique name
var txtname = '$LzText';
mc.createTextField( txtname, 1, 0, 0, 100, 12 );
var textclip = mc[txtname];
//Debug.write('created', textclip, 'in', mc, txtname);
this.__LZtextclip = textclip;
// set a pointer back to this view from the TextField object
textclip.__lzview = this.owner;
textclip._visible = true;
this.password = args.password ? true : false;
textclip.password = this.password;
}
LzInputTextSprite.prototype = new LzTextSprite(null);
LzInputTextSprite.prototype.defaultattrs.selectable = true;
LzInputTextSprite.prototype.defaultattrs.enabled = true;
/**
* @access private
*/
LzInputTextSprite.prototype.construct = function ( parent , args ){
}
LzInputTextSprite.prototype.focusable = true;
LzInputTextSprite.prototype.__initTextProperties = function (args) {
var textclip = this.__LZtextclip;
// conditionalize this; set to false for inputtext for back compatibility with lps 2.1
textclip.html = true;
textclip.selectable = args.selectable;
textclip.autoSize = false;
this.setMultiline( args.multiline );
//inherited attributes, documented in view
this.fontname = args.font;
this.fontsize = args.fontsize;
this.fontstyle = args.fontstyle;
this.__setFormat();
this.text = args.text;
textclip.htmlText = this.format + this.text + this.closeformat;
textclip.background = false;
// To compute our width:
// + if text is multiline:
// if no width is supplied, use parent width
// + if text is single line:
// if no width was supplied and there's no constraint, measure the text width:
// if empty text content was supplied, use DEFAULT_WIDTH
//(args.width == null && typeof(args.$refs.width) != "function")
if (args.width == null) {
// if there's text content, measure it's width
if (this.text != null && this.text.length > 0) {
args.width = this.getTextWidth();
} else {
// Empty string would result in a zero width view, which confuses
// developers, so use something reasonable instead.
args.width = this.DEFAULT_WIDTH;
}
}
// To compute our height:
// + If height is supplied, use it.
// + if no height supplied:
// if single line, use font line height
// else get height from flash textobject.textHeight
//
if (args.height == null && typeof(args.$refs.height) != "function") {
this.sizeToHeight = true;
// set autoSize to get text measured
textclip.autoSize = true;
textclip.htmlText = this.format + "__ypgSAMPLE__" + this.closeformat;
this.height = textclip._height;
textclip.htmlText = this.format + this.text + this.closeformat;
if (!this.multiline) {
// But turn off autosizing for single line text, now that
// we got a correct line height from flash.
textclip.autoSize = false;
}
} else {
textclip._height = args.height;
//this.setHeight(args.height);
}
// Default the scrollheight to the visible height.
this.scrollheight = this.height;
//@field Number maxlength: maximum number of characters allowed in this field
// default: null
//
if (args.maxlength != null) {
this.setMaxLength(args.maxlength);
}
//@field String pattern: regexp describing set of characters allowed in this field
// Restrict the characters that can be entered to a pattern
// specified by a regular expression.
//
// Currently only the expression [ ]* enclosing a set of
// characters or character ranges, preceded by an optional "^", is
// supported.
//
// examples: [0-9]* , [a-zA-Z0-9]*, [^0-9]*
// default: null
//
if (args.pattern != null) {
this.setPattern(args.pattern);
}
// We do not support html in input fields.
if ('enabled' in this && this.enabled) {
textclip.type = 'input';
} else {
textclip.type = 'dynamic';
}
this.__LZtextclip.__cacheSelection = TextField.prototype.__cacheSelection;
textclip.onSetFocus = TextField.prototype.__gotFocus;
textclip.onKillFocus = TextField.prototype.__lostFocus;
textclip.onChanged = TextField.prototype.__onChanged;
this.hasFocus = false;
textclip.onScroller = this.__updatefieldsize;
}
/**
* @access private
*/
LzInputTextSprite.prototype.gotFocus = function ( ){
//Debug.write('LzInputTextSprite.__handleOnFocus');
if ( this.hasFocus ) { return; }
this.select();
this.hasFocus = true;
}
LzInputTextSprite.prototype.select = function ( ){
var sf = targetPath(this.__LZtextclip);
// calling setFocus() seems to bash the scroll value, so save it
var myscroll = this.__LZtextclip.scroll;
if( Selection.getFocus() != sf ) {
Selection.setFocus( sf );
}
this.__LZtextclip.hscroll = 0;
// restore the scroll value
this.__LZtextclip.scroll = myscroll;
this.__LZtextclip.background = false;
}
LzInputTextSprite.prototype.deselect = function ( ){
var sf = targetPath(this.__LZtextclip);
if( Selection.getFocus() == sf ) {
Selection.setFocus( null );
}
}
/**
* @access private
*/
LzInputTextSprite.prototype.gotBlur = function ( ){
//Debug.write('LzInputTextSprite.__handleOnBlur');
this.hasFocus = false;
this.deselect();
}
/**
* 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
*/
TextField.prototype.__gotFocus = function ( oldfocus ){
// scroll text fields horizontally back to start
if (this.__lzview) this.__lzview.inputtextevent('onfocus');
}
/**
* Register to be called when the text field is modified. Convert this
* into a LFC ontext event.
* @access private
*/
TextField.prototype.__onChanged = function ( ){
if (this.__lzview) this.__lzview.inputtextevent('onchange', this.text);
}
/**
* @access private
*/
TextField.prototype.__lostFocus = function ( ){
if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus");
LzIdle.callOnIdle(this.__handlelostFocusdel);
}
/**
* 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
*/
TextField.prototype.__handlelostFocus = function ( ){
//Debug.write('lostfocus', this.__lzview.hasFocus, LzFocus.lastfocus, this, LzFocus.getFocus(), this.__lzview, this.__lzview.inputtextevent);
if (this.__lzview == LzFocus.getFocus()) {
LzFocus.clearFocus();
if (this.__lzview) this.__lzview.inputtextevent('onblur');
}
}
/**
* Retrieves the contents of the text field for use by a datapath. See
* <code>LzDatapath.updateData</code> for more on this.
* @access protected
*/
LzInputTextSprite.prototype.updateData = function (){
return this.__LZtextclip.text;
}
/**
* Sets whether user can modify input text field
* @param Boolean enabled: true if the text field can be edited
*/
LzInputTextSprite.prototype.setEnabled = function (enabled){
var mc = this.__LZtextclip;
this.enabled = enabled;
if (enabled) {
mc.type = 'input';
} else {
mc.type = 'dynamic';
}
}
/**
* Set the html flag on this text view
*/
LzInputTextSprite.prototype.setHTML = function (htmlp) {
this.__LZtextclip.html = htmlp;
}
/**
* setText sets the text of the field to display
* @param String t: the string to which to set the text
*/
LzInputTextSprite.prototype.setText = function ( t ){
//Debug.write('LzInputTextSprite.setText', this, t);
if (typeof(t) == 'undefined' || t == null) {
t = "";
} else if (typeof(t) != "string") {
t = t.toString();
}
this.text = t;// this.format + t if proper measurement were working
var mc = this.__LZtextclip;
// these must be done in this order, to get Flash to take the HTML styling
// but not to ignore CR linebreak chars that might be in the string.
if (mc.html) {
mc.htmlText = this.format;
}
mc.text = t;
/*
if (this.resize && (this.multiline == false)) {
// single line resizable fields adjust their width to match the text
this.setWidth(this.getTextWidth());
}*/
//multiline resizable fields adjust their height
if (this.multiline && this.sizeToHeight) {
this.setHeight(mc._height);
}
if (this.multiline && this.scroll == 0 ) {
var scrolldel = new LzDelegate(this, "__LZforceScrollAttrs");
LzIdle.callOnIdle(scrolldel);
}
//@event ontext: Sent whenever the text in the field changes.
//this.owner.ontext.sendEvent(t);
}
LzInputTextSprite.prototype.getTextfieldHeight = function ( ){
return this.__LZtextclip._height
}
LzTextSprite.prototype.getText = function ( ){
return this.__LZtextclip.text;
}
|
/**
* LzInputTextSprite.as
*
* @copyright Copyright 2001-2007 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
/**
* @shortdesc Used for input text.
*
*/
var LzInputTextSprite = function(newowner, args) {
this.__LZdepth = newowner.immediateparent.sprite.__LZsvdepth++;
this.__LZsvdepth = 0;
this.owner = newowner;
// Copied (eep!) from LzTextSprite
//inherited attributes, documented in view
this.fontname = args.font;
this.fontsize = args.fontsize;
this.fontstyle = args.fontstyle;
this.sizeToHeight = false;
this.yscroll = 0;
this.xscroll = 0;
this.resize = false;
////////////////////////////////////////////////////////////////
this.masked = true;
var mc = this.makeContainerResource();
// create the textfield on container movieclip - give it a unique name
var txtname = '$LzText';
mc.createTextField( txtname, 1, 0, 0, 100, 12 );
var textclip = mc[txtname];
//Debug.write('created', textclip, 'in', mc, txtname);
this.__LZtextclip = textclip;
// set a pointer back to this view from the TextField object
textclip.__lzview = this.owner;
textclip._visible = true;
this.password = args.password ? true : false;
textclip.password = this.password;
}
LzInputTextSprite.prototype = new LzTextSprite(null);
/**
* @access private
*/
LzInputTextSprite.prototype.construct = function ( parent , args ){
}
LzInputTextSprite.prototype.focusable = true;
LzInputTextSprite.prototype.__initTextProperties = function (args) {
var textclip = this.__LZtextclip;
// conditionalize this; set to false for inputtext for back compatibility with lps 2.1
textclip.html = true;
textclip.selectable = args.selectable;
textclip.autoSize = false;
this.setMultiline( args.multiline );
//inherited attributes, documented in view
this.fontname = args.font;
this.fontsize = args.fontsize;
this.fontstyle = args.fontstyle;
this.__setFormat();
this.text = args.text;
textclip.htmlText = this.format + this.text + this.closeformat;
textclip.background = false;
// To compute our width:
// + if text is multiline:
// if no width is supplied, use parent width
// + if text is single line:
// if no width was supplied and there's no constraint, measure the text width:
// if empty text content was supplied, use DEFAULT_WIDTH
//(args.width == null && typeof(args.$refs.width) != "function")
if (args.width == null) {
// if there's text content, measure it's width
if (this.text != null && this.text.length > 0) {
args.width = this.getTextWidth();
} else {
// Empty string would result in a zero width view, which confuses
// developers, so use something reasonable instead.
args.width = this.DEFAULT_WIDTH;
}
}
// To compute our height:
// + If height is supplied, use it.
// + if no height supplied:
// if single line, use font line height
// else get height from flash textobject.textHeight
//
if (args.height == null && typeof(args.$refs.height) != "function") {
this.sizeToHeight = true;
// set autoSize to get text measured
textclip.autoSize = true;
textclip.htmlText = this.format + "__ypgSAMPLE__" + this.closeformat;
this.height = textclip._height;
textclip.htmlText = this.format + this.text + this.closeformat;
if (!this.multiline) {
// But turn off autosizing for single line text, now that
// we got a correct line height from flash.
textclip.autoSize = false;
}
} else {
textclip._height = args.height;
//this.setHeight(args.height);
}
// Default the scrollheight to the visible height.
this.scrollheight = this.height;
//@field Number maxlength: maximum number of characters allowed in this field
// default: null
//
if (args.maxlength != null) {
this.setMaxLength(args.maxlength);
}
//@field String pattern: regexp describing set of characters allowed in this field
// Restrict the characters that can be entered to a pattern
// specified by a regular expression.
//
// Currently only the expression [ ]* enclosing a set of
// characters or character ranges, preceded by an optional "^", is
// supported.
//
// examples: [0-9]* , [a-zA-Z0-9]*, [^0-9]*
// default: null
//
if (args.pattern != null) {
this.setPattern(args.pattern);
}
// We do not support html in input fields.
if ('enabled' in this && this.enabled) {
textclip.type = 'input';
} else {
textclip.type = 'dynamic';
}
this.__LZtextclip.__cacheSelection = TextField.prototype.__cacheSelection;
textclip.onSetFocus = TextField.prototype.__gotFocus;
textclip.onKillFocus = TextField.prototype.__lostFocus;
textclip.onChanged = TextField.prototype.__onChanged;
this.hasFocus = false;
textclip.onScroller = this.__updatefieldsize;
}
/**
* @access private
*/
LzInputTextSprite.prototype.gotFocus = function ( ){
//Debug.write('LzInputTextSprite.__handleOnFocus');
if ( this.hasFocus ) { return; }
this.select();
this.hasFocus = true;
}
LzInputTextSprite.prototype.select = function ( ){
var sf = targetPath(this.__LZtextclip);
// calling setFocus() seems to bash the scroll value, so save it
var myscroll = this.__LZtextclip.scroll;
if( Selection.getFocus() != sf ) {
Selection.setFocus( sf );
}
this.__LZtextclip.hscroll = 0;
// restore the scroll value
this.__LZtextclip.scroll = myscroll;
this.__LZtextclip.background = false;
}
LzInputTextSprite.prototype.deselect = function ( ){
var sf = targetPath(this.__LZtextclip);
if( Selection.getFocus() == sf ) {
Selection.setFocus( null );
}
}
/**
* @access private
*/
LzInputTextSprite.prototype.gotBlur = function ( ){
//Debug.write('LzInputTextSprite.__handleOnBlur');
this.hasFocus = false;
this.deselect();
}
/**
* 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
*/
TextField.prototype.__gotFocus = function ( oldfocus ){
// scroll text fields horizontally back to start
if (this.__lzview) this.__lzview.inputtextevent('onfocus');
}
/**
* Register to be called when the text field is modified. Convert this
* into a LFC ontext event.
* @access private
*/
TextField.prototype.__onChanged = function ( ){
if (this.__lzview) this.__lzview.inputtextevent('onchange', this.text);
}
/**
* @access private
*/
TextField.prototype.__lostFocus = function ( ){
if (this['__handlelostFocusdel'] == null) this.__handlelostFocusdel = new LzDelegate(this, "__handlelostFocus");
LzIdle.callOnIdle(this.__handlelostFocusdel);
}
/**
* 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
*/
TextField.prototype.__handlelostFocus = function ( ){
//Debug.write('lostfocus', this.__lzview.hasFocus, LzFocus.lastfocus, this, LzFocus.getFocus(), this.__lzview, this.__lzview.inputtextevent);
if (this.__lzview == LzFocus.getFocus()) {
LzFocus.clearFocus();
if (this.__lzview) this.__lzview.inputtextevent('onblur');
}
}
/**
* Retrieves the contents of the text field for use by a datapath. See
* <code>LzDatapath.updateData</code> for more on this.
* @access protected
*/
LzInputTextSprite.prototype.updateData = function (){
return this.__LZtextclip.text;
}
/**
* Sets whether user can modify input text field
* @param Boolean enabled: true if the text field can be edited
*/
LzInputTextSprite.prototype.setEnabled = function (enabled){
var mc = this.__LZtextclip;
this.enabled = enabled;
if (enabled) {
mc.type = 'input';
} else {
mc.type = 'dynamic';
}
}
/**
* Set the html flag on this text view
*/
LzInputTextSprite.prototype.setHTML = function (htmlp) {
this.__LZtextclip.html = htmlp;
}
/**
* setText sets the text of the field to display
* @param String t: the string to which to set the text
*/
LzInputTextSprite.prototype.setText = function ( t ){
//Debug.write('LzInputTextSprite.setText', this, t);
if (typeof(t) == 'undefined' || t == null) {
t = "";
} else if (typeof(t) != "string") {
t = t.toString();
}
this.text = t;// this.format + t if proper measurement were working
var mc = this.__LZtextclip;
// these must be done in this order, to get Flash to take the HTML styling
// but not to ignore CR linebreak chars that might be in the string.
if (mc.html) {
mc.htmlText = this.format;
}
mc.text = t;
/*
if (this.resize && (this.multiline == false)) {
// single line resizable fields adjust their width to match the text
this.setWidth(this.getTextWidth());
}*/
//multiline resizable fields adjust their height
if (this.multiline && this.sizeToHeight) {
this.setHeight(mc._height);
}
if (this.multiline && this.scroll == 0 ) {
var scrolldel = new LzDelegate(this, "__LZforceScrollAttrs");
LzIdle.callOnIdle(scrolldel);
}
//@event ontext: Sent whenever the text in the field changes.
//this.owner.ontext.sendEvent(t);
}
LzInputTextSprite.prototype.getTextfieldHeight = function ( ){
return this.__LZtextclip._height
}
LzTextSprite.prototype.getText = function ( ){
return this.__LZtextclip.text;
}
|
Change 20071031-Philip-8 by Philip@Philip-DC on 2007-10-31 16:26:16 EDT in /cygdrive/f/laszlo/svn/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk Summary: Remove unnecessary references from LzInputTextSprite.as New Features: Bugs Fixed: LPP-4951 Technical Reviewer: max QA Reviewer: (pending) Doc Reviewer: (pending) Documentation: Release Notes: Details: LzInputTextSprite.as contains some copied code that references a hash from LzNode (defaultattrs). I removed it. Tests: /test/smoke/smokecheck.lzx Files: M WEB-INF/lps/lfc/kernel/swf/LzInputTextSprite.as Changeset: http://svn.openlaszlo.org/openlaszlo/patches/20071031-Philip-8.tar
|
Change 20071031-Philip-8 by Philip@Philip-DC on 2007-10-31 16:26:16 EDT
in /cygdrive/f/laszlo/svn/src/svn/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: Remove unnecessary references from LzInputTextSprite.as
New Features:
Bugs Fixed: LPP-4951
Technical Reviewer: max
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
LzInputTextSprite.as contains some copied code that references a hash from LzNode (defaultattrs). I removed it.
Tests:
/test/smoke/smokecheck.lzx
Files:
M WEB-INF/lps/lfc/kernel/swf/LzInputTextSprite.as
Changeset: http://svn.openlaszlo.org/openlaszlo/patches/20071031-Philip-8.tar
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@7091 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
5512ff416907e8069f4cac0053cb9dfc72bab158
|
src/aerys/minko/render/DrawCall.as
|
src/aerys/minko/render/DrawCall.as
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
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.render.resource.Context3DResource;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.VertexBuffer3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.binding.IBinder;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.ColorMask;
import aerys.minko.type.enum.TriangleCulling;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import flash.display3D.Context3DProgramType;
import flash.utils.Dictionary;
/**
* DrawCall objects contain all the shader constants and buffer settings required
* to perform drawing operations using the Stage3D API.
* @author Jean-Marc Le Roux
*
*/
public final class DrawCall
{
use namespace minko_render;
private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX;
private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT;
private static const NUM_TEXTURES : uint = 8;
private static const NUM_VERTEX_BUFFERS : uint = 8;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true);
private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true);
private var _bindings : Object = null;
private var _vsInputComponents : Vector.<VertexComponent> = null;
private var _vsInputIndices : Vector.<uint> = null;
private var _cpuConstants : Dictionary = null;
private var _vsConstants : Vector.<Number> = null;
private var _fsConstants : Vector.<Number> = null;
private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true);
// states
private var _indexBuffer : IndexBuffer3DResource = null;
private var _firstIndex : int = 0;
private var _numTriangles : int = -1;
private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true);
private var _numVertexComponents: uint = 0;
private var _offsets : Vector.<int> = new Vector.<int>(8, true);
private var _formats : Vector.<String> = new Vector.<String>(8, true);
private var _blending : uint = 0;
private var _blendingSource : String = null;
private var _blendingDest : String = null;
private var _triangleCulling : uint = 0;
private var _triangleCullingStr : String = null;
private var _colorMask : uint = 0;
private var _colorMaskR : Boolean = true;
private var _colorMaskG : Boolean = true;
private var _colorMaskB : Boolean = true;
private var _colorMaskA : Boolean = true;
private var _enabled : Boolean = true;
private var _depth : Number = 0.;
private var _center : Vector4 = null;
private var _invalidDepth : Boolean = false;
private var _localToWorld : Matrix4x4 = null;
private var _worldToScreen : Matrix4x4 = null;
private var _changes : Object = {};
public function get vertexComponents() : Vector.<VertexComponent>
{
return _vsInputComponents;
}
public function get blending() : uint
{
return _blending;
}
public function set blending(value : uint) : void
{
_blending = value;
_blendingSource = Blending.STRINGS[int(value & 0xffff)];
_blendingDest = Blending.STRINGS[int(value >>> 16)]
}
public function get triangleCulling() : uint
{
return _triangleCulling;
}
public function set triangleCulling(value : uint) : void
{
_triangleCulling = value;
_triangleCullingStr = TriangleCulling.STRINGS[value];
}
public function get colorMask() : uint
{
return _colorMask;
}
public function set colorMask(value : uint) : void
{
_colorMask = value;
_colorMaskR = (value & ColorMask.RED) != 0;
_colorMaskG = (value & ColorMask.GREEN) != 0;
_colorMaskB = (value & ColorMask.BLUE) != 0;
_colorMaskA = (value & ColorMask.ALPHA) != 0;
}
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
if (value)
for (var bindingName : String in _changes)
{
setParameter(bindingName, _changes[bindingName]);
delete _changes[bindingName];
}
}
public function get depth() : Number
{
if (_invalidDepth && _enabled)
{
_invalidDepth = false;
if (_localToWorld != null && _worldToScreen != null)
{
var worldSpacePosition : Vector4 = _localToWorld.transformVector(
_center, TMP_VECTOR4
);
var screenSpacePosition : Vector4 = _worldToScreen.transformVector(
worldSpacePosition, TMP_VECTOR4
);
_depth = screenSpacePosition.z / screenSpacePosition.w;
}
}
return _depth;
}
public function configure(program : Program3DResource,
geometry : Geometry,
meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
// if (_bindings != null)
// unsetBindings(meshBindings, sceneBindings);
_invalidDepth = computeDepth;
setProgram(program);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
_changes = {};
for (var parameter : String in _bindings)
{
if (meshBindings.hasCallback(parameter, parameterChangedHandler))
meshBindings.removeCallback(parameter, parameterChangedHandler);
else if (sceneBindings.hasCallback(parameter, parameterChangedHandler))
sceneBindings.removeCallback(parameter, parameterChangedHandler);
}
if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler))
sceneBindings.removeCallback('worldToScreen', transformChangedHandler);
if (meshBindings.hasCallback('localToWorld', transformChangedHandler))
meshBindings.removeCallback('localToWorld', transformChangedHandler);
}
private function setProgram(program : Program3DResource) : void
{
_cpuConstants = new Dictionary();
_vsConstants = program._vsConstants.slice();
_fsConstants = program._fsConstants.slice();
_fsTextures = program._fsTextures.slice();
_vsInputComponents = program._vertexInputComponents;
_vsInputIndices = program._vertexInputIndices;
_bindings = program._bindings;
triangleCulling = TriangleCulling.FRONT;
blending = Blending.NORMAL;
colorMask = ColorMask.RGBA;
}
/**
* Ask geometry to compute additional vertex data if needed for this drawcall.
*/
public function updateGeometry(geometry : Geometry) : void
{
var vertexFormat : VertexFormat = geometry.format;
if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0
&& !vertexFormat.hasComponent(VertexComponent.TANGENT))
{
geometry.computeTangentSpace();
}
else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0
&& !vertexFormat.hasComponent(VertexComponent.NORMAL))
{
geometry.computeNormals();
}
}
/**
* Obtain a reference to each buffer and offset that apply() may possibly need.
*
*/
public function setGeometry(geometry : Geometry, frame : uint = 0) : void
{
updateGeometry(geometry);
_center = geometry.boundingSphere
? geometry.boundingSphere.center
: Vector4.ZERO;
_numVertexComponents = _vsInputComponents.length;
_indexBuffer = geometry.indexStream.resource;
_firstIndex = geometry.firstIndex;
_numTriangles = geometry.numTriangles;
for (var i : uint = 0; i < _numVertexComponents; ++i)
{
var component : VertexComponent = _vsInputComponents[i];
var index : uint = _vsInputIndices[i];
if (component)
{
var vertexStream : IVertexStream = geometry.getVertexStream(index + frame);
var stream : VertexStream = vertexStream.getStreamByComponent(component);
if (stream == null)
{
throw new Error(
'Missing vertex component: \'' + component.toString() + '\'.'
);
}
_vertexBuffers[i] = stream.resource;
_formats[i] = component.nativeFormatString;
_offsets[i] = stream.format.getOffsetForComponent(component);
}
}
}
/**
* @fixme There is a bug here
* @fixme We splitted properties between scene and mesh
* @fixme it should be done on the compiler also to avoid this ugly hack
*/
private function setBindings(meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
for (var parameter : String in _bindings)
{
meshBindings.addCallback(parameter, parameterChangedHandler);
if (!sceneBindings.hasCallback(parameter, parameterChangedHandler))
sceneBindings.addCallback(parameter, parameterChangedHandler);
if (meshBindings.propertyExists(parameter))
setParameter(parameter, meshBindings.getProperty(parameter));
else if (sceneBindings.propertyExists(parameter))
setParameter(parameter, sceneBindings.getProperty(parameter));
}
if (computeDepth)
{
_worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4;
_localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4;
sceneBindings.addCallback('worldToScreen', transformChangedHandler);
meshBindings.addCallback('localToWorld', transformChangedHandler);
_invalidDepth = true;
}
}
public function apply(context : Context3DResource, previous : DrawCall) : uint
{
if (!_enabled)
return 0;
context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA)
.setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants)
.setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants);
var numTextures : uint = _fsTextures.length;
var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES;
var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS;
var i : uint = 0;
// setup textures
for (i = 0; i < numTextures; ++i)
{
context.setTextureAt(
i,
(_fsTextures[i] as ITextureResource).getTexture(context)
);
}
while (i < maxTextures)
context.setTextureAt(i++, null);
// setup buffers
for (i = 0; i < _numVertexComponents; ++i)
{
context.setVertexBufferAt(
i,
(_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context),
_offsets[i],
_formats[i]
);
}
while (i < maxBuffers)
context.setVertexBufferAt(i++, null);
// draw triangles
context.drawTriangles(
_indexBuffer.getIndexBuffer3D(context),
_firstIndex,
_numTriangles
);
return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles;
}
public function setParameter(name : String, value : Object) : void
{
if (!_enabled)
{
_changes[name] = value;
return ;
}
var binding : IBinder = _bindings[name] as IBinder;
if (binding != null)
binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value);
}
private function parameterChangedHandler(dataBindings : DataBindings,
property : String,
oldValue : Object,
newValue : Object) : void
{
newValue !== null && setParameter(property, newValue);
}
private function transformChangedHandler(bindings : DataBindings,
property : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
if (property == 'worldToScreen')
_worldToScreen = newValue;
else if (property == 'localToWorld')
_localToWorld = newValue;
_invalidDepth = true;
}
}
}
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
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.render.resource.Context3DResource;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.VertexBuffer3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.binding.IBinder;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.ColorMask;
import aerys.minko.type.enum.TriangleCulling;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import flash.display3D.Context3DProgramType;
import flash.utils.Dictionary;
/**
* DrawCall objects contain all the shader constants and buffer settings required
* to perform drawing operations using the Stage3D API.
* @author Jean-Marc Le Roux
*
*/
public final class DrawCall
{
use namespace minko_render;
private static const PROGRAM_TYPE_VERTEX : String = Context3DProgramType.VERTEX;
private static const PROGRAM_TYPE_FRAGMENT : String = Context3DProgramType.FRAGMENT;
private static const NUM_TEXTURES : uint = 8;
private static const NUM_VERTEX_BUFFERS : uint = 8;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const TMP_NUMBERS : Vector.<Number> = new Vector.<Number>(0xffff, true);
private static const TMP_INTS : Vector.<int> = new Vector.<int>(0xffff, true);
private var _bindings : Object = null;
private var _vsInputComponents : Vector.<VertexComponent> = null;
private var _vsInputIndices : Vector.<uint> = null;
private var _cpuConstants : Dictionary = null;
private var _vsConstants : Vector.<Number> = null;
private var _fsConstants : Vector.<Number> = null;
private var _fsTextures : Vector.<ITextureResource> = new Vector.<ITextureResource>(NUM_TEXTURES, true);
// states
private var _indexBuffer : IndexBuffer3DResource = null;
private var _firstIndex : int = 0;
private var _numTriangles : int = -1;
private var _vertexBuffers : Vector.<VertexBuffer3DResource> = new Vector.<VertexBuffer3DResource>(NUM_VERTEX_BUFFERS, true);
private var _numVertexComponents: uint = 0;
private var _offsets : Vector.<int> = new Vector.<int>(8, true);
private var _formats : Vector.<String> = new Vector.<String>(8, true);
private var _blending : uint = 0;
private var _blendingSource : String = null;
private var _blendingDest : String = null;
private var _triangleCulling : uint = 0;
private var _triangleCullingStr : String = null;
private var _colorMask : uint = 0;
private var _colorMaskR : Boolean = true;
private var _colorMaskG : Boolean = true;
private var _colorMaskB : Boolean = true;
private var _colorMaskA : Boolean = true;
private var _enabled : Boolean = true;
private var _depth : Number = 0.;
private var _center : Vector4 = null;
private var _invalidDepth : Boolean = false;
private var _localToWorld : Matrix4x4 = null;
private var _worldToScreen : Matrix4x4 = null;
private var _changes : Object = {};
public function get vertexComponents() : Vector.<VertexComponent>
{
return _vsInputComponents;
}
public function get blending() : uint
{
return _blending;
}
public function set blending(value : uint) : void
{
_blending = value;
_blendingSource = Blending.STRINGS[int(value & 0xffff)];
_blendingDest = Blending.STRINGS[int(value >>> 16)]
}
public function get triangleCulling() : uint
{
return _triangleCulling;
}
public function set triangleCulling(value : uint) : void
{
_triangleCulling = value;
_triangleCullingStr = TriangleCulling.STRINGS[value];
}
public function get colorMask() : uint
{
return _colorMask;
}
public function set colorMask(value : uint) : void
{
_colorMask = value;
_colorMaskR = (value & ColorMask.RED) != 0;
_colorMaskG = (value & ColorMask.GREEN) != 0;
_colorMaskB = (value & ColorMask.BLUE) != 0;
_colorMaskA = (value & ColorMask.ALPHA) != 0;
}
public function get enabled() : Boolean
{
return _enabled;
}
public function set enabled(value : Boolean) : void
{
_enabled = value;
if (value)
for (var bindingName : String in _changes)
{
setParameter(bindingName, _changes[bindingName]);
delete _changes[bindingName];
}
}
public function get depth() : Number
{
if (_invalidDepth && _enabled)
{
_invalidDepth = false;
if (_localToWorld != null && _worldToScreen != null)
{
var worldSpacePosition : Vector4 = _localToWorld.transformVector(
_center, TMP_VECTOR4
);
var screenSpacePosition : Vector4 = _worldToScreen.transformVector(
worldSpacePosition, TMP_VECTOR4
);
_depth = screenSpacePosition.z / screenSpacePosition.w;
}
}
return _depth;
}
public function configure(program : Program3DResource,
geometry : Geometry,
meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
// if (_bindings != null)
// unsetBindings(meshBindings, sceneBindings);
_invalidDepth = computeDepth;
setProgram(program);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
_changes = {};
for (var parameter : String in _bindings)
{
if (meshBindings.hasCallback(parameter, parameterChangedHandler))
meshBindings.removeCallback(parameter, parameterChangedHandler);
else if (sceneBindings.hasCallback(parameter, parameterChangedHandler))
sceneBindings.removeCallback(parameter, parameterChangedHandler);
}
if (sceneBindings.hasCallback('worldToScreen', transformChangedHandler))
sceneBindings.removeCallback('worldToScreen', transformChangedHandler);
if (meshBindings.hasCallback('localToWorld', transformChangedHandler))
meshBindings.removeCallback('localToWorld', transformChangedHandler);
}
private function setProgram(program : Program3DResource) : void
{
_cpuConstants = new Dictionary();
_vsConstants = program._vsConstants.slice();
_fsConstants = program._fsConstants.slice();
_fsTextures = program._fsTextures.slice();
_vsInputComponents = program._vertexInputComponents;
_vsInputIndices = program._vertexInputIndices;
_bindings = program._bindings;
triangleCulling = TriangleCulling.FRONT;
blending = Blending.NORMAL;
colorMask = ColorMask.RGBA;
}
/**
* Ask geometry to compute additional vertex data if needed for this drawcall.
*/
public function updateGeometry(geometry : Geometry) : void
{
var vertexFormat : VertexFormat = geometry.format;
if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0
&& !vertexFormat.hasComponent(VertexComponent.TANGENT))
{
geometry.computeTangentSpace();
}
else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0
&& !vertexFormat.hasComponent(VertexComponent.NORMAL))
{
geometry.computeNormals();
}
}
/**
* Obtain a reference to each buffer and offset that apply() may possibly need.
*
*/
public function setGeometry(geometry : Geometry, frame : uint = 0) : void
{
if (!_vsInputComponents)
return ;
updateGeometry(geometry);
_center = geometry.boundingSphere
? geometry.boundingSphere.center
: Vector4.ZERO;
_numVertexComponents = _vsInputComponents.length;
_indexBuffer = geometry.indexStream.resource;
_firstIndex = geometry.firstIndex;
_numTriangles = geometry.numTriangles;
for (var i : uint = 0; i < _numVertexComponents; ++i)
{
var component : VertexComponent = _vsInputComponents[i];
var index : uint = _vsInputIndices[i];
if (component)
{
var vertexStream : IVertexStream = geometry.getVertexStream(index + frame);
var stream : VertexStream = vertexStream.getStreamByComponent(component);
if (stream == null)
{
throw new Error(
'Missing vertex component: \'' + component.toString() + '\'.'
);
}
_vertexBuffers[i] = stream.resource;
_formats[i] = component.nativeFormatString;
_offsets[i] = stream.format.getOffsetForComponent(component);
}
}
}
/**
* @fixme There is a bug here
* @fixme We splitted properties between scene and mesh
* @fixme it should be done on the compiler also to avoid this ugly hack
*/
private function setBindings(meshBindings : DataBindings,
sceneBindings : DataBindings,
computeDepth : Boolean) : void
{
for (var parameter : String in _bindings)
{
meshBindings.addCallback(parameter, parameterChangedHandler);
if (!sceneBindings.hasCallback(parameter, parameterChangedHandler))
sceneBindings.addCallback(parameter, parameterChangedHandler);
if (meshBindings.propertyExists(parameter))
setParameter(parameter, meshBindings.getProperty(parameter));
else if (sceneBindings.propertyExists(parameter))
setParameter(parameter, sceneBindings.getProperty(parameter));
}
if (computeDepth)
{
_worldToScreen = sceneBindings.getProperty('worldToScreen') as Matrix4x4;
_localToWorld = meshBindings.getProperty('localToWorld') as Matrix4x4;
sceneBindings.addCallback('worldToScreen', transformChangedHandler);
meshBindings.addCallback('localToWorld', transformChangedHandler);
_invalidDepth = true;
}
}
public function apply(context : Context3DResource, previous : DrawCall) : uint
{
if (!_enabled)
return 0;
context.setColorMask(_colorMaskR, _colorMaskG, _colorMaskB, _colorMaskA)
.setProgramConstantsFromVector(PROGRAM_TYPE_VERTEX, 0, _vsConstants)
.setProgramConstantsFromVector(PROGRAM_TYPE_FRAGMENT, 0, _fsConstants);
var numTextures : uint = _fsTextures.length;
var maxTextures : uint = previous ? previous._fsTextures.length : NUM_TEXTURES;
var maxBuffers : uint = previous ? previous._numVertexComponents : NUM_VERTEX_BUFFERS;
var i : uint = 0;
// setup textures
for (i = 0; i < numTextures; ++i)
{
context.setTextureAt(
i,
(_fsTextures[i] as ITextureResource).getTexture(context)
);
}
while (i < maxTextures)
context.setTextureAt(i++, null);
// setup buffers
for (i = 0; i < _numVertexComponents; ++i)
{
context.setVertexBufferAt(
i,
(_vertexBuffers[i] as VertexBuffer3DResource).getVertexBuffer3D(context),
_offsets[i],
_formats[i]
);
}
while (i < maxBuffers)
context.setVertexBufferAt(i++, null);
// draw triangles
context.drawTriangles(
_indexBuffer.getIndexBuffer3D(context),
_firstIndex,
_numTriangles
);
return _numTriangles == -1 ? _indexBuffer.numIndices / 3 : _numTriangles;
}
public function setParameter(name : String, value : Object) : void
{
if (!_enabled)
{
_changes[name] = value;
return ;
}
var binding : IBinder = _bindings[name] as IBinder;
if (binding != null)
binding.set(_cpuConstants, _vsConstants, _fsConstants, _fsTextures, value);
}
private function parameterChangedHandler(dataBindings : DataBindings,
property : String,
oldValue : Object,
newValue : Object) : void
{
newValue !== null && setParameter(property, newValue);
}
private function transformChangedHandler(bindings : DataBindings,
property : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
if (property == 'worldToScreen')
_worldToScreen = newValue;
else if (property == 'localToWorld')
_localToWorld = newValue;
_invalidDepth = true;
}
}
}
|
fix DrawCall.setGeometry() accessing unavailable vertex shader input buffer mapping and causing null pointer exception
|
fix DrawCall.setGeometry() accessing unavailable vertex shader input buffer mapping and causing null pointer exception
|
ActionScript
|
mit
|
aerys/minko-as3
|
e0d75088c657be274b12ef0587041ac0d17a1d9d
|
src/asfac/src/com/thedevstop/asfac/AsFactory.as
|
src/asfac/src/com/thedevstop/asfac/AsFactory.as
|
package com.thedevstop.asfac
{
import avmplus.getQualifiedClassName;
import flash.errors.IllegalOperationError;
import flash.utils.describeType;
import flash.utils.Dictionary;
import flash.utils.getDefinitionByName;
/**
* The default AsFactory allows for registering instances, types, or callbacks.
*/
public class AsFactory
{
static public const DefaultScopeName:String = "";
private var _registrations:Dictionary;
private var _descriptions:Dictionary;
/**
* Constructs a new AsFactory.
*/
public function AsFactory()
{
_registrations = new Dictionary();
_descriptions = new Dictionary();
}
/**
* Registers a way of resolving a dependency when requested.
* @param instance How the dependency should be resolved. It can be either a Type, Instance, or Callback function.
* @param type The target type for which the instance should be returned at resolution time.
* @param scope The named string or Class scope for the registration.
* @param asSingleton If true, the resolved dependency will be cached and returned each time the type is resolved.
*/
public function register(instance:*, type:Class, scope:* = DefaultScopeName, asSingleton:Boolean=false):void
{
var scopeName:String = scope is Class
? getQualifiedClassName(scope)
: scope is String ? scope : getQualifiedClassName(scope.constructor);
if (instance is Class)
registerType(instance, type, scopeName, asSingleton);
else if (instance is Function)
registerCallback(instance, type, scopeName, asSingleton);
else
registerInstance(instance, type, scopeName);
}
/**
* Registers a concrete instance to be returned whenever the target type is requested.
* @param instance The concrete instance to be returned.
* @param type The target type for which the instance should be returned at resolution time.
* @param scopeName The named scope for the registration.
*/
private function registerInstance(instance:Object, type:Class, scopeName:String = DefaultScopeName):void
{
var returnInstance:Function = function():Object
{
return instance;
};
registerCallback(returnInstance, type, scopeName, false);
}
/**
* Registers a type to be returned whenever the target type is requested.
* @param instanceType The type to construct at resolution time.
* @param type The type being requested.
* @param asSingleton If true, only one instance will be created and returned on each request. If false (default), a new instance
* is created and returned at each resolution request.
*/
private function registerType(instanceType:Class, type:Class, scopeName:String=DefaultScopeName, asSingleton:Boolean=false):void
{
var resolveType:Function = function():Object
{
return resolveByClass(instanceType);
};
registerCallback(resolveType, type, scopeName, asSingleton);
}
/**
* Registers a callback to be executed, the result of which is returned whenever the target type is requested
* @param callback The callback to execute.
* @param type The type being requested.
* @param asSingleton If true, callback is only invoked once and the result is returned on each request. If false (default),
* callback is invoked on each resolution request.
*/
private function registerCallback(callback:Function, type:Class, scopeName:String = DefaultScopeName, asSingleton:Boolean=false):void
{
if (!type)
throw new IllegalOperationError("Type cannot be null when registering a callback");
validateCallback(callback);
var registrationsByScope:Dictionary = _registrations[type];
if (!registrationsByScope)
{
registrationsByScope = _registrations[type] = new Dictionary();
}
if (asSingleton)
registrationsByScope[scopeName] = (function(callback:Function, scopeName:String):Function
{
var instance:Object = null;
return function():Object
{
if (!instance)
instance = callback(this, scopeName);
return instance;
};
})(callback, scopeName);
else
registrationsByScope[scopeName] = callback;
}
/**
* Returns an instance for the target type, using prior registrations to fulfill constructor parameters.
* @param type The type being requested.
* @param scope The name or Class scope
* @return The resolved instance.
*/
public function resolve(type:Class, scope:* = DefaultScopeName):*
{
var registrationsByScope:Dictionary = _registrations[type];
var scopeName:String = scope is Class
? getQualifiedClassName(scope)
: scope is String ? scope : getQualifiedClassName(scope.constructor);
if (registrationsByScope)
{
if (registrationsByScope[scopeName])
return registrationsByScope[scopeName](this, scopeName);
else if (scopeName != DefaultScopeName)
throw new ArgumentError("Type being resolved has not been registered for scope named " + scopeName);
}
return resolveByClass(type);
}
/**
* Resolves the desired type using prior registrations.
* @param type The type being requested.
* @return The resolved instance.
*/
private function resolveByClass(type:Class):*
{
if (!type)
throw new IllegalOperationError("Type cannot be null when resolving.");
var typeDescription:Object = getTypeDescription(type);
if (!typeDescription)
throw new IllegalOperationError("Interface must be registered before it can be resolved.");
var parameters:Array = resolveConstructorParameters(typeDescription);
var instance:Object = createObject(type, parameters);
injectProperties(instance, typeDescription);
return instance;
}
/**
* Creates a new instance of the type, using the specified parameters as the constructor parameters.
* @param type The type being created.
* @param parameters The parameters to supply to the constructor.
* @return The new instance of type.
*/
private function createObject(type:Class, parameters:Array):*
{
switch (parameters.length)
{
case 0 : return new type();
case 1 : return new type(parameters[0]);
case 2 : return new type(parameters[0], parameters[1]);
case 3 : return new type(parameters[0], parameters[1], parameters[2]);
case 4 : return new type(parameters[0], parameters[1], parameters[2], parameters[3]);
case 5 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4]);
case 6 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5]);
case 7 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6]);
case 8 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7]);
case 9 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8]);
case 10 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9]);
case 11 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10]);
case 12 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11]);
case 13 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12]);
case 14 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12], parameters[13]);
case 15 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12], parameters[13], parameters[14]);
default : throw new Error("Too many constructor parameters for createObject");
}
}
/**
* Confirms that a callback is valid for registration. Currently the callback must accept no arguments, or a single AsFactory argument.
* @param callback The callback being tested.
*/
private function validateCallback(callback:Function):void
{
// TODO: How to check type?
if (callback.length != 0 && callback.length != 2)
throw new IllegalOperationError("Callback function must accept 0 or 2 arguments. The first is AsFactory and the second is scope name.");
}
/**
* Gets the class description for the type.
* @param type The class to be described.
* @return An object of constructor types and injectable properties.
*/
private function getTypeDescription(type:Class):Object
{
if (_descriptions[type] !== undefined)
return _descriptions[type];
return _descriptions[type] = buildTypeDescription(type);
}
/**
* Builds an optimized description of the type.
* @param type The type to be described.
* @return An optimized description of the constructor and injectable properties.
*/
private function buildTypeDescription(type:Class):Object
{
var typeDescription:Object = { constructorTypes:[], injectableProperties:[] };
var description:XML = describeType(type);
// Object does not extend class
if (description.factory.extendsClass.length() === 0 && type !== Object)
return null;
for each (var parameter:XML in description.factory.constructor.parameter)
{
if ([email protected]() != "false")
break;
var parameterType:Class = Class(getDefinitionByName([email protected]()));
typeDescription.constructorTypes.push(parameterType);
}
for each (var accessor:XML in description.factory.accessor)
{
if (shouldInjectAccessor(accessor))
{
var propertyType:Class = Class(getDefinitionByName([email protected]()));
typeDescription.injectableProperties.push( { name:[email protected](), type:propertyType } );
}
}
return typeDescription;
}
/**
* Determines whether the accessor should be injected.
* @param accessor An accessor node from a class description xml.
* @return True if the Inject metadata is present, otherwise false.
*/
private function shouldInjectAccessor(accessor:XML):Boolean
{
if (accessor.@access == "readwrite" ||
accessor.@access == "write")
{
for each (var metadata:XML in accessor.metadata)
{
if ([email protected]() == "Inject")
return true;
}
}
return false;
}
/**
* Resolves the non-optional parameters for a constructor.
* @param typeDescription The optimized description of the type.
* @return An array of objects to use as constructor arguments.
*/
private function resolveConstructorParameters(typeDescription:Object):Array
{
var parameters:Array = [];
for each (var parameterType:Class in typeDescription.constructorTypes)
parameters.push(resolve(parameterType));
return parameters;
}
/**
* Resolves the properties on the instance object that are marked 'Inject'.
* @param instance The object to be inspected.
* @param typeDescription The optimized description of the type.
*/
private function injectProperties(instance:Object, typeDescription:Object):void
{
for each (var injectableProperty:Object in typeDescription.injectableProperties)
instance[injectableProperty.name] = resolve(injectableProperty.type);
}
}
}
|
package com.thedevstop.asfac
{
import avmplus.getQualifiedClassName;
import flash.errors.IllegalOperationError;
import flash.utils.describeType;
import flash.utils.Dictionary;
import flash.utils.getDefinitionByName;
/**
* The default AsFactory allows for registering instances, types, or callbacks.
*/
public class AsFactory
{
static public const DefaultScopeName:String = "";
private var _registrations:Dictionary;
private var _descriptions:Dictionary;
/**
* Constructs a new AsFactory.
*/
public function AsFactory()
{
_registrations = new Dictionary();
_descriptions = new Dictionary();
}
/**
* Registers a way of resolving a dependency when requested.
* @param instance How the dependency should be resolved. It can be either a Type, Instance, or Callback function.
* @param type The target type for which the instance should be returned at resolution time.
* @param scope The named string or Class scope for the registration.
* @param asSingleton If true, the resolved dependency will be cached and returned each time the type is resolved.
*/
public function register(instance:*, type:Class, scope:* = DefaultScopeName, asSingleton:Boolean=false):void
{
var scopeName:String = scope is String
? scope
: getQualifiedClassName(scope);
if (instance is Class)
registerType(instance, type, scopeName, asSingleton);
else if (instance is Function)
registerCallback(instance, type, scopeName, asSingleton);
else
registerInstance(instance, type, scopeName);
}
/**
* Registers a concrete instance to be returned whenever the target type is requested.
* @param instance The concrete instance to be returned.
* @param type The target type for which the instance should be returned at resolution time.
* @param scopeName The named scope for the registration.
*/
private function registerInstance(instance:Object, type:Class, scopeName:String = DefaultScopeName):void
{
var returnInstance:Function = function():Object
{
return instance;
};
registerCallback(returnInstance, type, scopeName, false);
}
/**
* Registers a type to be returned whenever the target type is requested.
* @param instanceType The type to construct at resolution time.
* @param type The type being requested.
* @param asSingleton If true, only one instance will be created and returned on each request. If false (default), a new instance
* is created and returned at each resolution request.
*/
private function registerType(instanceType:Class, type:Class, scopeName:String=DefaultScopeName, asSingleton:Boolean=false):void
{
var resolveType:Function = function():Object
{
return resolveByClass(instanceType);
};
registerCallback(resolveType, type, scopeName, asSingleton);
}
/**
* Registers a callback to be executed, the result of which is returned whenever the target type is requested
* @param callback The callback to execute.
* @param type The type being requested.
* @param asSingleton If true, callback is only invoked once and the result is returned on each request. If false (default),
* callback is invoked on each resolution request.
*/
private function registerCallback(callback:Function, type:Class, scopeName:String = DefaultScopeName, asSingleton:Boolean=false):void
{
if (!type)
throw new IllegalOperationError("Type cannot be null when registering a callback");
validateCallback(callback);
var registrationsByScope:Dictionary = _registrations[type];
if (!registrationsByScope)
{
registrationsByScope = _registrations[type] = new Dictionary();
}
if (asSingleton)
registrationsByScope[scopeName] = (function(callback:Function, scopeName:String):Function
{
var instance:Object = null;
return function():Object
{
if (!instance)
instance = callback(this, scopeName);
return instance;
};
})(callback, scopeName);
else
registrationsByScope[scopeName] = callback;
}
/**
* Returns an instance for the target type, using prior registrations to fulfill constructor parameters.
* @param type The type being requested.
* @param scope The name or Class scope
* @return The resolved instance.
*/
public function resolve(type:Class, scope:* = DefaultScopeName):*
{
var registrationsByScope:Dictionary = _registrations[type];
var scopeName:String = scope is String
? scope
: getQualifiedClassName(scope);
if (registrationsByScope)
{
if (registrationsByScope[scopeName])
return registrationsByScope[scopeName](this, scopeName);
else if (scopeName != DefaultScopeName)
throw new ArgumentError("Type being resolved has not been registered for scope named " + scopeName);
}
return resolveByClass(type);
}
/**
* Resolves the desired type using prior registrations.
* @param type The type being requested.
* @return The resolved instance.
*/
private function resolveByClass(type:Class):*
{
if (!type)
throw new IllegalOperationError("Type cannot be null when resolving.");
var typeDescription:Object = getTypeDescription(type);
if (!typeDescription)
throw new IllegalOperationError("Interface must be registered before it can be resolved.");
var parameters:Array = resolveConstructorParameters(typeDescription);
var instance:Object = createObject(type, parameters);
injectProperties(instance, typeDescription);
return instance;
}
/**
* Creates a new instance of the type, using the specified parameters as the constructor parameters.
* @param type The type being created.
* @param parameters The parameters to supply to the constructor.
* @return The new instance of type.
*/
private function createObject(type:Class, parameters:Array):*
{
switch (parameters.length)
{
case 0 : return new type();
case 1 : return new type(parameters[0]);
case 2 : return new type(parameters[0], parameters[1]);
case 3 : return new type(parameters[0], parameters[1], parameters[2]);
case 4 : return new type(parameters[0], parameters[1], parameters[2], parameters[3]);
case 5 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4]);
case 6 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5]);
case 7 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6]);
case 8 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7]);
case 9 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8]);
case 10 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9]);
case 11 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10]);
case 12 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11]);
case 13 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12]);
case 14 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12], parameters[13]);
case 15 : return new type(parameters[0], parameters[1], parameters[2], parameters[3], parameters[4], parameters[5], parameters[6], parameters[7], parameters[8], parameters[9], parameters[10], parameters[11], parameters[12], parameters[13], parameters[14]);
default : throw new Error("Too many constructor parameters for createObject");
}
}
/**
* Confirms that a callback is valid for registration. Currently the callback must accept no arguments, or a single AsFactory argument.
* @param callback The callback being tested.
*/
private function validateCallback(callback:Function):void
{
// TODO: How to check type?
if (callback.length != 0 && callback.length != 2)
throw new IllegalOperationError("Callback function must accept 0 or 2 arguments. The first is AsFactory and the second is scope name.");
}
/**
* Gets the class description for the type.
* @param type The class to be described.
* @return An object of constructor types and injectable properties.
*/
private function getTypeDescription(type:Class):Object
{
if (_descriptions[type] !== undefined)
return _descriptions[type];
return _descriptions[type] = buildTypeDescription(type);
}
/**
* Builds an optimized description of the type.
* @param type The type to be described.
* @return An optimized description of the constructor and injectable properties.
*/
private function buildTypeDescription(type:Class):Object
{
var typeDescription:Object = { constructorTypes:[], injectableProperties:[] };
var description:XML = describeType(type);
// Object does not extend class
if (description.factory.extendsClass.length() === 0 && type !== Object)
return null;
for each (var parameter:XML in description.factory.constructor.parameter)
{
if ([email protected]() != "false")
break;
var parameterType:Class = Class(getDefinitionByName([email protected]()));
typeDescription.constructorTypes.push(parameterType);
}
for each (var accessor:XML in description.factory.accessor)
{
if (shouldInjectAccessor(accessor))
{
var propertyType:Class = Class(getDefinitionByName([email protected]()));
typeDescription.injectableProperties.push( { name:[email protected](), type:propertyType } );
}
}
return typeDescription;
}
/**
* Determines whether the accessor should be injected.
* @param accessor An accessor node from a class description xml.
* @return True if the Inject metadata is present, otherwise false.
*/
private function shouldInjectAccessor(accessor:XML):Boolean
{
if (accessor.@access == "readwrite" ||
accessor.@access == "write")
{
for each (var metadata:XML in accessor.metadata)
{
if ([email protected]() == "Inject")
return true;
}
}
return false;
}
/**
* Resolves the non-optional parameters for a constructor.
* @param typeDescription The optimized description of the type.
* @return An array of objects to use as constructor arguments.
*/
private function resolveConstructorParameters(typeDescription:Object):Array
{
var parameters:Array = [];
for each (var parameterType:Class in typeDescription.constructorTypes)
parameters.push(resolve(parameterType));
return parameters;
}
/**
* Resolves the properties on the instance object that are marked 'Inject'.
* @param instance The object to be inspected.
* @param typeDescription The optimized description of the type.
*/
private function injectProperties(instance:Object, typeDescription:Object):void
{
for each (var injectableProperty:Object in typeDescription.injectableProperties)
instance[injectableProperty.name] = resolve(injectableProperty.type);
}
}
}
|
Remove .constructor from scope name logic
|
Remove .constructor from scope name logic
|
ActionScript
|
mit
|
thedevstop/asfac
|
8d21c7c2e7b4622ca5b15a65dd6be11e9eaf1821
|
src/aerys/minko/scene/controller/mesh/MeshController.as
|
src/aerys/minko/scene/controller/mesh/MeshController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.math.Matrix4x4;
public final class MeshController extends AbstractController
{
private var _data : DataProvider;
private var _worldToLocal : Matrix4x4;
public function MeshController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_worldToLocal = new Matrix4x4();
targetAdded.add(targetAddedHandler);
}
private function targetAddedHandler(ctrl : MeshController,
target : Mesh) : void
{
target.added.add(addedHandler);
target.removed.add(removedHandler);
}
private function addedHandler(target : Mesh,
ancestor : Group) : void
{
if (!target.scene)
return ;
_data = new DataProvider(
null, target.name + '_transforms', DataProviderUsage.EXCLUSIVE
);
_data.setProperty('localToWorld', target.getLocalToWorldTransform());
_data.setProperty('worldToLocal', target.getWorldToLocalTransform(false, _worldToLocal));
target.bindings.addProvider(_data);
target.localToWorldTransformChanged.add(localToWorldChangedHandler);
}
private function removedHandler(target : Mesh,
ancestor : Group) : void
{
if (!ancestor.scene)
return ;
target.localToWorldTransformChanged.remove(localToWorldChangedHandler);
target.bindings.removeProvider(_data);
_data = null;
}
private function localToWorldChangedHandler(mesh : Mesh, localToWorld : Matrix4x4) : void
{
_data.setProperty('localToWorld', localToWorld);
mesh.getWorldToLocalTransform(false, _worldToLocal);
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.math.Matrix4x4;
public final class MeshController extends AbstractController
{
private var _data : DataProvider;
private var _worldToLocal : Matrix4x4;
public function MeshController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_worldToLocal = new Matrix4x4();
targetAdded.add(targetAddedHandler);
}
private function targetAddedHandler(ctrl : MeshController,
target : Mesh) : void
{
target.added.add(addedHandler);
target.removed.add(removedHandler);
}
private function addedHandler(target : Mesh,
ancestor : Group) : void
{
if (!target.scene)
return ;
_data = new DataProvider(
null, target.name + '_transforms', DataProviderUsage.EXCLUSIVE
);
_data.setProperty('localToWorld', target.getLocalToWorldTransform(true));
_data.setProperty('worldToLocal', target.getWorldToLocalTransform(false, _worldToLocal));
target.bindings.addProvider(_data);
target.localToWorldTransformChanged.add(localToWorldChangedHandler);
}
private function removedHandler(target : Mesh,
ancestor : Group) : void
{
if (!ancestor.scene)
return ;
target.localToWorldTransformChanged.remove(localToWorldChangedHandler);
target.bindings.removeProvider(_data);
_data.dispose();
_data = null;
}
private function localToWorldChangedHandler(mesh : Mesh, localToWorld : Matrix4x4) : void
{
_data.setProperty('localToWorld', mesh.getLocalToWorldTransform());
mesh.getWorldToLocalTransform(false, _worldToLocal);
}
}
}
|
fix big memory leak/performances leak because of trailing callbacks by calling DataProvider.dispose() in MeshController.removedHandler()
|
fix big memory leak/performances leak because of trailing callbacks by calling DataProvider.dispose() in MeshController.removedHandler()
|
ActionScript
|
mit
|
aerys/minko-as3
|
e81b57f4845bfb2b12f8a9ae7c56b4e71c27ccab
|
src/aerys/minko/scene/controller/animation/AnimationController.as
|
src/aerys/minko/scene/controller/animation/AnimationController.as
|
package aerys.minko.scene.controller.animation
{
import aerys.minko.scene.controller.*;
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.Signal;
import aerys.minko.type.animation.timeline.ITimeline;
import flash.display.BitmapData;
import flash.utils.getTimer;
/**
* The AnimationController uses timelines to animate properties of scene nodes.
*
* @author Jean-Marc Le Roux
*
*/
public class AnimationController extends EnterFrameController implements IAnimationController
{
private var _timelines : Vector.<ITimeline>;
private var _isPlaying : Boolean;
private var _updateOneTime : Boolean;
private var _loopBeginTime : int;
private var _loopEndTime : int;
private var _looping : Boolean;
private var _currentTime : int;
private var _totalTime : int;
private var _timeFunction : Function;
private var _labelNames : Vector.<String>;
private var _labelTimes : Vector.<Number>;
private var _lastTime : Number;
private var _looped : Signal;
private var _started : Signal;
private var _stopped : Signal;
public function get numLabels() : uint
{
return _labelNames.length;
}
public function get timeFunction() : Function
{
return _timeFunction;
}
public function set timeFunction(value : Function) : void
{
_timeFunction = value;
}
public function get numTimelines() : uint
{
return _timelines.length;
}
public function get started() : Signal
{
return _started;
}
public function get stopped() : Signal
{
return _stopped;
}
public function get looped() : Signal
{
return _looped;
}
public function get totalTime() : int
{
return _totalTime;
}
public function get looping() : Boolean
{
return _looping;
}
public function set looping(value : Boolean) : void
{
_looping = value;
}
public function get isPlaying() : Boolean
{
return _isPlaying;
}
public function set isPlaying(value : Boolean) : void
{
_isPlaying = value;
}
public function get currentTime() : int
{
return _currentTime;
}
public function AnimationController(timelines : Vector.<ITimeline>,
loop : Boolean = true)
{
super();
initialize(timelines, loop);
}
private function initialize(timelines : Vector.<ITimeline>,
loop : Boolean) : void
{
_timelines = timelines.slice();
_looping = loop;
_labelNames = new <String>[];
_labelTimes = new <Number>[];
_looped = new Signal('AnimationController.looped');
_started = new Signal('AnimationController.started');
_stopped = new Signal('AnimationController.stopped');
var numTimelines : uint = _timelines.length;
for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId)
if (_totalTime < _timelines[timelineId].duration)
_totalTime = _timelines[timelineId].duration;
setPlaybackWindow(0, _totalTime);
seek(0).play();
}
override public function clone() : AbstractController
{
return new AnimationController(_timelines.slice());
}
public function cloneTimelines() : void
{
var numTimelines : uint = _timelines.length;
for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId)
_timelines[timelineId] = (_timelines[timelineId] as ITimeline).clone();
}
public function getTimeline(index : uint = 0) : ITimeline
{
return _timelines[index];
}
public function seek(time : Object) : IAnimationController
{
var timeValue : uint = getAnimationTime(time);
if (timeValue < _loopBeginTime || timeValue > _loopEndTime)
throw new Error(
'Time value is outside of playback window. '
+'To reset playback window, call resetPlaybackWindow.'
);
_currentTime = timeValue;
return this;
}
public function play() : IAnimationController
{
_isPlaying = true;
_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
_started.execute(this);
return this;
}
public function stop() : IAnimationController
{
_isPlaying = false;
_updateOneTime = true;
_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
_stopped.execute(this);
return this;
}
public function setPlaybackWindow(beginTime : Object = null,
endTime : Object = null) : IAnimationController
{
_loopBeginTime = beginTime != null ? getAnimationTime(beginTime) : 0;
_loopEndTime = endTime != null ? getAnimationTime(endTime) : _totalTime;
if (_currentTime < _loopBeginTime || _currentTime > _loopEndTime)
_currentTime = _loopBeginTime;
return this;
}
public function resetPlaybackWindow() : IAnimationController
{
setPlaybackWindow();
return this;
}
private function getAnimationTime(time : Object) : uint
{
var timeValue : uint;
if (time is uint || time is int || time is Number)
{
timeValue = uint(time);
}
else if (time is String)
{
var labelCount : uint = _labelNames.length;
for (var labelId : uint = 0; labelId < labelCount; ++labelId)
if (_labelNames[labelId] == time)
timeValue = _labelTimes[labelId];
}
else
{
throw new Error('Invalid argument type: time must be Number or String');
}
return timeValue;
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
target : BitmapData,
time : Number) : void
{
if (updateOnTime(time))
{
_updateOneTime = false;
for (var j : uint = 0; j < numTargets; ++j)
{
var ctrlTarget : ISceneNode = getTarget(j);
if (ctrlTarget.root != scene)
continue ;
var numTimelines : int = _timelines.length;
var group : Group = target as Group;
for (var i : int = 0; i < numTimelines; ++i)
{
var timeline : ITimeline = _timelines[i] as ITimeline;
timeline.updateAt(
_currentTime % (timeline.duration + 1),
ctrlTarget
);
}
}
}
}
private function updateOnTime(time : Number) : Boolean
{
if (_isPlaying || _updateOneTime)
{
if (_timeFunction != null)
time = _timeFunction(time);
var deltaT : Number = time - _lastTime;
var lastCurrentTime : Number = _currentTime;
if (_isPlaying)
{
_currentTime = _loopBeginTime
+ (_currentTime + deltaT - _loopBeginTime)
% (_loopEndTime - _loopBeginTime);
}
if ((deltaT > 0 && lastCurrentTime > _currentTime)
|| (deltaT < 0 && (lastCurrentTime < _currentTime
|| _currentTime * lastCurrentTime < 0)))
{
if (_looping)
_looped.execute(this);
else
{
_currentTime = deltaT > 0 ? _totalTime : 0;
stop();
return true;
}
}
}
_lastTime = time;
return _isPlaying || _updateOneTime;
}
public function addLabel(name : String, time : Number) : IAnimationController
{
if (_labelNames.indexOf(name) >= 0)
throw new Error('A label with the same name already exists.');
_labelNames.push(name);
_labelTimes.push(time);
return this;
}
public function removeLabel(name : String) : IAnimationController
{
var index : int = _labelNames.indexOf(name);
if (index < 0)
throw new Error('The time label named \'' + name + '\' does not exist.');
var numLabels : uint = _labelNames.length - 1;
_labelNames[index] = _labelNames[numLabels];
_labelNames.length = numLabels;
_labelTimes[index] = _labelTimes[numLabels];
_labelTimes.length = numLabels;
return this;
}
public function getLabelName(index : uint) : String
{
return _labelNames[index];
}
public function getLabelTime(index : uint) : Number
{
return _labelTimes[index];
}
}
}
|
package aerys.minko.scene.controller.animation
{
import flash.display.BitmapData;
import flash.utils.getTimer;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.EnterFrameController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.Signal;
import aerys.minko.type.animation.timeline.ITimeline;
/**
* The AnimationController uses timelines to animate properties of scene nodes.
*
* @author Jean-Marc Le Roux
*
*/
public class AnimationController extends EnterFrameController implements IAnimationController
{
private var _timelines : Vector.<ITimeline>;
private var _isPlaying : Boolean;
private var _updateOneTime : Boolean;
private var _loopBeginTime : int;
private var _loopEndTime : int;
private var _looping : Boolean;
private var _currentTime : int;
private var _totalTime : int;
private var _timeFunction : Function;
private var _labelNames : Vector.<String>;
private var _labelTimes : Vector.<Number>;
private var _lastTime : Number;
private var _looped : Signal;
private var _started : Signal;
private var _stopped : Signal;
public function get numLabels() : uint
{
return _labelNames.length;
}
public function get timeFunction() : Function
{
return _timeFunction;
}
public function set timeFunction(value : Function) : void
{
_timeFunction = value;
}
public function get numTimelines() : uint
{
return _timelines.length;
}
public function get started() : Signal
{
return _started;
}
public function get stopped() : Signal
{
return _stopped;
}
public function get looped() : Signal
{
return _looped;
}
public function get totalTime() : int
{
return _totalTime;
}
public function get looping() : Boolean
{
return _looping;
}
public function set looping(value : Boolean) : void
{
_looping = value;
}
public function get isPlaying() : Boolean
{
return _isPlaying;
}
public function set isPlaying(value : Boolean) : void
{
_isPlaying = value;
}
public function get currentTime() : int
{
return _currentTime;
}
public function AnimationController(timelines : Vector.<ITimeline>,
loop : Boolean = true)
{
super();
initialize(timelines, loop);
}
private function initialize(timelines : Vector.<ITimeline>,
loop : Boolean) : void
{
_timelines = timelines.slice();
_looping = loop;
_labelNames = new <String>[];
_labelTimes = new <Number>[];
_looped = new Signal('AnimationController.looped');
_started = new Signal('AnimationController.started');
_stopped = new Signal('AnimationController.stopped');
var numTimelines : uint = _timelines.length;
for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId)
if (_totalTime < _timelines[timelineId].duration)
_totalTime = _timelines[timelineId].duration;
setPlaybackWindow(0, _totalTime);
seek(0).play();
}
override public function clone() : AbstractController
{
return new AnimationController(_timelines.slice());
}
public function cloneTimelines() : void
{
var numTimelines : uint = _timelines.length;
for (var timelineId : uint = 0; timelineId < numTimelines; ++timelineId)
_timelines[timelineId] = (_timelines[timelineId] as ITimeline).clone();
}
public function getTimeline(index : uint = 0) : ITimeline
{
return _timelines[index];
}
public function seek(time : Object) : IAnimationController
{
var timeValue : uint = getAnimationTime(time);
if (timeValue < _loopBeginTime || timeValue > _loopEndTime)
throw new Error(
'Time value is outside of playback window. '
+'To reset playback window, call resetPlaybackWindow.'
);
_currentTime = timeValue;
return this;
}
public function play() : IAnimationController
{
_isPlaying = true;
_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
_started.execute(this);
return this;
}
public function stop() : IAnimationController
{
_isPlaying = false;
_updateOneTime = true;
_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
_stopped.execute(this);
return this;
}
public function setPlaybackWindow(beginTime : Object = null,
endTime : Object = null) : IAnimationController
{
_loopBeginTime = beginTime != null ? getAnimationTime(beginTime) : 0;
_loopEndTime = endTime != null ? getAnimationTime(endTime) : _totalTime;
if (_currentTime < _loopBeginTime || _currentTime > _loopEndTime)
_currentTime = _loopBeginTime;
return this;
}
public function resetPlaybackWindow() : IAnimationController
{
setPlaybackWindow();
return this;
}
private function getAnimationTime(time : Object) : uint
{
var timeValue : uint;
if (time is uint || time is int || time is Number)
{
timeValue = uint(time);
}
else if (time is String)
{
var labelCount : uint = _labelNames.length;
for (var labelId : uint = 0; labelId < labelCount; ++labelId)
if (_labelNames[labelId] == time)
timeValue = _labelTimes[labelId];
}
else
{
throw new Error('Invalid argument type: time must be Number or String');
}
return timeValue;
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
target : BitmapData,
time : Number) : void
{
if (updateOnTime(time))
{
_updateOneTime = false;
for (var j : uint = 0; j < numTargets; ++j)
{
var ctrlTarget : ISceneNode = getTarget(j);
if (ctrlTarget.root != scene)
continue ;
var numTimelines : int = _timelines.length;
var group : Group = target as Group;
for (var i : int = 0; i < numTimelines; ++i)
{
var timeline : ITimeline = _timelines[i] as ITimeline;
timeline.updateAt(
_currentTime % (timeline.duration + 1),
ctrlTarget
);
}
}
}
}
private function updateOnTime(time : Number) : Boolean
{
if (_isPlaying || _updateOneTime)
{
if (_timeFunction != null)
time = _timeFunction(time);
var deltaT : Number = time - _lastTime;
var lastCurrentTime : Number = _currentTime;
if (_isPlaying)
{
_currentTime = _loopBeginTime
+ (_currentTime + deltaT - _loopBeginTime)
% (_loopEndTime - _loopBeginTime);
}
if ((deltaT > 0 && lastCurrentTime > _currentTime)
|| (deltaT < 0 && (lastCurrentTime < _currentTime
|| _currentTime * lastCurrentTime < 0)))
{
if (_looping)
_looped.execute(this);
else
{
_currentTime = deltaT > 0 ? _totalTime : 0;
stop();
return true;
}
}
}
_lastTime = time;
return _isPlaying || _updateOneTime;
}
public function addLabel(name : String, time : Number) : IAnimationController
{
if (_labelNames.indexOf(name) >= 0)
throw new Error('A label with the same name already exists.');
_labelNames.push(name);
_labelTimes.push(time);
return this;
}
public function changeLabel(oldName : String, newName : String) : IAnimationController
{
var index : int = _labelNames.indexOf(oldName);
if (index < 0)
throw new Error('The time label named \'' + oldName + '\' does not exist.');
_labelNames[index] = newName;
return this;
}
public function setTimeForLabel(name : String, newTime : Number) : IAnimationController
{
var index : int = _labelNames.indexOf(name);
if (index < 0)
throw new Error('The time label named \'' + name + '\' does not exist.');
_labelTimes[index] = newTime;
return this;
}
public function removeLabel(name : String) : IAnimationController
{
var index : int = _labelNames.indexOf(name);
if (index < 0)
throw new Error('The time label named \'' + name + '\' does not exist.');
var numLabels : uint = _labelNames.length - 1;
_labelNames[index] = _labelNames[numLabels];
_labelNames.length = numLabels;
_labelTimes[index] = _labelTimes[numLabels];
_labelTimes.length = numLabels;
return this;
}
public function getLabelName(index : uint) : String
{
return _labelNames[index];
}
public function getLabelTime(index : uint) : Number
{
return _labelTimes[index];
}
}
}
|
Add function to rename or change a timelabel
|
Add function to rename or change a timelabel
|
ActionScript
|
mit
|
aerys/minko-as3
|
2eb5dd0003117497575d2c7e50a567edc8ca4d64
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
private var _computedVisibility : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_frustumCulling = value;
testCulling();
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return frustumCulling == FrustumCulling.DISABLED || _computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
mesh.visibilityChanged.add(visiblityChangedHandler);
mesh.parent.computedVisibilityChanged.add(visiblityChangedHandler);
mesh.removed.add(meshRemovedHandler);
}
private function meshRemovedHandler(mesh : Mesh, ancestor : Group) : void
{
if (!mesh.parent)
ancestor.computedVisibilityChanged.remove(visiblityChangedHandler);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.visibilityChanged.remove(visiblityChangedHandler);
mesh.removed.remove(meshRemovedHandler);
if (mesh.parent)
mesh.parent.computedVisibilityChanged.remove(visiblityChangedHandler);
}
private function visiblityChangedHandler(node : ISceneNode, visibility : Boolean) : void
{
_computedVisibility = _mesh.visible && _mesh.parent.computedVisibility
&& _insideFrustum;
_mesh.computedVisibilityChanged.execute(_mesh, _computedVisibility);
}
private function worldToScreenChangedHandler(bindings : DataBindings,
propertyName : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (culling != FrustumCulling.DISABLED && _mesh && _mesh.geometry.boundingBox
&& _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();;
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
private var _computedVisibility : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_frustumCulling = value;
testCulling();
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _frustumCulling == FrustumCulling.DISABLED || _computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
mesh.visibilityChanged.add(visiblityChangedHandler);
mesh.parent.computedVisibilityChanged.add(visiblityChangedHandler);
mesh.removed.add(meshRemovedHandler);
}
private function meshRemovedHandler(mesh : Mesh, ancestor : Group) : void
{
if (!mesh.parent)
ancestor.computedVisibilityChanged.remove(visiblityChangedHandler);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.visibilityChanged.remove(visiblityChangedHandler);
mesh.removed.remove(meshRemovedHandler);
if (mesh.parent)
mesh.parent.computedVisibilityChanged.remove(visiblityChangedHandler);
}
private function visiblityChangedHandler(node : ISceneNode, visibility : Boolean) : void
{
_computedVisibility = _mesh.visible && _mesh.parent.computedVisibility
&& _insideFrustum;
_mesh.computedVisibilityChanged.execute(_mesh, _computedVisibility);
}
private function worldToScreenChangedHandler(bindings : DataBindings,
propertyName : String,
oldValue : Matrix4x4,
newValue : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (culling != FrustumCulling.DISABLED && _mesh && _mesh.geometry.boundingBox
&& _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();;
}
}
}
|
use _frustumCulling private property directly instead of protected frustumCulling protected getter for better performances
|
use _frustumCulling private property directly instead of protected frustumCulling protected getter for better performances
|
ActionScript
|
mit
|
aerys/minko-as3
|
4b4a996d8544a121e5d6d9ba67c6abda2f5922ce
|
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.events.ProgressEvent;
import flash.utils.ByteArray;
import flump.executor.Executor;
import flump.executor.Future;
import flump.mold.LibraryMold;
import react.Signal;
/**
* 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);
}
/**
* Dispatched when a ProgressEvent is received on a URL load of a Zip archive.
*
* Signal parameters:
* * event :flash.events.ProgressEvent
*/
public const urlLoadProgressed :Signal = new Signal(ProgressEvent);
/**
* Dispatched when a file is found in the Zip archive that is not recognized by Flump.
*
* Dispatched Object has the following named properties:
* * name :String - the filename in the archive
* * bytes :ByteArray - the content of the file
*/
public const fileLoaded :Signal = new Signal(Object);
/**
* Dispatched when the library mold has been read from the archive.
*/
public const libraryMoldLoaded :Signal = new Signal(LibraryMold);
/**
* Dispatched when the bytes for an ATF atlas have been read from the archive.
*
* Dispatched Object has the following named properties:
* * name :String - the filename of the atlas
* * bytes :ByteArray - the content of the atlas
*/
public const atfAtlasLoaded :Signal = new Signal(Object);
/**
* Dispatched when a PNG atlas has been loaded and decoded from the archive. Changes made to
* the loaded png in a signal listener will affect the final rendered texture.
*
* NOTE: If Starling is not configured to handle lost context (Starling.handleLostContext),
* the Bitmap dispatched to this signal will be disposed immediately after the dispatch, and
* will become useless.
*
* Dispatched Object has the following named properties:
* * atlas :AtlasMold - The loaded atlas.
* * image :LoadedImage - the decoded image.
*/
public const pngAtlasLoaded :Signal = new Signal(Object);
/**
* 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;
}
public function get scaleFactor () :Number {
return _scaleFactor;
}
/**
* 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;
}
public function get generateMipMaps () :Boolean {
return _generateMipMaps;
}
/**
* Sets the CreatorFactory instance used for this loader.
*/
public function setCreatorFactory (factory :CreatorFactory) :LibraryLoader {
_creatorFactory = factory;
return this;
}
public function get creatorFactory () :CreatorFactory {
if (_creatorFactory == null) {
_creatorFactory = new CreatorFactoryImpl();
}
return _creatorFactory;
}
/**
* 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, this).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, this).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;
protected var _creatorFactory :CreatorFactory;
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.display {
import flash.events.ProgressEvent;
import flash.utils.ByteArray;
import flump.executor.Executor;
import flump.executor.Future;
import flump.mold.LibraryMold;
import react.Signal;
/**
* 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);
}
/**
* Dispatched when a ProgressEvent is received on a URL load of a Zip archive.
*
* Signal parameters:
* * event :flash.events.ProgressEvent
*/
public const urlLoadProgressed :Signal = new Signal(ProgressEvent);
/**
* Dispatched when a file is found in the Zip archive that is not recognized by Flump.
*
* Dispatched Object has the following named properties:
* * name :String - the filename in the archive
* * bytes :ByteArray - the content of the file
*/
public const fileLoaded :Signal = new Signal(Object);
/**
* Dispatched when the library mold has been read from the archive.
*/
public const libraryMoldLoaded :Signal = new Signal(LibraryMold);
/**
* Dispatched when the bytes for an ATF atlas have been read from the archive.
*
* Dispatched Object has the following named properties:
* * name :String - the filename of the atlas
* * bytes :ByteArray - the content of the atlas
*/
public const atfAtlasLoaded :Signal = new Signal(Object);
/**
* Dispatched when a PNG atlas has been loaded and decoded from the archive. Changes made to
* the loaded png in a signal listener will affect the final rendered texture.
*
* NOTE: If Starling is not configured to handle lost context (Starling.handleLostContext),
* the Bitmap dispatched to this signal will be disposed immediately after the dispatch, and
* will become useless.
*
* Dispatched Object has the following named properties:
* * atlas :AtlasMold - The loaded atlas.
* * image :LoadedImage - the decoded image.
*/
public const pngAtlasLoaded :Signal = new Signal(Object);
/**
* 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;
}
public function get scaleFactor () :Number {
return _scaleFactor;
}
/**
* 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;
}
public function get generateMipMaps () :Boolean {
return _generateMipMaps;
}
/**
* Sets the CreatorFactory instance used for this loader.
*/
public function setCreatorFactory (factory :CreatorFactory) :LibraryLoader {
_creatorFactory = factory;
return this;
}
public function get creatorFactory () :CreatorFactory {
if (_creatorFactory == null) {
_creatorFactory = new CreatorFactoryImpl();
}
return _creatorFactory;
}
/**
* 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, this).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, this).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;
protected var _creatorFactory :CreatorFactory;
}
}
|
Fix doc comments.
|
Fix doc comments.
|
ActionScript
|
mit
|
tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump
|
814950e456dff49edb7e890bc6f57fcf7508cfbc
|
src/jp/promotal/ssplayer/starling/SSSPlayer.as
|
src/jp/promotal/ssplayer/starling/SSSPlayer.as
|
package jp.promotal.ssplayer.starling {
import flash.geom.Point;
import jp.promotal.ssplayer.data.SSModel;
import jp.promotal.ssplayer.data.SSPartAnime;
import jp.promotal.ssplayer.data.SSProject;
import jp.promotal.ssplayer.data.SSAnime;
import jp.promotal.ssplayer.data.SSPart;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
public class SSSPlayer extends Sprite {
public static const VERSION:String = "0.0.1";
private var project:SSProject;
private var model:SSModel;
private var _anime:SSAnime;
public function get anime():SSAnime {
return this._anime;
}
private var _currentFrame:Number;
public function get currentFrame():Number {
return this._currentFrame;
}
public function set currentFrame(value:Number):void {
this._currentFrame = value;
this.updateParts();
}
private var _partPlayers:Vector.<SSSPartPlayer>;
public function get partPlayers():Vector.<SSSPartPlayer> {
return this._partPlayers.concat();
}
private var _isPlaying:Boolean = false;
public function get isPlaying():Boolean {
return this._isPlaying;
}
public function set isPlaying(value:Boolean):void {
if (value == this._isPlaying) {
return;
}
if (value) {
this.addEventListener(Event.ENTER_FRAME, this.onEnterFrame);
} else {
this.removeEventListener(Event.ENTER_FRAME, this.onEnterFrame);
}
this._isPlaying = value;
}
private var _loop:Boolean = true;
public function get loop():Boolean {
return this._loop;
}
public function set loop(value:Boolean):void {
this._loop = value;
}
private var _withFlatten:Boolean = false;
public function get withFlatten():Boolean {
return this._withFlatten;
}
public function set withFlatten(value:Boolean):void {
if (value == this._withFlatten) {
return;
}
this._withFlatten = value;
if (value) {
this.flatten();
} else {
this.unflatten();
}
}
public function set color(value:uint):void {
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
partPlayer.color = value;
}
}
public function SSSPlayer(project:SSProject) {
super();
this.project = project;
}
public function setAnime(name:String):SSSPlayer {
this.model = this.project.modelForAnime(name);
this._anime = this.project.anime(name);
this.prepareChildren();
this._currentFrame = 0;
this.updateParts();
return this;
}
public function startAnime(name:String):SSSPlayer {
this.setAnime(name);
this.isPlaying = true;
return this;
}
public function play():void {
this.isPlaying = true;
}
public function stop():void {
this.isPlaying = false;
}
private function onEnterFrame(event:Event):void {
if (++this._currentFrame >= this._anime.frameCount) {
if (this._loop) {
this._currentFrame = 0;
} else {
this._currentFrame--;
this.stop();
}
this.dispatchEventWith(Event.COMPLETE);
}
this.updateParts();
}
private function prepareChildren():void {
this.removeChildren();
this._partPlayers = new Vector.<SSSPartPlayer>();
for each (var part:SSPart in this.model.parts) {
var partAnime:SSPartAnime = this._anime.partAnimes[part.name];
var parentPartPlayer:SSSPartPlayer = null;
if (part.parentIndex > -1) {
parentPartPlayer = this._partPlayers[part.parentIndex];
}
var partPlayer:SSSPartPlayer = new SSSPartPlayer(this.project, this.model, part, partAnime, parentPartPlayer);
this.addChild(partPlayer);
this._partPlayers.push(partPlayer);
}
}
private function updateParts():void {
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
partPlayer.currentFrame = this._currentFrame;
}
if (this._withFlatten) {
this.flatten();
}
}
public function partPlayerAt(x:Number, y:Number, forTouch:Boolean = false):SSSPartPlayer {
var touchable:Boolean = this.touchable;
this.touchable = true;
var hitObject:DisplayObject = this.hitTest(new Point(x, y), forTouch);
this.touchable = touchable;
if (!hitObject) {
return null;
}
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
if (hitObject.parent == partPlayer) {
return partPlayer;
}
}
return null;
}
public function partNameAt(x:Number, y:Number, forTouch:Boolean = false):String {
var partPlayer:SSSPartPlayer = this.partPlayerAt(x, y, forTouch);
return partPlayer ? partPlayer.name : null;
}
}
}
|
package jp.promotal.ssplayer.starling {
import flash.geom.Point;
import jp.promotal.ssplayer.data.SSModel;
import jp.promotal.ssplayer.data.SSPartAnime;
import jp.promotal.ssplayer.data.SSProject;
import jp.promotal.ssplayer.data.SSAnime;
import jp.promotal.ssplayer.data.SSPart;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
public class SSSPlayer extends Sprite {
public static const VERSION:String = "0.1.0";
private var project:SSProject;
private var model:SSModel;
private var _anime:SSAnime;
public function get anime():SSAnime {
return this._anime;
}
private var _currentFrame:Number;
public function get currentFrame():Number {
return this._currentFrame;
}
public function set currentFrame(value:Number):void {
this._currentFrame = value;
this.updateParts();
}
private var _partPlayers:Vector.<SSSPartPlayer>;
public function get partPlayers():Vector.<SSSPartPlayer> {
return this._partPlayers.concat();
}
private var _isPlaying:Boolean = false;
public function get isPlaying():Boolean {
return this._isPlaying;
}
public function set isPlaying(value:Boolean):void {
if (value == this._isPlaying) {
return;
}
if (value) {
this.addEventListener(Event.ENTER_FRAME, this.onEnterFrame);
} else {
this.removeEventListener(Event.ENTER_FRAME, this.onEnterFrame);
}
this._isPlaying = value;
}
private var _loop:Boolean = true;
public function get loop():Boolean {
return this._loop;
}
public function set loop(value:Boolean):void {
this._loop = value;
}
private var _withFlatten:Boolean = false;
public function get withFlatten():Boolean {
return this._withFlatten;
}
public function set withFlatten(value:Boolean):void {
if (value == this._withFlatten) {
return;
}
this._withFlatten = value;
if (value) {
this.flatten();
} else {
this.unflatten();
}
}
public function set color(value:uint):void {
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
partPlayer.color = value;
}
}
public function SSSPlayer(project:SSProject) {
super();
this.project = project;
}
public function setAnime(name:String):SSSPlayer {
this.model = this.project.modelForAnime(name);
this._anime = this.project.anime(name);
this.prepareChildren();
this._currentFrame = 0;
this.updateParts();
return this;
}
public function startAnime(name:String):SSSPlayer {
this.setAnime(name);
this.isPlaying = true;
return this;
}
public function play():void {
this.isPlaying = true;
}
public function stop():void {
this.isPlaying = false;
}
private function onEnterFrame(event:Event):void {
if (++this._currentFrame >= this._anime.frameCount) {
if (this._loop) {
this._currentFrame = 0;
} else {
this._currentFrame--;
this.stop();
}
this.dispatchEventWith(Event.COMPLETE);
}
this.updateParts();
}
private function prepareChildren():void {
this.removeChildren();
this._partPlayers = new Vector.<SSSPartPlayer>();
for each (var part:SSPart in this.model.parts) {
var partAnime:SSPartAnime = this._anime.partAnimes[part.name];
var parentPartPlayer:SSSPartPlayer = null;
if (part.parentIndex > -1) {
parentPartPlayer = this._partPlayers[part.parentIndex];
}
var partPlayer:SSSPartPlayer = new SSSPartPlayer(this.project, this.model, part, partAnime, parentPartPlayer);
this.addChild(partPlayer);
this._partPlayers.push(partPlayer);
}
}
private function updateParts():void {
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
partPlayer.currentFrame = this._currentFrame;
}
if (this._withFlatten) {
this.flatten();
}
}
public function partPlayerAt(x:Number, y:Number, forTouch:Boolean = false):SSSPartPlayer {
var touchable:Boolean = this.touchable;
this.touchable = true;
var hitObject:DisplayObject = this.hitTest(new Point(x, y), forTouch);
this.touchable = touchable;
if (!hitObject) {
return null;
}
for each (var partPlayer:SSSPartPlayer in this._partPlayers) {
if (hitObject.parent == partPlayer) {
return partPlayer;
}
}
return null;
}
public function partNameAt(x:Number, y:Number, forTouch:Boolean = false):String {
var partPlayer:SSSPartPlayer = this.partPlayerAt(x, y, forTouch);
return partPlayer ? partPlayer.name : null;
}
}
}
|
bump version
|
bump version
|
ActionScript
|
bsd-2-clause
|
promotal/SS5Player,promotal/SS5Player
|
8dbd0390745e03134ff084d1514a9818e1557ca6
|
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.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;
}
}
}
|
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 const INDEX_LIMIT : uint = 5242;
public static const VERTEX_LIMIT : uint = 6553;
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 : Vector.<uint>,
outVertices : Vector.<ByteArray>,
outIndices : Vector.<ByteArray>,
bytesPerVertex : uint = 12) : void
{
var inVerticesStartPosition : uint = inVertices.position;
var numVertices : uint = inVertices.bytesAvailable / bytesPerVertex;
var numIndices : int = inIndices.length;
if (numIndices < INDEX_LIMIT && numVertices < VERTEX_LIMIT)
{
var indices : ByteArray = new ByteArray();
indices.endian = Endian.LITTLE_ENDIAN;
for (var i : uint = 0; i < numIndices; ++i)
indices.writeShort(inIndices[i]);
indices.position = 0;
outVertices.push(inVertices);
outIndices.push(indices);
return;
}
var totalUsedIndices : int = 0;
while (numIndices > 0)
{
var indexDataLength : uint = numIndices;
// 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)
{
oldVertexIds[localVertexId] = inIndices[uint(totalUsedIndices + usedIndicesCount + localVertexId)];
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;
}
totalUsedIndices += usedIndicesCount;
numIndices -= usedIndicesCount;
partialVertexData.position = 0;
outVertices.push(partialVertexData);
partialIndexData.position = 0;
outIndices.push(partialIndexData);
}
inVertices.position = inVerticesStartPosition;
}
/**
* 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 -= 2;
indexData.writeShort(oldVertexIdToNewVertexId[index]);
}
indexData.position = indexDataStartPosition;
}
}
}
|
fix GeometrySanitizer.splitBuffers() to work on Vector.<uint> instead of a ByteArray of shorts to allow indices > 65535
|
fix GeometrySanitizer.splitBuffers() to work on Vector.<uint> instead of a ByteArray of shorts to allow indices > 65535
|
ActionScript
|
mit
|
aerys/minko-as3
|
241466168c924bb156437760d9a431fa4001b5e8
|
src/org/mangui/hls/controller/LevelController.as
|
src/org/mangui/hls/controller/LevelController.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.constant.HLSMaxLevelCappingMode;
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.Level;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that manages auto level selection
*
* this is an implementation based on Serial segment fetching method from
* http://www.cs.tut.fi/~moncef/publications/rate-adaptation-IC-2011.pdf
*/
public class LevelController {
/** Reference to the HLS controller. **/
private var _hls : HLS;
/** switch up threshold **/
private var _switchup : Vector.<Number> = null;
/** switch down threshold **/
private var _switchdown : Vector.<Number> = null;
/** bitrate array **/
private var _bitrate : Vector.<uint> = null;
/** vector of levels with unique dimension with highest bandwidth **/
private var _maxUniqueLevels : Vector.<Level> = null;
/** nb level **/
private var _nbLevel : int = 0;
private var _lastSegmentDuration : Number;
private var _lastFetchDuration : Number;
private var lastBandwidth : int;
private var _autoLevelCapping : int;
private var _startLevel : int = -1;
private var _fpsController : FPSController;
/** Create the loader. **/
public function LevelController(hls : HLS) : void {
_hls = hls;
_fpsController = new FPSController(hls);
/* low priority listener, so that other listeners with default priority
could seamlessly set hls.startLevel in their HLSEvent.MANIFEST_PARSED listener */
_hls.addEventListener(HLSEvent.MANIFEST_PARSED, _manifestParsedHandler, false, int.MIN_VALUE);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOAD_EMERGENCY_ABORTED, _fragmentLoadedHandler);
}
;
public function dispose() : void {
_fpsController.dispose();
_fpsController = null;
_hls.removeEventListener(HLSEvent.MANIFEST_PARSED, _manifestParsedHandler);
_hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
_hls.removeEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler);
_hls.removeEventListener(HLSEvent.FRAGMENT_LOAD_EMERGENCY_ABORTED, _fragmentLoadedHandler);
}
private function _fragmentLoadedHandler(event : HLSEvent) : void {
var metrics : HLSLoadMetrics = event.loadMetrics;
// only monitor main fragment metrics for level switching
if(metrics.type == HLSLoaderTypes.FRAGMENT_MAIN) {
lastBandwidth = metrics.bandwidth;
_lastSegmentDuration = metrics.duration;
_lastFetchDuration = metrics.processing_duration;
}
}
private function _manifestParsedHandler(event : HLSEvent) : void {
if(HLSSettings.autoStartLoad) {
// upon manifest parsed event, trigger a level switch to load startLevel playlist
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, _hls.startLevel));
}
}
private function _manifestLoadedHandler(event : HLSEvent) : void {
var levels : Vector.<Level> = event.levels;
var maxswitchup : Number = 0;
var minswitchdwown : Number = Number.MAX_VALUE;
_nbLevel = levels.length;
_bitrate = new Vector.<uint>(_nbLevel, true);
_switchup = new Vector.<Number>(_nbLevel, true);
_switchdown = new Vector.<Number>(_nbLevel, true);
_autoLevelCapping = -1;
_lastSegmentDuration = 0;
_lastFetchDuration = 0;
lastBandwidth = 0;
var i : int;
for (i = 0; i < _nbLevel; i++) {
_bitrate[i] = levels[i].bitrate;
}
for (i = 0; i < _nbLevel - 1; i++) {
_switchup[i] = (_bitrate[i + 1] - _bitrate[i]) / _bitrate[i];
maxswitchup = Math.max(maxswitchup, _switchup[i]);
}
for (i = 0; i < _nbLevel - 1; i++) {
_switchup[i] = Math.min(maxswitchup, 2 * _switchup[i]);
CONFIG::LOGGING {
Log.debug("_switchup[" + i + "]=" + _switchup[i]);
}
}
for (i = 1; i < _nbLevel; i++) {
_switchdown[i] = (_bitrate[i] - _bitrate[i - 1]) / _bitrate[i];
minswitchdwown = Math.min(minswitchdwown, _switchdown[i]);
}
for (i = 1; i < _nbLevel; i++) {
_switchdown[i] = Math.max(2 * minswitchdwown, _switchdown[i]);
CONFIG::LOGGING {
Log.debug("_switchdown[" + i + "]=" + _switchdown[i]);
}
}
if (HLSSettings.capLevelToStage) {
_maxUniqueLevels = _maxLevelsWithUniqueDimensions;
}
}
;
public function getbestlevel(downloadBandwidth : int) : int {
var max_level : int = _maxLevel;
for (var i : int = max_level; i >= 0; i--) {
if (_bitrate[i] <= downloadBandwidth) {
return i;
}
}
return 0;
}
private function get _maxLevelsWithUniqueDimensions() : Vector.<Level> {
var filter : Function = function(l : Level, i : int, v : Vector.<Level>) : Boolean {
if (l.width > 0 && l.height > 0) {
if (i + 1 < v.length) {
var nextLevel : Level = v[i + 1];
if (l.width != nextLevel.width && l.height != nextLevel.height) {
return true;
}
} else {
return true;
}
}
return false;
};
return _hls.levels.filter(filter);
}
/** Return the capping/max level value that could be used by automatic level selection algorithm **/
public function get autoLevelCapping() : int {
return _autoLevelCapping;
}
/** set the capping/max level value that could be used by automatic level selection algorithm **/
public function set autoLevelCapping(newLevel : int) : void {
_autoLevelCapping = newLevel;
}
private function get _maxLevel() : int {
// if set, _autoLevelCapping takes precedence
if(_autoLevelCapping >= 0) {
return Math.min(_nbLevel - 1, _autoLevelCapping);
} else if (HLSSettings.capLevelToStage) {
var maxLevelsCount : int = _maxUniqueLevels.length;
if (_hls.stage && maxLevelsCount) {
var maxLevel : Level = this._maxUniqueLevels[0], maxLevelIdx : int = maxLevel.index, sWidth : Number = this._hls.stage.stageWidth, sHeight : Number = this._hls.stage.stageHeight, lWidth : int, lHeight : int, i : int;
switch (HLSSettings.maxLevelCappingMode) {
case HLSMaxLevelCappingMode.UPSCALE:
for (i = maxLevelsCount - 1; i >= 0; i--) {
maxLevel = this._maxUniqueLevels[i];
maxLevelIdx = maxLevel.index;
lWidth = maxLevel.width;
lHeight = maxLevel.height;
CONFIG::LOGGING {
Log.debug("stage size: " + sWidth + "x" + sHeight + " ,level" + maxLevelIdx + " size: " + lWidth + "x" + lHeight);
}
if (sWidth >= lWidth || sHeight >= lHeight) {
break;
// from for loop
}
}
break;
case HLSMaxLevelCappingMode.DOWNSCALE:
for (i = 0; i < maxLevelsCount; i++) {
maxLevel = this._maxUniqueLevels[i];
maxLevelIdx = maxLevel.index;
lWidth = maxLevel.width;
lHeight = maxLevel.height;
CONFIG::LOGGING {
Log.debug("stage size: " + sWidth + "x" + sHeight + " ,level" + maxLevelIdx + " size: " + lWidth + "x" + lHeight);
}
if (sWidth <= lWidth || sHeight <= lHeight) {
break;
// from for loop
}
}
break;
}
CONFIG::LOGGING {
Log.debug("max capped level idx: " + maxLevelIdx);
}
}
return maxLevelIdx;
} else {
return _nbLevel - 1;
}
}
/** Update the quality level for the next fragment load. **/
public function getnextlevel(current_level : int, buffer : Number) : int {
if (_lastFetchDuration == 0 || _lastSegmentDuration == 0) {
return 0;
}
/* rsft : remaining segment fetch time : available time to fetch next segment
it depends on the current playback timestamp , the timestamp of the first frame of the next segment
and TBMT, indicating a desired latency between the time instant to receive the last byte of a
segment to the playback of the first media frame of a segment
buffer is start time of next segment
TBMT is the buffer size we need to ensure (we need at least 2 segments buffered */
var rsft : Number = 1000 * buffer - 2 * _lastFetchDuration;
var sftm : Number = Math.min(_lastSegmentDuration, rsft) / _lastFetchDuration;
var max_level : Number = _maxLevel;
var switch_to_level : int = current_level;
// CONFIG::LOGGING {
// Log.info("rsft:" + rsft);
// Log.info("sftm:" + sftm);
// }
// }
/* to switch level up :
rsft should be greater than switch up condition
*/
if ((current_level < max_level) && (sftm > (1 + _switchup[current_level]))) {
CONFIG::LOGGING {
Log.debug("sftm:> 1+_switchup[_level]=" + (1 + _switchup[current_level]));
}
switch_to_level = current_level + 1;
}
/* to switch level down :
rsft should be smaller than switch up condition,
or the current level is greater than max level
*/ else if ((current_level > max_level && current_level > 0) || (current_level > 0 && (sftm < 1 - _switchdown[current_level]))) {
CONFIG::LOGGING {
Log.debug("sftm < 1-_switchdown[current_level]=" + _switchdown[current_level]);
}
var bufferratio : Number = 1000 * buffer / _lastSegmentDuration;
/* find suitable level matching current bandwidth, starting from current level
when switching level down, we also need to consider that we might need to load two fragments.
the condition (bufferratio > 2*_levels[j].bitrate/_lastBandwidth)
ensures that buffer time is bigger than than the time to download 2 fragments from level j, if we keep same bandwidth.
*/
for (var j : int = current_level - 1; j >= 0; j--) {
if (_bitrate[j] <= lastBandwidth && (bufferratio > 2 * _bitrate[j] / lastBandwidth)) {
switch_to_level = j;
break;
}
if (j == 0) {
switch_to_level = 0;
}
}
}
// Then we should check if selected level is higher than max_level if so, than take the min of those two
switch_to_level = Math.min(max_level, switch_to_level);
CONFIG::LOGGING {
if (switch_to_level != current_level) {
Log.debug("switch to level " + switch_to_level);
}
}
return switch_to_level;
}
// get level index of first level appearing in the manifest
public function get firstLevel() : int {
var levels : Vector.<Level> = _hls.levels;
for (var i : int = 0; i < levels.length; i++) {
if (levels[i].manifest_index == 0) {
return i;
}
}
return 0;
}
public function isStartLevelSet() : Boolean {
return (_startLevel >=0);
}
/* set the quality level used when starting a fresh playback */
public function set startLevel(level : int) : void {
_startLevel = level;
};
public function get startLevel() : int {
var start_level : int = -1;
var levels : Vector.<Level> = _hls.levels;
if (levels) {
// if set, _startLevel takes precedence
if(_startLevel >=0) {
return Math.min(levels.length-1,_startLevel);
} else if (HLSSettings.startFromLevel === -2) {
// playback will start from the first level appearing in Manifest (not sorted by bitrate)
return firstLevel;
} else if (HLSSettings.startFromLevel === -1 && HLSSettings.startFromBitrate === -1) {
/* if startFromLevel is set to -1, it means that effective startup level
* will be determined from first segment download bandwidth
* let's use lowest bitrate for this download bandwidth assessment
* this should speed up playback start time
*/
return 0;
} else {
// set up start level as being the lowest non-audio level.
for (var i : int = 0; i < levels.length; i++) {
if (!levels[i].audio) {
start_level = i;
break;
}
}
// in case of audio only playlist, force startLevel to 0
if (start_level == -1) {
CONFIG::LOGGING {
Log.info("playlist is audio-only");
}
start_level = 0;
} else {
if (HLSSettings.startFromBitrate > 0) {
start_level = findIndexOfClosestLevel(HLSSettings.startFromBitrate);
} else if (HLSSettings.startFromLevel > 0) {
// adjust start level using a rule by 3
start_level += Math.round(HLSSettings.startFromLevel * (levels.length - start_level - 1));
}
}
}
CONFIG::LOGGING {
Log.debug("start level :" + start_level);
}
}
return start_level;
}
/**
* @param desiredBitrate
* @return The index of the level that has a bitrate closest to the desired bitrate.
*/
private function findIndexOfClosestLevel(desiredBitrate : Number) : int {
var levelIndex : int = -1;
var minDistance : Number = Number.MAX_VALUE;
var levels : Vector.<Level> = _hls.levels;
for (var index : int = 0; index < levels.length; index++) {
var level : Level = levels[index];
var distance : Number = Math.abs(desiredBitrate - level.bitrate);
if (distance < minDistance) {
levelIndex = index;
minDistance = distance;
}
}
return levelIndex;
}
public function get seekLevel() : int {
var seek_level : int = -1;
var levels : Vector.<Level> = _hls.levels;
if (HLSSettings.seekFromLevel == -1) {
// keep last level, but don't exceed _maxLevel
return Math.min(_hls.loadLevel,_maxLevel);
}
// set up seek level as being the lowest non-audio level.
for (var i : int = 0; i < levels.length; i++) {
if (!levels[i].audio) {
seek_level = i;
break;
}
}
// in case of audio only playlist, force seek_level to 0
if (seek_level == -1) {
seek_level = 0;
} else {
if (HLSSettings.seekFromLevel > 0) {
// adjust start level using a rule by 3
seek_level += Math.round(HLSSettings.seekFromLevel * (levels.length - seek_level - 1));
}
}
CONFIG::LOGGING {
Log.debug("seek level :" + seek_level);
}
return seek_level;
}
}
}
|
/* 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.constant.HLSMaxLevelCappingMode;
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.Level;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that manages auto level selection
*
* this is an implementation based on Serial segment fetching method from
* http://www.cs.tut.fi/~moncef/publications/rate-adaptation-IC-2011.pdf
*/
public class LevelController {
/** Reference to the HLS controller. **/
private var _hls : HLS;
/** switch up threshold **/
private var _switchup : Vector.<Number> = null;
/** switch down threshold **/
private var _switchdown : Vector.<Number> = null;
/** bitrate array **/
private var _bitrate : Vector.<uint> = null;
/** vector of levels with unique dimension with highest bandwidth **/
private var _maxUniqueLevels : Vector.<Level> = null;
/** nb level **/
private var _nbLevel : int = 0;
private var _lastSegmentDuration : Number;
private var _lastFetchDuration : Number;
private var lastBandwidth : int;
private var _autoLevelCapping : int;
private var _startLevel : int = -1;
private var _fpsController : FPSController;
/** Create the loader. **/
public function LevelController(hls : HLS) : void {
_hls = hls;
_fpsController = new FPSController(hls);
/* low priority listener, so that other listeners with default priority
could seamlessly set hls.startLevel in their HLSEvent.MANIFEST_PARSED listener */
_hls.addEventListener(HLSEvent.MANIFEST_PARSED, _manifestParsedHandler, false, int.MIN_VALUE);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOAD_EMERGENCY_ABORTED, _fragmentLoadedHandler);
}
;
public function dispose() : void {
_fpsController.dispose();
_fpsController = null;
_hls.removeEventListener(HLSEvent.MANIFEST_PARSED, _manifestParsedHandler);
_hls.removeEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
_hls.removeEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentLoadedHandler);
_hls.removeEventListener(HLSEvent.FRAGMENT_LOAD_EMERGENCY_ABORTED, _fragmentLoadedHandler);
}
private function _fragmentLoadedHandler(event : HLSEvent) : void {
var metrics : HLSLoadMetrics = event.loadMetrics;
// only monitor main fragment metrics for level switching
if(metrics.type == HLSLoaderTypes.FRAGMENT_MAIN) {
lastBandwidth = metrics.bandwidth;
_lastSegmentDuration = metrics.duration;
_lastFetchDuration = metrics.processing_duration;
}
}
private function _manifestParsedHandler(event : HLSEvent) : void {
if(HLSSettings.autoStartLoad) {
// upon manifest parsed event, trigger a level switch to load startLevel playlist
_hls.dispatchEvent(new HLSEvent(HLSEvent.LEVEL_SWITCH, startLevel));
}
}
private function _manifestLoadedHandler(event : HLSEvent) : void {
var levels : Vector.<Level> = event.levels;
var maxswitchup : Number = 0;
var minswitchdwown : Number = Number.MAX_VALUE;
_nbLevel = levels.length;
_bitrate = new Vector.<uint>(_nbLevel, true);
_switchup = new Vector.<Number>(_nbLevel, true);
_switchdown = new Vector.<Number>(_nbLevel, true);
_autoLevelCapping = -1;
_lastSegmentDuration = 0;
_lastFetchDuration = 0;
lastBandwidth = 0;
var i : int;
for (i = 0; i < _nbLevel; i++) {
_bitrate[i] = levels[i].bitrate;
}
for (i = 0; i < _nbLevel - 1; i++) {
_switchup[i] = (_bitrate[i + 1] - _bitrate[i]) / _bitrate[i];
maxswitchup = Math.max(maxswitchup, _switchup[i]);
}
for (i = 0; i < _nbLevel - 1; i++) {
_switchup[i] = Math.min(maxswitchup, 2 * _switchup[i]);
CONFIG::LOGGING {
Log.debug("_switchup[" + i + "]=" + _switchup[i]);
}
}
for (i = 1; i < _nbLevel; i++) {
_switchdown[i] = (_bitrate[i] - _bitrate[i - 1]) / _bitrate[i];
minswitchdwown = Math.min(minswitchdwown, _switchdown[i]);
}
for (i = 1; i < _nbLevel; i++) {
_switchdown[i] = Math.max(2 * minswitchdwown, _switchdown[i]);
CONFIG::LOGGING {
Log.debug("_switchdown[" + i + "]=" + _switchdown[i]);
}
}
if (HLSSettings.capLevelToStage) {
_maxUniqueLevels = _maxLevelsWithUniqueDimensions;
}
}
;
public function getbestlevel(downloadBandwidth : int) : int {
var max_level : int = _maxLevel;
for (var i : int = max_level; i >= 0; i--) {
if (_bitrate[i] <= downloadBandwidth) {
return i;
}
}
return 0;
}
private function get _maxLevelsWithUniqueDimensions() : Vector.<Level> {
var filter : Function = function(l : Level, i : int, v : Vector.<Level>) : Boolean {
if (l.width > 0 && l.height > 0) {
if (i + 1 < v.length) {
var nextLevel : Level = v[i + 1];
if (l.width != nextLevel.width && l.height != nextLevel.height) {
return true;
}
} else {
return true;
}
}
return false;
};
return _hls.levels.filter(filter);
}
/** Return the capping/max level value that could be used by automatic level selection algorithm **/
public function get autoLevelCapping() : int {
return _autoLevelCapping;
}
/** set the capping/max level value that could be used by automatic level selection algorithm **/
public function set autoLevelCapping(newLevel : int) : void {
_autoLevelCapping = newLevel;
}
private function get _maxLevel() : int {
// if set, _autoLevelCapping takes precedence
if(_autoLevelCapping >= 0) {
return Math.min(_nbLevel - 1, _autoLevelCapping);
} else if (HLSSettings.capLevelToStage) {
var maxLevelsCount : int = _maxUniqueLevels.length;
if (_hls.stage && maxLevelsCount) {
var maxLevel : Level = this._maxUniqueLevels[0], maxLevelIdx : int = maxLevel.index, sWidth : Number = this._hls.stage.stageWidth, sHeight : Number = this._hls.stage.stageHeight, lWidth : int, lHeight : int, i : int;
switch (HLSSettings.maxLevelCappingMode) {
case HLSMaxLevelCappingMode.UPSCALE:
for (i = maxLevelsCount - 1; i >= 0; i--) {
maxLevel = this._maxUniqueLevels[i];
maxLevelIdx = maxLevel.index;
lWidth = maxLevel.width;
lHeight = maxLevel.height;
CONFIG::LOGGING {
Log.debug("stage size: " + sWidth + "x" + sHeight + " ,level" + maxLevelIdx + " size: " + lWidth + "x" + lHeight);
}
if (sWidth >= lWidth || sHeight >= lHeight) {
break;
// from for loop
}
}
break;
case HLSMaxLevelCappingMode.DOWNSCALE:
for (i = 0; i < maxLevelsCount; i++) {
maxLevel = this._maxUniqueLevels[i];
maxLevelIdx = maxLevel.index;
lWidth = maxLevel.width;
lHeight = maxLevel.height;
CONFIG::LOGGING {
Log.debug("stage size: " + sWidth + "x" + sHeight + " ,level" + maxLevelIdx + " size: " + lWidth + "x" + lHeight);
}
if (sWidth <= lWidth || sHeight <= lHeight) {
break;
// from for loop
}
}
break;
}
CONFIG::LOGGING {
Log.debug("max capped level idx: " + maxLevelIdx);
}
}
return maxLevelIdx;
} else {
return _nbLevel - 1;
}
}
/** Update the quality level for the next fragment load. **/
public function getnextlevel(current_level : int, buffer : Number) : int {
if (_lastFetchDuration == 0 || _lastSegmentDuration == 0) {
return 0;
}
/* rsft : remaining segment fetch time : available time to fetch next segment
it depends on the current playback timestamp , the timestamp of the first frame of the next segment
and TBMT, indicating a desired latency between the time instant to receive the last byte of a
segment to the playback of the first media frame of a segment
buffer is start time of next segment
TBMT is the buffer size we need to ensure (we need at least 2 segments buffered */
var rsft : Number = 1000 * buffer - 2 * _lastFetchDuration;
var sftm : Number = Math.min(_lastSegmentDuration, rsft) / _lastFetchDuration;
var max_level : Number = _maxLevel;
var switch_to_level : int = current_level;
// CONFIG::LOGGING {
// Log.info("rsft:" + rsft);
// Log.info("sftm:" + sftm);
// }
// }
/* to switch level up :
rsft should be greater than switch up condition
*/
if ((current_level < max_level) && (sftm > (1 + _switchup[current_level]))) {
CONFIG::LOGGING {
Log.debug("sftm:> 1+_switchup[_level]=" + (1 + _switchup[current_level]));
}
switch_to_level = current_level + 1;
}
/* to switch level down :
rsft should be smaller than switch up condition,
or the current level is greater than max level
*/ else if ((current_level > max_level && current_level > 0) || (current_level > 0 && (sftm < 1 - _switchdown[current_level]))) {
CONFIG::LOGGING {
Log.debug("sftm < 1-_switchdown[current_level]=" + _switchdown[current_level]);
}
var bufferratio : Number = 1000 * buffer / _lastSegmentDuration;
/* find suitable level matching current bandwidth, starting from current level
when switching level down, we also need to consider that we might need to load two fragments.
the condition (bufferratio > 2*_levels[j].bitrate/_lastBandwidth)
ensures that buffer time is bigger than than the time to download 2 fragments from level j, if we keep same bandwidth.
*/
for (var j : int = current_level - 1; j >= 0; j--) {
if (_bitrate[j] <= lastBandwidth && (bufferratio > 2 * _bitrate[j] / lastBandwidth)) {
switch_to_level = j;
break;
}
if (j == 0) {
switch_to_level = 0;
}
}
}
// Then we should check if selected level is higher than max_level if so, than take the min of those two
switch_to_level = Math.min(max_level, switch_to_level);
CONFIG::LOGGING {
if (switch_to_level != current_level) {
Log.debug("switch to level " + switch_to_level);
}
}
return switch_to_level;
}
// get level index of first level appearing in the manifest
public function get firstLevel() : int {
var levels : Vector.<Level> = _hls.levels;
for (var i : int = 0; i < levels.length; i++) {
if (levels[i].manifest_index == 0) {
return i;
}
}
return 0;
}
public function isStartLevelSet() : Boolean {
return (_startLevel >=0);
}
/* set the quality level used when starting a fresh playback */
public function set startLevel(level : int) : void {
_startLevel = level;
};
public function get startLevel() : int {
var start_level : int = -1;
var levels : Vector.<Level> = _hls.levels;
if (levels) {
// if set, _startLevel takes precedence
if(_startLevel >=0) {
return Math.min(levels.length-1,_startLevel);
} else if (HLSSettings.startFromLevel === -2) {
// playback will start from the first level appearing in Manifest (not sorted by bitrate)
return firstLevel;
} else if (HLSSettings.startFromLevel === -1 && HLSSettings.startFromBitrate === -1) {
/* if startFromLevel is set to -1, it means that effective startup level
* will be determined from first segment download bandwidth
* let's use lowest bitrate for this download bandwidth assessment
* this should speed up playback start time
*/
return 0;
} else {
// set up start level as being the lowest non-audio level.
for (var i : int = 0; i < levels.length; i++) {
if (!levels[i].audio) {
start_level = i;
break;
}
}
// in case of audio only playlist, force startLevel to 0
if (start_level == -1) {
CONFIG::LOGGING {
Log.info("playlist is audio-only");
}
start_level = 0;
} else {
if (HLSSettings.startFromBitrate > 0) {
start_level = findIndexOfClosestLevel(HLSSettings.startFromBitrate);
} else if (HLSSettings.startFromLevel > 0) {
// adjust start level using a rule by 3
start_level += Math.round(HLSSettings.startFromLevel * (levels.length - start_level - 1));
}
}
}
CONFIG::LOGGING {
Log.debug("start level :" + start_level);
}
}
return start_level;
}
/**
* @param desiredBitrate
* @return The index of the level that has a bitrate closest to the desired bitrate.
*/
private function findIndexOfClosestLevel(desiredBitrate : Number) : int {
var levelIndex : int = -1;
var minDistance : Number = Number.MAX_VALUE;
var levels : Vector.<Level> = _hls.levels;
for (var index : int = 0; index < levels.length; index++) {
var level : Level = levels[index];
var distance : Number = Math.abs(desiredBitrate - level.bitrate);
if (distance < minDistance) {
levelIndex = index;
minDistance = distance;
}
}
return levelIndex;
}
public function get seekLevel() : int {
var seek_level : int = -1;
var levels : Vector.<Level> = _hls.levels;
if (HLSSettings.seekFromLevel == -1) {
// keep last level, but don't exceed _maxLevel
return Math.min(_hls.loadLevel,_maxLevel);
}
// set up seek level as being the lowest non-audio level.
for (var i : int = 0; i < levels.length; i++) {
if (!levels[i].audio) {
seek_level = i;
break;
}
}
// in case of audio only playlist, force seek_level to 0
if (seek_level == -1) {
seek_level = 0;
} else {
if (HLSSettings.seekFromLevel > 0) {
// adjust start level using a rule by 3
seek_level += Math.round(HLSSettings.seekFromLevel * (levels.length - seek_level - 1));
}
}
CONFIG::LOGGING {
Log.debug("seek level :" + seek_level);
}
return seek_level;
}
}
}
|
use startLevel getter directly
|
LevelController: use startLevel getter directly
|
ActionScript
|
mpl-2.0
|
loungelogic/flashls,tedconf/flashls,clappr/flashls,jlacivita/flashls,tedconf/flashls,hola/flashls,vidible/vdb-flashls,codex-corp/flashls,NicolasSiver/flashls,Corey600/flashls,thdtjsdn/flashls,jlacivita/flashls,Corey600/flashls,hola/flashls,codex-corp/flashls,vidible/vdb-flashls,thdtjsdn/flashls,loungelogic/flashls,mangui/flashls,NicolasSiver/flashls,fixedmachine/flashls,neilrackett/flashls,neilrackett/flashls,clappr/flashls,fixedmachine/flashls,mangui/flashls
|
e87132126bc0ab41815ef3f7018d1da95e51d1b4
|
src/com/as3mxml/asconfigc/utils/findOutputDirectory.as
|
src/com/as3mxml/asconfigc/utils/findOutputDirectory.as
|
/*
Copyright 2016-2021 Bowler Hat LLC
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.as3mxml.asconfigc.utils
{
public function findOutputDirectory(mainFile:String, outputPath:String, isSWF:Boolean):String
{
if(!outputPath)
{
if(!mainFile)
{
return process.cwd();
}
var mainPath:String = path.resolve(path.dirname(mainFile));
if(!isSWF)
{
//Royale treats these directory structures as a special case
if(mainPath.endsWith("/src") ||
mainPath.endsWith("\\src"))
{
return path.resolve(mainPath, "../");
}
else if(mainPath.endsWith("/src/main/flex") ||
mainPath.endsWith("\\src\\main\\flex") ||
mainPath.endsWith("/src/main/royale") ||
mainPath.endsWith("\\src\\main\\royale"))
{
return path.resolve(mainPath, "../../../");
}
}
return mainPath;
}
return path.resolve(path.dirname(outputPath));
}
}
|
/*
Copyright 2016-2021 Bowler Hat LLC
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.as3mxml.asconfigc.utils
{
public function findOutputDirectory(mainFile:String, outputPath:String, isSWF:Boolean):String
{
if(!outputPath)
{
if(!mainFile)
{
return process.cwd();
}
var mainPath:String = path.resolve(path.dirname(mainFile));
if(!isSWF)
{
//Royale treats these directory structures as a special case
if(mainPath.endsWith("/src") ||
mainPath.endsWith("\\src"))
{
return path.resolve(mainPath, "../");
}
else if(mainPath.endsWith("/src/main/flex") ||
mainPath.endsWith("\\src\\main\\flex") ||
mainPath.endsWith("/src/main/royale") ||
mainPath.endsWith("\\src\\main\\royale"))
{
return path.resolve(mainPath, "../../../");
}
}
return mainPath;
}
if (!isSWF)
{
return outputPath;
}
return path.resolve(path.dirname(outputPath));
}
}
|
fix result for Royale when js-output is defined
|
findOutputDirectory: fix result for Royale when js-output is defined
|
ActionScript
|
apache-2.0
|
BowlerHatLLC/asconfigc
|
486d913476e9e3ab604683a2224c0c07ea9d1ffc
|
src/com/merlinds/miracle_tool/views/AppMenuMediator.as
|
src/com/merlinds/miracle_tool/views/AppMenuMediator.as
|
/**
* User: MerlinDS
* Date: 12.07.2014
* Time: 21:35
*/
package com.merlinds.miracle_tool.views {
import com.merlinds.miracle_tool.utils.dispatchAction;
import com.merlinds.miracle_tool.views.components.controls.ActionButton;
import flash.events.MouseEvent;
import org.robotlegs.mvcs.Mediator;
public class AppMenuMediator extends Mediator {
//==============================================================================
//{region PUBLIC METHODS
public function AppMenuMediator() {
super();
}
override public function onRegister():void {
this.addViewListener(MouseEvent.CLICK, this.mouseClickHandler);
}
override public function onRemove():void {
this.removeViewListener(MouseEvent.CLICK, this.mouseClickHandler);
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function mouseClickHandler(event:MouseEvent):void {
var target:Object = event.target;
if(target is ActionButton){
dispatchAction((target as ActionButton).action, this.dispatch);
}
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
/**
* User: MerlinDS
* Date: 12.07.2014
* Time: 21:35
*/
package com.merlinds.miracle_tool.views {
import com.merlinds.miracle_tool.events.ActionEvent;
import com.merlinds.miracle_tool.services.ActionService;
import com.merlinds.miracle_tool.utils.dispatchAction;
import com.merlinds.miracle_tool.views.components.controls.ActionButton;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import org.robotlegs.mvcs.Mediator;
public class AppMenuMediator extends Mediator {
[Inject]
public var actionService:ActionService;
//==============================================================================
//{region PUBLIC METHODS
public function AppMenuMediator() {
super();
}
override public function onRegister():void {
this.contextView.stage.addEventListener(KeyboardEvent.KEY_UP, this.keyboardHandler);
this.addViewListener(MouseEvent.CLICK, this.mouseClickHandler);
}
override public function onRemove():void {
this.removeViewListener(MouseEvent.CLICK, this.mouseClickHandler);
this.contextView.stage.removeEventListener(KeyboardEvent.KEY_UP, this.keyboardHandler);
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function mouseClickHandler(event:MouseEvent):void {
var target:Object = event.target;
if(target is ActionButton){
dispatchAction((target as ActionButton).action, this.dispatch);
}
}
private function keyboardHandler(event:KeyboardEvent):void {
switch (event.keyCode){
case 78: // N
if(event.ctrlKey){
//new project
this.dispatch(new ActionEvent(ActionEvent.NEW_PROJECT));
}
break;
case 83: // S
if(event.ctrlKey){
//save project
this.dispatch(new ActionEvent(ActionEvent.SAVE_PROJECT));
}
break;
case 81: // Q
if(event.ctrlKey){
//close program
}
break;
case 69: // E
if(event.ctrlKey){
//close project
this.dispatch(new ActionEvent(ActionEvent.CLOSE_PROJECT));
}
break;
case 86: // V
break;
case 72: // H
break;
case 119: // F8
break;
case 120: // F9
break;
}
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
Add few shortcuts
|
Add few shortcuts
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
02d97ddec1b96cf7cdafb46ba96ca4c4da33c10f
|
src/as/com/threerings/util/NetUtil.as
|
src/as/com/threerings/util/NetUtil.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.net.URLRequest;
//import flash.net.navigateToURL; // function import
public class NetUtil
{
/**
* Convenience method to load a web page in the browser window without
* having to worry about SecurityErrors in various conditions.
*
* @return true if the url was able to be loaded.
*/
public static function navigateToURL (url :String, preferredWindow :String = "_self") :Boolean
{
var ureq :URLRequest = new URLRequest(url);
while (true) {
try {
flash.net.navigateToURL(ureq, preferredWindow);
return true;
} catch (err :SecurityError) {
if (preferredWindow != null) {
preferredWindow = null; // try again with no preferred window
} else {
Log.getLog(NetUtil).warning("Unable to navigate to URL [e=" + err + "].");
break;
}
}
}
return false; // failure!
}
}
}
|
//
// $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.net.URLRequest;
//import flash.net.navigateToURL; // function import
public class NetUtil
{
/**
* Convenience method to load a web page in the browser window without
* having to worry about SecurityErrors in various conditions.
*
* @param url a String or a URLRequest.
* @param preferredWindow the browser tab/window identifier in which to load. If you
* specify a non-null window and it causes a security error, the request is retried with null.
*
* @return true if the url was able to be loaded.
*/
public static function navigateToURL (url :*, preferredWindow :String = "_self") :Boolean
{
var ureq :URLRequest = (url is URLRequest) ? URLRequest(url) : new URLRequest(String(url));
while (true) {
try {
flash.net.navigateToURL(ureq, preferredWindow);
return true;
} catch (err :SecurityError) {
if (preferredWindow != null) {
preferredWindow = null; // try again with no preferred window
} else {
Log.getLog(NetUtil).warning("Unable to navigate to URL [e=" + err + "].");
break;
}
}
}
return false; // failure!
}
}
}
|
Allow a preconfigured URLRequest to be passed in.
|
Allow a preconfigured URLRequest to be passed in.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5646 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
8210f98a8da070412d23599c2b782a2678acf21b
|
src/aerys/minko/scene/controller/TransformController.as
|
src/aerys/minko/scene/controller/TransformController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _localToWorldTransformsInitialized : Vector.<Boolean>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _worldToLocalTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
updateLocalToWorld();
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[childId];
if (rootTransform._hasChanged || !_localToWorldTransformsInitialized[nodeId])
{
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]);
rootTransform._hasChanged = false;
_localToWorldTransformsInitialized[nodeId] = true;
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
}
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
var isDirty : Boolean = localToWorld._hasChanged;
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
|| !_localToWorldTransformsInitialized[childId];
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
_localToWorldTransformsInitialized[childId] = true;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function getDirtyRoot(nodeId : int) : int
{
var dirtyRoot : int = -1;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged ||
!_localToWorldTransformsInitialized[nodeId])
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
return dirtyRoot;
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_localToWorldTransformsInitialized = null;
_localToWorldTransforms = null;
_worldToLocalTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_localToWorldTransformsInitialized = new <Boolean>[];
_localToWorldTransforms = new <Matrix4x4>[];
_worldToLocalTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
_localToWorldTransformsInitialized[nodeId] = false;
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_worldToLocalTransforms.length = _localToWorldTransforms.length;
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
{
var dirtyRoot : int = getDirtyRoot(nodeId);
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
return _localToWorldTransforms[nodeId];
}
public function getWorldToLocalTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId];
if (!worldToLocalTransform)
{
_worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4();
if (!forceUpdate)
worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert();
}
if (forceUpdate)
{
var dirtyRoot : int = getDirtyRoot(nodeId);
if (dirtyRoot >= 0)
{
updateLocalToWorld(dirtyRoot);
worldToLocalTransform
.copyFrom(_localToWorldTransforms[nodeId])
.invert();
}
}
return worldToLocalTransform;
}
}
}
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private static const INIT_NONE : uint = 0;
private static const INIT_LOCAL_TO_WORLD : uint = 1;
private static const INIT_WORLD_TO_LOCAL : uint = 2;
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _initialized : Vector.<uint>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _worldToLocalTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
updateLocalToWorld();
}
private function updateLocalToWorld(nodeId : uint = 0) : void
{
var numNodes : uint = _transforms.length;
var childrenOffset : uint = 1;
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[childId];
if (rootTransform._hasChanged || _initialized[nodeId] == INIT_NONE)
{
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]);
rootTransform._hasChanged = false;
_initialized[nodeId] = INIT_LOCAL_TO_WORLD;
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
}
for (; nodeId < numNodes; ++nodeId)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
var isDirty : Boolean = localToWorld._hasChanged;
localToWorld._hasChanged = false;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged
|| !_initialized[childId];
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
childTransform._hasChanged = false;
_initialized[childId] = INIT_LOCAL_TO_WORLD;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
}
}
}
}
private function updateAncestorsAndSelfLocalToWorld(nodeId : uint) : void
{
var dirtyRoot : int = -1;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged ||
!_initialized[nodeId])
dirtyRoot = nodeId;
nodeId = _parentId[nodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_initialized = null;
_localToWorldTransforms = null;
_worldToLocalTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_initialized = new <uint>[];
_localToWorldTransforms = new <Matrix4x4>[];
_worldToLocalTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
_initialized[nodeId] = INIT_NONE;
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_worldToLocalTransforms.length = _localToWorldTransforms.length;
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
return _localToWorldTransforms[nodeId];
}
public function getWorldToLocalTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
if (_invalidList || _nodeToId[node] == undefined)
updateTransformsList();
var nodeId : uint = _nodeToId[node];
var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId];
if (!worldToLocalTransform)
{
_worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4();
if (!forceUpdate)
{
worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert();
_initialized[nodeId] |= INIT_WORLD_TO_LOCAL;
}
}
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
if (!(_initialized[nodeId] & INIT_WORLD_TO_LOCAL))
{
_initialized[nodeId] |= INIT_WORLD_TO_LOCAL;
worldToLocalTransform
.copyFrom(_localToWorldTransforms[nodeId])
.invert();
}
return worldToLocalTransform;
}
}
}
|
fix world to local computation/update when the local to world is uptodate and the world to local has already been instanciated
|
fix world to local computation/update when the local to world is uptodate and the world to local has already been instanciated
|
ActionScript
|
mit
|
aerys/minko-as3
|
03467a12ae6ac8d4a5f49b579cc5de8dc948807c
|
src/aerys/minko/scene/controller/TransformController.as
|
src/aerys/minko/scene/controller/TransformController.as
|
package aerys.minko.scene.controller
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.Viewport;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.math.Matrix4x4;
import flash.display.BitmapData;
import flash.utils.Dictionary;
import mx.olap.aggregators.MaxAggregator;
use namespace minko_math;
/**
* The TransformController handles the batched update of all the local to world matrices
* of a sub-scene. As such, it will only be active on the root node of a sub-scene and will
* automatically disable itself on other nodes.
*
* @author Jean-Marc Le Roux
*
*/
public final class TransformController extends AbstractController
{
private static const FLAG_NONE : uint = 0;
private static const FLAG_INIT_LOCAL_TO_WORLD : uint = 1;
private static const FLAG_INIT_WORLD_TO_LOCAL : uint = 2;
private static const FLAG_SYNCHRONIZE_TRANSFORMS : uint = 4;
private static const FLAG_LOCK_TRANSFORMS : uint = 8;
private var _target : ISceneNode;
private var _invalidList : Boolean;
private var _nodeToId : Dictionary;
private var _idToNode : Vector.<ISceneNode>
private var _transforms : Vector.<Matrix4x4>;
private var _flags : Vector.<uint>;
private var _localToWorldTransforms : Vector.<Matrix4x4>;
private var _worldToLocalTransforms : Vector.<Matrix4x4>;
private var _numChildren : Vector.<uint>;
private var _firstChildId : Vector.<uint>;
private var _parentId : Vector.<int>;
public function TransformController()
{
super();
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function renderingBeginHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : Number) : void
{
if (_invalidList)
updateTransformsList();
if (_transforms.length)
updateLocalToWorld();
}
private function updateRootLocalToWorld(nodeId : uint = 0) : void
{
var rootLocalToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var rootTransform : Matrix4x4 = _transforms[nodeId];
var root : ISceneNode = _idToNode[nodeId];
var rootFlags : uint = _flags[nodeId];
if (rootTransform._hasChanged || !(rootFlags & FLAG_INIT_LOCAL_TO_WORLD))
{
if (rootFlags & FLAG_LOCK_TRANSFORMS)
rootLocalToWorld.lock();
rootLocalToWorld.copyFrom(rootTransform);
if (nodeId != 0)
rootLocalToWorld.append(_localToWorldTransforms[_parentId[nodeId]]);
if (rootFlags & FLAG_LOCK_TRANSFORMS)
rootLocalToWorld.unlock();
rootTransform._hasChanged = false;
_flags[nodeId] |= FLAG_INIT_LOCAL_TO_WORLD;
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
if (rootFlags & FLAG_SYNCHRONIZE_TRANSFORMS)
{
var rootWorldToLocal : Matrix4x4 = _worldToLocalTransforms[nodeId]
|| (_worldToLocalTransforms[nodeId] = new Matrix4x4());
if (rootFlags & FLAG_LOCK_TRANSFORMS)
rootWorldToLocal.lock();
rootWorldToLocal.copyFrom(rootLocalToWorld).invert();
if (rootFlags & FLAG_LOCK_TRANSFORMS)
rootWorldToLocal.unlock();
}
}
}
private function updateLocalToWorld(nodeId : uint = 0, subtreeOnly : Boolean = false) : void
{
var numNodes : uint = _transforms.length;
var subtreeMax : uint = nodeId;
updateRootLocalToWorld(nodeId);
while (nodeId < numNodes)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
var isDirty : Boolean = localToWorld._hasChanged;
localToWorld._hasChanged = false;
if (lastChildId > subtreeMax)
subtreeMax = lastChildId;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childFlags : uint = _flags[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged
|| !(childFlags & FLAG_INIT_LOCAL_TO_WORLD);
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
if (childFlags & FLAG_LOCK_TRANSFORMS)
childLocalToWorld.lock();
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
if (childFlags & FLAG_LOCK_TRANSFORMS)
childLocalToWorld.unlock();
childTransform._hasChanged = false;
_flags[childId] |= FLAG_INIT_LOCAL_TO_WORLD;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
if (childFlags & FLAG_SYNCHRONIZE_TRANSFORMS)
{
var childWorldToLocal : Matrix4x4 = _worldToLocalTransforms[childId]
|| (_worldToLocalTransforms[childId] = new Matrix4x4());
if (childFlags & FLAG_LOCK_TRANSFORMS)
childWorldToLocal.lock();
childWorldToLocal.copyFrom(childLocalToWorld).invert();
if (childFlags & FLAG_LOCK_TRANSFORMS)
childWorldToLocal.unlock();
}
}
}
if (subtreeOnly && 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 : int) : void
{
var dirtyRoot : int = -1;
while (nodeId >= 0)
{
if ((_transforms[nodeId] as Matrix4x4)._hasChanged
|| !(_flags[nodeId] & FLAG_INIT_LOCAL_TO_WORLD))
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;
_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;
_flags[nodeId] |= FLAG_INIT_LOCAL_TO_WORLD;
root.localToWorldTransformChanged.execute(root, rootLocalToWorld);
if (rootFlags & FLAG_SYNCHRONIZE_TRANSFORMS)
{
var rootWorldToLocal : Matrix4x4 = _worldToLocalTransforms[nodeId]
|| (_worldToLocalTransforms[nodeId] = new Matrix4x4());
if (rootFlags & FLAG_LOCK_TRANSFORMS)
rootWorldToLocal.lock();
rootWorldToLocal.copyFrom(rootLocalToWorld).invert();
if (rootFlags & FLAG_LOCK_TRANSFORMS)
rootWorldToLocal.unlock();
}
}
}
private function updateLocalToWorld(nodeId : uint = 0, targetNodeId : int = -1) : void
{
var numNodes : uint = _transforms.length;
var subtreeMax : uint = nodeId;
updateRootLocalToWorld(nodeId);
if (nodeId == targetNodeId)
return;
while (nodeId < numNodes)
{
var localToWorld : Matrix4x4 = _localToWorldTransforms[nodeId];
var numChildren : uint = _numChildren[nodeId];
var firstChildId : uint = _firstChildId[nodeId];
var lastChildId : uint = firstChildId + numChildren;
var isDirty : Boolean = localToWorld._hasChanged;
localToWorld._hasChanged = false;
if (lastChildId > subtreeMax)
subtreeMax = lastChildId;
for (var childId : uint = firstChildId; childId < lastChildId; ++childId)
{
var childTransform : Matrix4x4 = _transforms[childId];
var childLocalToWorld : Matrix4x4 = _localToWorldTransforms[childId];
var childFlags : uint = _flags[childId];
var childIsDirty : Boolean = isDirty || childTransform._hasChanged
|| !(childFlags & FLAG_INIT_LOCAL_TO_WORLD);
if (childIsDirty)
{
var child : ISceneNode = _idToNode[childId];
if (childFlags & FLAG_LOCK_TRANSFORMS)
childLocalToWorld.lock();
childLocalToWorld
.copyFrom(childTransform)
.append(localToWorld);
if (childFlags & FLAG_LOCK_TRANSFORMS)
childLocalToWorld.unlock();
childTransform._hasChanged = false;
_flags[childId] |= FLAG_INIT_LOCAL_TO_WORLD;
child.localToWorldTransformChanged.execute(child, childLocalToWorld);
if (childFlags & FLAG_SYNCHRONIZE_TRANSFORMS)
{
var childWorldToLocal : Matrix4x4 = _worldToLocalTransforms[childId]
|| (_worldToLocalTransforms[childId] = new Matrix4x4());
if (childFlags & FLAG_LOCK_TRANSFORMS)
childWorldToLocal.lock();
childWorldToLocal.copyFrom(childLocalToWorld).invert();
if (childFlags & FLAG_LOCK_TRANSFORMS)
childWorldToLocal.unlock();
}
if (childId == targetNodeId)
return;
}
}
if (targetNodeId >= 0 && nodeId && nodeId >= subtreeMax)
{
// jump to the first brother who has children
var parentId : uint = _parentId[nodeId];
nodeId = _firstChildId[parentId];
while (!_numChildren[nodeId] && nodeId < subtreeMax)
++nodeId;
if (nodeId >= subtreeMax)
return ;
nodeId = _firstChildId[nodeId];
}
else
++nodeId;
}
}
private function updateAncestorsAndSelfLocalToWorld(nodeId : uint) : void
{
var dirtyRoot : int = -1;
var tmpNodeId : int = nodeId;
while (tmpNodeId >= 0)
{
if ((_transforms[tmpNodeId] as Matrix4x4)._hasChanged
|| !(_flags[nodeId] & FLAG_INIT_LOCAL_TO_WORLD))
dirtyRoot = tmpNodeId;
tmpNodeId = _parentId[tmpNodeId];
}
if (dirtyRoot >= 0)
updateLocalToWorld(dirtyRoot, nodeId);
}
private function targetAddedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
if (_target)
throw new Error('The TransformController cannot have more than one target.');
_target = target;
_invalidList = true;
if (target is Scene)
{
(target as Scene).renderingBegin.add(renderingBeginHandler);
return;
}
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.add(descendantAddedHandler);
targetGroup.descendantRemoved.add(descendantRemovedHandler);
}
target.added.add(addedHandler);
}
private function targetRemovedHandler(ctrl : TransformController,
target : ISceneNode) : void
{
target.added.remove(addedHandler);
if (target is Group)
{
var targetGroup : Group = target as Group;
targetGroup.descendantAdded.remove(descendantAddedHandler);
targetGroup.descendantRemoved.remove(descendantRemovedHandler);
}
_invalidList = false;
_target = null;
_nodeToId = null;
_transforms = null;
_flags = null;
_localToWorldTransforms = null;
_worldToLocalTransforms = null;
_numChildren = null;
_idToNode = null;
_parentId = null;
}
private function addedHandler(target : ISceneNode, ancestor : Group) : void
{
// the controller will remove itself from the node when it's not its own root anymore
// but it will watch for the 'removed' signal to add itself back if the node becomes
// its own root again
_target.removed.add(removedHandler);
_target.removeController(this);
}
private function removedHandler(target : ISceneNode, ancestor : Group) : void
{
if (target.root == target)
{
target.removed.remove(removedHandler);
target.addController(this);
}
}
private function descendantAddedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function descendantRemovedHandler(root : Group,
descendant : ISceneNode) : void
{
_invalidList = true;
}
private function getNodeId(node : ISceneNode) : uint
{
if (_invalidList || !(node in _nodeToId))
updateTransformsList();
return _nodeToId[node];
}
private function updateTransformsList() : void
{
var root : ISceneNode = _target.root;
var nodes : Vector.<ISceneNode> = new <ISceneNode>[root];
var nodeId : uint = 0;
var oldNodeToId : Dictionary = _nodeToId;
var oldInitialized : Vector.<uint> = _flags;
var oldLocalToWorldTransforms : Vector.<Matrix4x4> = _localToWorldTransforms;
var oldWorldToLocalTransform : Vector.<Matrix4x4> = _worldToLocalTransforms;
_nodeToId = new Dictionary(true);
_transforms = new <Matrix4x4>[];
_flags = new <uint>[];
_localToWorldTransforms = new <Matrix4x4>[];
_worldToLocalTransforms = new <Matrix4x4>[];
_numChildren = new <uint>[];
_firstChildId = new <uint>[];
_idToNode = new <ISceneNode>[];
_parentId = new <int>[-1];
while (nodes.length)
{
var node : ISceneNode = nodes.shift();
var group : Group = node as Group;
_nodeToId[node] = nodeId;
_idToNode[nodeId] = node;
_transforms[nodeId] = node.transform;
if (oldNodeToId && node in oldNodeToId)
{
var oldNodeId : uint = oldNodeToId[node];
_localToWorldTransforms[nodeId] = oldLocalToWorldTransforms[oldNodeId];
_worldToLocalTransforms[nodeId] = oldWorldToLocalTransform[oldNodeId];
_flags[nodeId] = oldInitialized[oldNodeId];
}
else
{
_localToWorldTransforms[nodeId] = new Matrix4x4().lock();
_worldToLocalTransforms[nodeId] = null;
_flags[nodeId] = FLAG_NONE;
}
if (group)
{
var numChildren : uint = group.numChildren;
var firstChildId : uint = nodeId + nodes.length + 1;
_numChildren[nodeId] = numChildren;
_firstChildId[nodeId] = firstChildId;
for (var childId : uint = 0; childId < numChildren; ++childId)
{
_parentId[uint(firstChildId + childId)] = nodeId;
nodes.push(group.getChildAt(childId));
}
}
else
{
_numChildren[nodeId] = 0;
_firstChildId[nodeId] = 0;
}
++nodeId;
}
_worldToLocalTransforms.length = _localToWorldTransforms.length;
_invalidList = false;
}
public function getLocalToWorldTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
var nodeId : uint = getNodeId(node);
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
return _localToWorldTransforms[nodeId];
}
public function getWorldToLocalTransform(node : ISceneNode,
forceUpdate : Boolean = false) : Matrix4x4
{
var nodeId : uint = getNodeId(node);
var worldToLocalTransform : Matrix4x4 = _worldToLocalTransforms[nodeId];
if (!worldToLocalTransform)
{
_worldToLocalTransforms[nodeId] = worldToLocalTransform = new Matrix4x4();
if (!forceUpdate)
{
worldToLocalTransform.copyFrom(_localToWorldTransforms[nodeId]).invert();
_flags[nodeId] |= FLAG_INIT_WORLD_TO_LOCAL;
}
}
if (forceUpdate)
updateAncestorsAndSelfLocalToWorld(nodeId);
var flags : uint = _flags[nodeId];
if (!(flags & FLAG_INIT_WORLD_TO_LOCAL))
{
_flags[nodeId] |= FLAG_INIT_WORLD_TO_LOCAL;
if (flags & FLAG_LOCK_TRANSFORMS)
worldToLocalTransform.lock();
worldToLocalTransform
.copyFrom(_localToWorldTransforms[nodeId])
.invert();
if (flags & FLAG_LOCK_TRANSFORMS)
worldToLocalTransform.unlock();
}
return worldToLocalTransform;
}
public function setSharedLocalToWorldTransformReference(node : ISceneNode,
matrix : Matrix4x4) : void
{
var nodeId : uint = getNodeId(node);
if (_flags[nodeId] & FLAG_INIT_LOCAL_TO_WORLD)
matrix.copyFrom(_localToWorldTransforms[nodeId]);
_localToWorldTransforms[nodeId] = matrix;
}
public function setSharedWorldToLocalTransformReference(node : ISceneNode,
matrix : Matrix4x4) : void
{
var nodeId : uint = getNodeId(node);
if (_flags[nodeId] & FLAG_INIT_WORLD_TO_LOCAL)
matrix.copyFrom(_worldToLocalTransforms[nodeId]);
_worldToLocalTransforms[nodeId] = matrix;
}
public function synchronizeTransforms(node : ISceneNode, enabled : Boolean) : void
{
var nodeId : uint = getNodeId(node);
_flags[nodeId] = enabled
? _flags[nodeId] | FLAG_SYNCHRONIZE_TRANSFORMS
: _flags[nodeId] & ~FLAG_SYNCHRONIZE_TRANSFORMS;
}
public function lockTransformsBeforeUpdate(node : ISceneNode, enabled : Boolean) : void
{
var nodeId : uint = getNodeId(node);
_flags[nodeId] = enabled
? _flags[nodeId] | FLAG_LOCK_TRANSFORMS
: _flags[nodeId] & ~FLAG_LOCK_TRANSFORMS;
}
}
}
|
optimize TransformController.updateLocalToWorld() to stop updating as soon as the node with id == targetNodeId is updated (if provided)
|
optimize TransformController.updateLocalToWorld() to stop updating as soon as the node with id == targetNodeId is updated (if provided)
|
ActionScript
|
mit
|
aerys/minko-as3
|
afa7915a17b5ba20b62107ef0202e5e0699c000f
|
src/net/manaca/loaderqueue/inspector/LoaderInspector.as
|
src/net/manaca/loaderqueue/inspector/LoaderInspector.as
|
package net.manaca.loaderqueue.inspector
{
import com.bit101.components.CheckBox;
import com.bit101.components.ScrollPane;
import com.bit101.components.Style;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.system.Capabilities;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.ui.Keyboard;
import flash.utils.Dictionary;
import net.manaca.loaderqueue.ILoaderAdapter;
import net.manaca.loaderqueue.ILoaderQueue;
import net.manaca.loaderqueue.LoaderAdapterState;
import net.manaca.loaderqueue.LoaderQueueEvent;
/**
* 提供一个可视化界面用户查看加载队列进行情况.
* @author wersling
*
*/
public class LoaderInspector extends Sprite
{
//==========================================================================
// Constructor
//==========================================================================
/**
* 构造函数.
* @param loaderQueue 需要监视的加载队列.
*
*/
public function LoaderInspector(loaderQueue:ILoaderQueue = null)
{
super();
this.loaderQueue = loaderQueue;
initDisplay();
}
//==========================================================================
// Variables
//==========================================================================
private var scrollPane:ScrollPane;
private var container:DisplayObjectContainer;
private var onlyButton:CheckBox;
private var itemsMap:Dictionary = new Dictionary(true);
private var parentContainer:DisplayObjectContainer;
//==========================================================================
// Properties
//==========================================================================
private var _loaderQueue:ILoaderQueue;
/**
* 需要监视的加载队列.
* @return
*
*/
public function get loaderQueue():ILoaderQueue
{
return _loaderQueue;
}
public function set loaderQueue(value:ILoaderQueue):void
{
if(_loaderQueue && _loaderQueue != value)
{
removeEvents();
clearAllTask();
}
_loaderQueue = value;
if(_loaderQueue)
{
addEvents();
}
}
private var _height:Number = 0;
/**
* @private
*/
override public function get height():Number
{
return _height;
}
override public function set height(value:Number):void
{
_height = value;
layout();
}
private var _width:Number = 0;
/**
* @private
*/
override public function get width():Number
{
return _width;
}
override public function set width(value:Number):void
{
_width = value;
layout();
}
//----------------------------------
// freeze
//----------------------------------
private var _freeze:Boolean = true;
/**
* 是否冻结,如果冻结,则不更新界面.
* @return
*
*/
protected function get freeze():Boolean
{
return _freeze;
}
protected function set freeze(value:Boolean):void
{
if(_freeze != value)
{
_freeze = value;
for each (var item:InspectorItem in itemsMap)
{
item.freeze = freeze;
}
if(!freeze)
{
layout();
}
}
}
//==========================================================================
// Methods
//==========================================================================
/**
* 初始化界面
*
*/
private function initDisplay():void
{
addEventListener(Event.ADDED_TO_STAGE,
addedToStageHandler);
var titleLabel:TextField = new TextField();
titleLabel.autoSize = "left";
titleLabel.selectable = false;
titleLabel.text = "LoaderInspector v0.1";
titleLabel.x = 5;
titleLabel.y = 3;
var tf:TextFormat = new TextFormat(Style.fontName, 12, 0x000000, true);
titleLabel.setTextFormat(tf);
addChild(titleLabel);
container = new Sprite();
addChild(container);
onlyButton = new CheckBox(this, 20, 8,
"Only Progressing", onlyProgressingItems);
scrollPane = new ScrollPane(this, 5, 25);
scrollPane.content.addChild(container);
scrollPane.autoHideScrollBar = true;
}
/**
* 添加队列事件
*
*/
private function addEvents():void
{
loaderQueue.addEventListener(LoaderQueueEvent.TASK_ADDED,
loaderQueue_taskAddedHandler);
loaderQueue.addEventListener(LoaderQueueEvent.TASK_REMOVED,
loaderQueue_taskRemovedHandler);
}
/**
* 删除队列事件
*
*/
private function removeEvents():void
{
loaderQueue.removeEventListener(LoaderQueueEvent.TASK_ADDED,
loaderQueue_taskAddedHandler);
loaderQueue.removeEventListener(LoaderQueueEvent.TASK_REMOVED,
loaderQueue_taskRemovedHandler);
}
/**
* 重新布局,调整UI
*
*/
private function layout():void
{
if(freeze)
{
return;
}
graphics.clear();
graphics.beginFill(0x141E26);
graphics.drawRect(0, 0, width, height);
graphics.drawRect(1, 1, width - 2, height - 2);
graphics.beginFill(0xC3E8FC, 1);
graphics.drawRect(1, 1, width - 2, height - 2);
for each (var item:InspectorItem in itemsMap)
{
item.width = width - 20;
}
sortItemY();
onlyButton.x = width - 140;
scrollPane.width = width - 10;
scrollPane.height = height - 30;
scrollPane.update();
}
/**
* 对队列中的加载对象进行排序
*
*/
private function sortItemY():void
{
if(freeze)
{
return;
}
var cy:int = 5;
var items:Array = [];
for each (var item:InspectorItem in itemsMap)
{
//判断是否只显示正在加载的对象
if(onlyButton.selected)
{
if(item.loaderAdapter.state == LoaderAdapterState.STARTED)
{
items.push(item);
}
else if(container.contains(item))
{
container.removeChild(item);
}
}
else
{
items.push(item);
}
}
//排序
items.sortOn(["priority", "index"]);
//调整位置
for each (item in items)
{
container.addChild(item);
item.y = cy;
cy += 35;
}
}
/**
* 销毁该对象
*
*/
public function dispose():void
{
if(loaderQueue)
{
removeEvents();
clearAllTask();
}
}
/**
* 清除所有加载对象
*
*/
private function clearAllTask():void
{
for each (var item:InspectorItem in itemsMap)
{
removeTask(item.loaderAdapter);
}
}
/**
* 添加一个加载对象
* @param loaderAdapter
*
*/
private function addTask(loaderAdapter:ILoaderAdapter):void
{
if(loaderAdapter)
{
var item:InspectorItem = new InspectorItem(loaderAdapter);
item.addEventListener(Event.CHANGE,
item_completeHandler);
item.width = width - 20;
item.freeze = freeze;
itemsMap[loaderAdapter] = item;
sortItemY();
scrollPane.update();
}
}
/**
* 删除一个加载对象
* @param loaderAdapter
*
*/
private function removeTask(loaderAdapter:ILoaderAdapter):void
{
if(loaderAdapter && itemsMap[loaderAdapter])
{
var item:InspectorItem = itemsMap[loaderAdapter];
item.removeEventListener(Event.CHANGE,
item_completeHandler);
item.dispose();
itemsMap[loaderAdapter] = null;
sortItemY();
scrollPane.update();
}
}
//==========================================================================
// Event Handlers
//==========================================================================
protected function addedToStageHandler(event:Event):void
{
freeze = false;
parentContainer = parent;
stage.addEventListener(Event.RESIZE, resizeHandler);
stage.addEventListener(Event.REMOVED_FROM_STAGE,
removeFromStageHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, shortcutKey);
resizeHandler(null);
}
private function removeFromStageHandler():void
{
freeze = true;
stage.removeEventListener(Event.RESIZE, resizeHandler);
stage.removeEventListener(Event.REMOVED_FROM_STAGE,
removeFromStageHandler);
}
protected function resizeHandler(event:Event):void
{
width = Math.min(stage.stageWidth, 600);
height = stage.stageHeight;
x = int((stage.stageWidth - width)/2);
}
private function loaderQueue_taskAddedHandler(event:LoaderQueueEvent):void
{
addTask(ILoaderAdapter(event.customData));
}
private function loaderQueue_taskRemovedHandler(event:LoaderQueueEvent):void
{
removeTask(ILoaderAdapter(event.customData));
}
private function item_completeHandler(event:Event):void
{
if(onlyButton.selected)
{
sortItemY();
}
}
/**
* 更新是否仅仅显示真正加载的对象.
* @param event
*
*/
private function onlyProgressingItems(event:Event):void
{
sortItemY();
scrollPane.update();
}
/**
* shortcutKey handler.
* @param e
*/
private function shortcutKey(event:KeyboardEvent):void
{
var effective:Boolean = false;
if (event.shiftKey && event.altKey && event.ctrlKey &&
event.keyCode == Keyboard.L)
{
effective = true;
}
if (Capabilities.os.toLowerCase().indexOf("mac") != -1)
{
if (event.shiftKey && event.ctrlKey && event.keyCode == Keyboard.L)
{
effective = true;
}
}
if (effective)
{
if (parent && parent.contains(this))
{
parent.removeChild(this);
}
else if(parentContainer)
{
parentContainer.addChild(this);
}
}
}
}
}
|
package net.manaca.loaderqueue.inspector
{
import com.bit101.components.CheckBox;
import com.bit101.components.ScrollPane;
import com.bit101.components.Style;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.system.Capabilities;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.ui.Keyboard;
import flash.utils.Dictionary;
import net.manaca.loaderqueue.ILoaderAdapter;
import net.manaca.loaderqueue.ILoaderQueue;
import net.manaca.loaderqueue.LoaderAdapterState;
import net.manaca.loaderqueue.LoaderQueueEvent;
/**
* 提供一个可视化界面用户查看加载队列进行情况.
* @author wersling
*
*/
public class LoaderInspector extends Sprite
{
//==========================================================================
// Constructor
//==========================================================================
/**
* 构造函数.
* @param loaderQueue 需要监视的加载队列.
*
*/
public function LoaderInspector(loaderQueue:ILoaderQueue = null)
{
super();
this.loaderQueue = loaderQueue;
initDisplay();
}
//==========================================================================
// Variables
//==========================================================================
private var scrollPane:ScrollPane;
private var container:DisplayObjectContainer;
private var onlyButton:CheckBox;
private var itemsMap:Dictionary = new Dictionary(true);
private var parentContainer:DisplayObjectContainer;
//==========================================================================
// Properties
//==========================================================================
private var _loaderQueue:ILoaderQueue;
/**
* 需要监视的加载队列.
* @return
*
*/
public function get loaderQueue():ILoaderQueue
{
return _loaderQueue;
}
public function set loaderQueue(value:ILoaderQueue):void
{
if(_loaderQueue && _loaderQueue != value)
{
removeEvents();
clearAllTask();
}
_loaderQueue = value;
if(_loaderQueue)
{
addEvents();
}
}
private var _height:Number = 0;
/**
* @private
*/
override public function get height():Number
{
return _height;
}
override public function set height(value:Number):void
{
_height = value;
layout();
}
private var _width:Number = 0;
/**
* @private
*/
override public function get width():Number
{
return _width;
}
override public function set width(value:Number):void
{
_width = value;
layout();
}
//----------------------------------
// freeze
//----------------------------------
private var _freeze:Boolean = true;
/**
* 是否冻结,如果冻结,则不更新界面.
* @return
*
*/
protected function get freeze():Boolean
{
return _freeze;
}
protected function set freeze(value:Boolean):void
{
if(_freeze != value)
{
_freeze = value;
for each (var item:InspectorItem in itemsMap)
{
item.freeze = freeze;
}
if(!freeze)
{
layout();
}
}
}
//==========================================================================
// Methods
//==========================================================================
/**
* 初始化界面
*
*/
private function initDisplay():void
{
addEventListener(Event.ADDED_TO_STAGE,
addedToStageHandler);
var titleLabel:TextField = new TextField();
titleLabel.autoSize = "left";
titleLabel.selectable = false;
titleLabel.text = "LoaderInspector v0.1";
titleLabel.x = 5;
titleLabel.y = 3;
var tf:TextFormat = new TextFormat(Style.fontName, 12, 0x000000, true);
titleLabel.setTextFormat(tf);
addChild(titleLabel);
container = new Sprite();
addChild(container);
onlyButton = new CheckBox(this, 20, 8,
"Only Progressing", onlyProgressingItems);
scrollPane = new ScrollPane(this, 5, 25);
scrollPane.content.addChild(container);
scrollPane.autoHideScrollBar = true;
}
/**
* 添加队列事件
*
*/
private function addEvents():void
{
loaderQueue.addEventListener(LoaderQueueEvent.TASK_ADDED,
loaderQueue_taskAddedHandler);
loaderQueue.addEventListener(LoaderQueueEvent.TASK_REMOVED,
loaderQueue_taskRemovedHandler);
}
/**
* 删除队列事件
*
*/
private function removeEvents():void
{
loaderQueue.removeEventListener(LoaderQueueEvent.TASK_ADDED,
loaderQueue_taskAddedHandler);
loaderQueue.removeEventListener(LoaderQueueEvent.TASK_REMOVED,
loaderQueue_taskRemovedHandler);
}
/**
* 重新布局,调整UI
*
*/
private function layout():void
{
if(freeze)
{
return;
}
graphics.clear();
graphics.beginFill(0x141E26);
graphics.drawRect(0, 0, width, height);
graphics.drawRect(1, 1, width - 2, height - 2);
graphics.beginFill(0xC3E8FC, 1);
graphics.drawRect(1, 1, width - 2, height - 2);
for each (var item:InspectorItem in itemsMap)
{
item.width = width - 20;
}
sortItemY();
onlyButton.x = width - 140;
scrollPane.width = width - 10;
scrollPane.height = height - 30;
scrollPane.update();
}
/**
* 对队列中的加载对象进行排序
*
*/
private function sortItemY():void
{
if(freeze)
{
return;
}
var cy:int = 5;
var items:Array = [];
for each (var item:InspectorItem in itemsMap)
{
//判断是否只显示正在加载的对象
if(onlyButton.selected)
{
if(item.loaderAdapter.state == LoaderAdapterState.STARTED)
{
items.push(item);
}
else if(container.contains(item))
{
container.removeChild(item);
}
}
else
{
items.push(item);
}
}
//排序
items.sortOn(["priority", "index"]);
//调整位置
for each (item in items)
{
container.addChild(item);
item.y = cy;
cy += 35;
}
}
/**
* 销毁该对象
*
*/
public function dispose():void
{
if(loaderQueue)
{
removeEvents();
clearAllTask();
}
if(container)
{
scrollPane.content.removeChild(container);
container = null;
}
if(scrollPane)
{
scrollPane = null;
}
if(onlyButton)
{
removeChild(onlyButton);
onlyButton = null;
}
parentContainer = null;
}
/**
* 清除所有加载对象
*
*/
private function clearAllTask():void
{
for each (var item:InspectorItem in itemsMap)
{
removeTask(item.loaderAdapter);
}
}
/**
* 添加一个加载对象
* @param loaderAdapter
*
*/
private function addTask(loaderAdapter:ILoaderAdapter):void
{
if(loaderAdapter)
{
var item:InspectorItem = new InspectorItem(loaderAdapter);
item.addEventListener(Event.CHANGE,
item_completeHandler);
item.width = width - 20;
item.freeze = freeze;
itemsMap[loaderAdapter] = item;
sortItemY();
scrollPane.update();
}
}
/**
* 删除一个加载对象
* @param loaderAdapter
*
*/
private function removeTask(loaderAdapter:ILoaderAdapter):void
{
if(loaderAdapter && itemsMap[loaderAdapter])
{
var item:InspectorItem = itemsMap[loaderAdapter];
item.removeEventListener(Event.CHANGE,
item_completeHandler);
item.dispose();
itemsMap[loaderAdapter] = null;
sortItemY();
scrollPane.update();
}
}
//==========================================================================
// Event Handlers
//==========================================================================
protected function addedToStageHandler(event:Event):void
{
freeze = false;
parentContainer = parent;
stage.addEventListener(Event.RESIZE, resizeHandler);
stage.addEventListener(Event.REMOVED_FROM_STAGE,
removeFromStageHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, shortcutKey);
resizeHandler(null);
}
private function removeFromStageHandler():void
{
freeze = true;
stage.removeEventListener(Event.RESIZE, resizeHandler);
stage.removeEventListener(Event.REMOVED_FROM_STAGE,
removeFromStageHandler);
}
protected function resizeHandler(event:Event):void
{
width = Math.min(stage.stageWidth, 600);
height = stage.stageHeight;
x = int((stage.stageWidth - width)/2);
}
private function loaderQueue_taskAddedHandler(event:LoaderQueueEvent):void
{
addTask(ILoaderAdapter(event.customData));
}
private function loaderQueue_taskRemovedHandler(event:LoaderQueueEvent):void
{
removeTask(ILoaderAdapter(event.customData));
}
private function item_completeHandler(event:Event):void
{
if(onlyButton.selected)
{
sortItemY();
}
}
/**
* 更新是否仅仅显示真正加载的对象.
* @param event
*
*/
private function onlyProgressingItems(event:Event):void
{
sortItemY();
scrollPane.update();
}
/**
* shortcutKey handler.
* @param e
*/
private function shortcutKey(event:KeyboardEvent):void
{
var effective:Boolean = false;
if (event.shiftKey && event.altKey && event.ctrlKey &&
event.keyCode == Keyboard.L)
{
effective = true;
}
if (Capabilities.os.toLowerCase().indexOf("mac") != -1)
{
if (event.shiftKey && event.ctrlKey && event.keyCode == Keyboard.L)
{
effective = true;
}
}
if (effective)
{
if (parent && parent.contains(this))
{
parent.removeChild(this);
}
else if(parentContainer)
{
parentContainer.addChild(this);
}
}
}
}
}
|
Update LoaderInspector.dispose for best GC.
|
Update LoaderInspector.dispose for best GC.
|
ActionScript
|
mit
|
wersling/LoaderQueue
|
6e08f80ad5c7806e3c00fbe93f244bafa7bed69c
|
src/battlecode/client/viewer/render/ImageAssets.as
|
src/battlecode/client/viewer/render/ImageAssets.as
|
package battlecode.client.viewer.render {
public class ImageAssets {
// control bar background
[Embed('/img/client/background.png')] public static const GRADIENT_BACKGROUND:Class;
[Embed('/img/client/hud_unit_underlay.png')] public static const HUD_ARCHON_BACKGROUND:Class;
// button icons
[Embed('/img/client/icons/control_play.png')] public static const PLAY_ICON:Class;
[Embed('/img/client/icons/control_pause.png')] public static const PAUSE_ICON:Class;
[Embed('/img/client/icons/control_start.png')] public static const START_ICON:Class;
[Embed('/img/client/icons/control_fastforward.png')] public static const FASTFORWARD_ICON:Class;
[Embed('/img/client/icons/resultset_next.png')] public static const NEXT_ICON:Class;
[Embed('/img/client/icons/resultset_previous.png')] public static const PREVIOUS_ICON:Class;
[Embed('/img/client/icons/control_fastforward_blue.png')] public static const STEP_FORWARD_ICON:Class;
[Embed('/img/client/icons/control_rewind_blue.png')] public static const STEP_BACKWARD_ICON:Class;
[Embed('/img/client/icons/arrow_out.png')] public static const ENTER_FULLSCREEN_ICON:Class;
[Embed('/img/client/icons/arrow_in.png')] public static const EXIT_FULLSCREEN_ICON:Class;
// unit avatars
[Embed('/img/units/hq0.png')] public static const HQ_NEUTRAL:Class;
[Embed('/img/units/hq1.png')] public static const HQ_A:Class;
[Embed('/img/units/hq2.png')] public static const HQ_B:Class;
[Embed('/img/units/soldier0.png')] public static const SOLDIER_NEUTRAL:Class;
[Embed('/img/units/soldier1.png')] public static const SOLDIER_A:Class;
[Embed('/img/units/soldier2.png')] public static const SOLDIER_B:Class;
[Embed('/img/units/medbay0.png')] public static const PLACEHOLDER:Class; // TODO
// explosions images
[Embed('/img/explode/explode64_f01.png')] public static const EXPLODE_1:Class;
[Embed('/img/explode/explode64_f02.png')] public static const EXPLODE_2:Class;
[Embed('/img/explode/explode64_f03.png')] public static const EXPLODE_3:Class;
[Embed('/img/explode/explode64_f04.png')] public static const EXPLODE_4:Class;
[Embed('/img/explode/explode64_f05.png')] public static const EXPLODE_5:Class;
[Embed('/img/explode/explode64_f06.png')] public static const EXPLODE_6:Class;
[Embed('/img/explode/explode64_f07.png')] public static const EXPLODE_7:Class;
[Embed('/img/explode/explode64_f08.png')] public static const EXPLODE_8:Class;
public function ImageAssets() { }
}
}
|
package battlecode.client.viewer.render {
public class ImageAssets {
// control bar background
[Embed('/img/client/background.png')] public static const GRADIENT_BACKGROUND:Class;
[Embed('/img/client/hud_unit_underlay.png')] public static const HUD_ARCHON_BACKGROUND:Class;
// button icons
[Embed('/img/client/icons/control_play.png')] public static const PLAY_ICON:Class;
[Embed('/img/client/icons/control_pause.png')] public static const PAUSE_ICON:Class;
[Embed('/img/client/icons/control_start.png')] public static const START_ICON:Class;
[Embed('/img/client/icons/control_fastforward.png')] public static const FASTFORWARD_ICON:Class;
[Embed('/img/client/icons/resultset_next.png')] public static const NEXT_ICON:Class;
[Embed('/img/client/icons/resultset_previous.png')] public static const PREVIOUS_ICON:Class;
[Embed('/img/client/icons/control_fastforward_blue.png')] public static const STEP_FORWARD_ICON:Class;
[Embed('/img/client/icons/control_rewind_blue.png')] public static const STEP_BACKWARD_ICON:Class;
[Embed('/img/client/icons/arrow_out.png')] public static const ENTER_FULLSCREEN_ICON:Class;
[Embed('/img/client/icons/arrow_in.png')] public static const EXIT_FULLSCREEN_ICON:Class;
// unit avatars
[Embed('/img/units/hq0.png')] public static const HQ_NEUTRAL:Class;
[Embed('/img/units/hq1.png')] public static const HQ_A:Class;
[Embed('/img/units/hq2.png')] public static const HQ_B:Class;
[Embed('/img/units/soldier0.png')] public static const SOLDIER_NEUTRAL:Class;
[Embed('/img/units/soldier1.png')] public static const SOLDIER_A:Class;
[Embed('/img/units/soldier2.png')] public static const SOLDIER_B:Class;
[Embed('/img/units/medbay0.png')] public static const MEDBAY_NEUTRAL:Class;
[Embed('/img/units/medbay1.png')] public static const MEDBAY_A:Class;
[Embed('/img/units/medbay2.png')] public static const MEDBAY_B:Class;
[Embed('/img/units/shields0.png')] public static const SHIELDS_NEUTRAL:Class;
[Embed('/img/units/shields1.png')] public static const SHIELDS_A:Class;
[Embed('/img/units/shields2.png')] public static const SHIELDS_B:Class;
[Embed('/img/units/artillery0.png')] public static const ARTILLERY_NEUTRAL:Class;
[Embed('/img/units/artillery1.png')] public static const ARTILLERY_A:Class;
[Embed('/img/units/artillery2.png')] public static const ARTILLERY_B:Class;
[Embed('/img/units/generator0.png')] public static const GENERATOR_NEUTRAL:Class;
[Embed('/img/units/generator1.png')] public static const GENERATOR_A:Class;
[Embed('/img/units/generator2.png')] public static const GENERATOR_B:Class;
[Embed('/img/units/supplier0.png')] public static const SUPPLIER_NEUTRAL:Class;
[Embed('/img/units/supplier1.png')] public static const SUPPLIER_A:Class;
[Embed('/img/units/supplier2.png')] public static const SUPPLIER_B:Class;
// explosions images
[Embed('/img/explode/explode64_f01.png')] public static const EXPLODE_1:Class;
[Embed('/img/explode/explode64_f02.png')] public static const EXPLODE_2:Class;
[Embed('/img/explode/explode64_f03.png')] public static const EXPLODE_3:Class;
[Embed('/img/explode/explode64_f04.png')] public static const EXPLODE_4:Class;
[Embed('/img/explode/explode64_f05.png')] public static const EXPLODE_5:Class;
[Embed('/img/explode/explode64_f06.png')] public static const EXPLODE_6:Class;
[Embed('/img/explode/explode64_f07.png')] public static const EXPLODE_7:Class;
[Embed('/img/explode/explode64_f08.png')] public static const EXPLODE_8:Class;
public function ImageAssets() { }
}
}
|
add missing unit image bindings
|
add missing unit image bindings
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
b24d9a48cf63dbbb5d3c071c92766960e52d8f0b
|
WeaveData/src/weave/data/DataSources/RDataSource.as
|
WeaveData/src/weave/data/DataSources/RDataSource.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 weave.data.DataSources
{
import flash.events.ErrorEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import weave.api.core.ILinkableObject;
import weave.api.data.ColumnMetadata;
import weave.api.data.IAttributeColumn;
import weave.api.data.IColumnReference;
import weave.api.data.IDataSource;
import weave.api.data.IDataSource_Service;
import weave.api.data.IWeaveTreeNode;
import weave.api.detectLinkableObjectChange;
import weave.api.disposeObject;
import weave.api.getCallbackCollection;
import weave.api.getLinkableDescendants;
import weave.api.getSessionState;
import weave.api.linkableObjectIsBusy;
import weave.api.newLinkableChild;
import weave.api.registerLinkableChild;
import weave.api.reportError;
import weave.core.LinkableHashMap;
import weave.core.LinkablePromise;
import weave.core.LinkableString;
import weave.data.AttributeColumns.ProxyColumn;
import weave.data.AttributeColumns.ReferencedColumn;
import weave.data.hierarchy.ColumnTreeNode;
import weave.services.AMF3Servlet;
import weave.services.JsonCache;
import weave.services.WeaveRServlet;
import weave.services.addAsyncResponder;
import weave.utils.ColumnUtils;
import weave.utils.VectorUtils;
public class RDataSource extends AbstractDataSource implements IDataSource_Service
{
WeaveAPI.ClassRegistry.registerImplementation(IDataSource, RDataSource, "R Data Source");
public static const SCRIPT_OUTPUT_NAME:String = 'scriptOutputName';
private static const RESULT_DATA:String = "resultData";
private static const COLUMN_NAMES:String = "columnNames";
public function RDataSource()
{
promise.depend(url, scriptName, inputs, hierarchyRefresh);
}
public const url:LinkableString = registerLinkableChild(this, new LinkableString('/WeaveAnalystServices/ComputationalServlet'), handleURLChange);
public const scriptName:LinkableString = newLinkableChild(this, LinkableString);
public const inputs:LinkableHashMap = newLinkableChild(this, LinkableHashMap);
private const promise:LinkablePromise = registerLinkableChild(this, new LinkablePromise(runScript, describePromise));
private function describePromise():String { return lang("Running script {0}", scriptName.value); }
private const outputCSV:CSVDataSource = newLinkableChild(this, CSVDataSource);
private var _service:AMF3Servlet;
override protected function initialize():void
{
super.initialize();
promise.validate();
}
private function handleURLChange():void
{
if (_service && _service.servletURL == url.value)
return;
disposeObject(_service);
_service = registerLinkableChild(this, new AMF3Servlet(url.value));
hierarchyRefresh.triggerCallbacks();
}
private function runScript():void
{
// if callbacks are delayed, we assume that hierarchyRefresh will be explicitly triggered later.
if (getCallbackCollection(this).callbacksAreDelayed)
return;
// force retrieval of referenced columns
for each (var refCol:ReferencedColumn in getLinkableDescendants(inputs, ReferencedColumn))
refCol.getInternalColumn();
if (linkableObjectIsBusy(inputs))
return;
var keyType:String;
var simpleInputs:Object = {};
var columnsByKeyType:Object = {}; // Object(keyType -> Array of IAttributeColumn)
var tableData:Object = {}; // Object(inputName -> { columnName : column })
var columnData:Object = {}; // Object(keyType -> {keys: [], columns: Object(name -> Array) })
var joined:Array = [];
var colMap:Object = {};
for each (var obj:ILinkableObject in inputs.getObjects())
{
var name:String = inputs.getName(obj);
// if the input is a column
var column:IAttributeColumn = obj as IAttributeColumn;
if (column)
{
keyType = column.getMetadata(ColumnMetadata.KEY_TYPE);
var columnArray:Array = columnsByKeyType[keyType] || (columnsByKeyType[keyType] = [])
columnArray.push(column);
for (keyType in columnsByKeyType)
{
var cols:Array = columnsByKeyType[keyType];
joined = ColumnUtils.joinColumns(cols, null, true);
var keys:Array = VectorUtils.pluck(joined.shift() as Array, 'localName');
colMap = {};
for (var i:int = 0; i < joined.length; i++)
colMap[ inputs.getName(cols[i]) ] = joined[i];
columnData[keyType] = {keys: keys, columns: colMap};
}
}
else
{
var columns:Array = obj as Array;
// if the input is an array of columns
if(columns)
{
var flag:Boolean = false;
if(!columns.length)
return;
column = columns[0] as IAttributeColumn;
keyType = column.getMetadata(ColumnMetadata.KEY_TYPE);
for each (var col:IAttributeColumn in columns)
{
flag = col.getMetadata(ColumnMetadata.KEY_TYPE) != keyType;
colMap[col.getMetadata(ColumnMetadata.TITLE)] = col;
}
if(flag) {
reportError("Columns in table input must all be of the same keyType");
return;
} else {
tableData[name] = colMap;
}
} else {
// if the input is just a value (number, string or boolean)
simpleInputs[name] = getSessionState(inputs.getObject(name));
}
}
}
outputCSV.setCSVData(null);
outputCSV.metadata.setSessionState(null);
addAsyncResponder(
_service.invokeAsyncMethod('runScriptWithInputs', [scriptName.value, simpleInputs, columnData, tableData]),
handleScriptResult,
handleScriptError,
getSessionState(this)
);
}
private function handleScriptResult(event:ResultEvent, sessionState:Object):void
{
// ignore outdated response
if (WeaveAPI.SessionManager.computeDiff(sessionState, getSessionState(this)) !== undefined)
return;
var result:Object = event.result;
var columnNames:Array = result[COLUMN_NAMES]; // array of strings
var resultData:Array = result[RESULT_DATA]; // array of columns
if (resultData)
{
var rows:Array = VectorUtils.transpose(resultData);
rows.unshift(columnNames);
outputCSV.setCSVData(rows);
}
else
outputCSV.setCSVData(null);
}
private function handleScriptError(event:FaultEvent, sessionState:Object):void
{
// ignore outdated response
if (WeaveAPI.SessionManager.computeDiff(sessionState, getSessionState(this)) !== undefined)
return;
reportError(event);
}
override public function getHierarchyRoot():IWeaveTreeNode
{
if (!_rootNode)
{
var name:String = WeaveAPI.globalHashMap.getName(this);
var source:RDataSource = this;
_rootNode = new ColumnTreeNode({
label: name,
dataSource: this,
dependency: outputCSV,
hasChildBranches: false,
children: function():Array {
var csvRoot:IWeaveTreeNode = outputCSV.getHierarchyRoot();
return csvRoot.getChildren().map(function(csvNode:IColumnReference, ..._):IWeaveTreeNode {
var meta:Object = csvNode.getColumnMetadata();
meta[SCRIPT_OUTPUT_NAME] = meta[CSVDataSource.METADATA_COLUMN_NAME];
return generateHierarchyNode(meta);
});
}
});
}
return _rootNode;
}
override protected function generateHierarchyNode(metadata:Object):IWeaveTreeNode
{
if (!metadata)
return null;
return new ColumnTreeNode({
dataSource: this,
idFields: [SCRIPT_OUTPUT_NAME],
data: metadata
});
}
override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void
{
var name:String = proxyColumn.getMetadata(SCRIPT_OUTPUT_NAME);
var column:IAttributeColumn = outputCSV.getColumnById(name);
if (column)
proxyColumn.setInternalColumn(column);
else
proxyColumn.dataUnavailable();
}
}
}
|
/* ***** 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 weave.data.DataSources
{
import flash.events.ErrorEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import weave.api.core.ILinkableObject;
import weave.api.data.ColumnMetadata;
import weave.api.data.IAttributeColumn;
import weave.api.data.IColumnReference;
import weave.api.data.IDataSource;
import weave.api.data.IDataSource_Service;
import weave.api.data.IWeaveTreeNode;
import weave.api.detectLinkableObjectChange;
import weave.api.disposeObject;
import weave.api.getCallbackCollection;
import weave.api.getLinkableDescendants;
import weave.api.getSessionState;
import weave.api.linkableObjectIsBusy;
import weave.api.newLinkableChild;
import weave.api.registerLinkableChild;
import weave.api.reportError;
import weave.core.LinkableHashMap;
import weave.core.LinkablePromise;
import weave.core.LinkableString;
import weave.data.AttributeColumns.ProxyColumn;
import weave.data.AttributeColumns.ReferencedColumn;
import weave.data.hierarchy.ColumnTreeNode;
import weave.services.AMF3Servlet;
import weave.services.JsonCache;
import weave.services.WeaveRServlet;
import weave.services.addAsyncResponder;
import weave.utils.ColumnUtils;
import weave.utils.VectorUtils;
public class RDataSource extends AbstractDataSource implements IDataSource_Service
{
WeaveAPI.ClassRegistry.registerImplementation(IDataSource, RDataSource, "R Data Source");
public static const SCRIPT_OUTPUT_NAME:String = 'scriptOutputName';
private static const RESULT_DATA:String = "resultData";
private static const COLUMN_NAMES:String = "columnNames";
public function RDataSource()
{
promise.depend(url, scriptName, inputs, hierarchyRefresh);
}
public const url:LinkableString = registerLinkableChild(this, new LinkableString('/WeaveAnalystServices/ComputationalServlet'), handleURLChange);
public const scriptName:LinkableString = newLinkableChild(this, LinkableString);
public const inputs:LinkableHashMap = newLinkableChild(this, LinkableHashMap);
private const promise:LinkablePromise = registerLinkableChild(this, new LinkablePromise(runScript, describePromise));
private function describePromise():String { return lang("Running script {0}", scriptName.value); }
private const outputCSV:CSVDataSource = newLinkableChild(this, CSVDataSource);
private var _service:AMF3Servlet;
override protected function initialize():void
{
super.initialize();
promise.validate();
}
private function handleURLChange():void
{
if (_service && _service.servletURL == url.value)
return;
disposeObject(_service);
_service = registerLinkableChild(this, new AMF3Servlet(url.value));
hierarchyRefresh.triggerCallbacks();
}
private function runScript():void
{
// if callbacks are delayed, we assume that hierarchyRefresh will be explicitly triggered later.
if (getCallbackCollection(this).callbacksAreDelayed)
return;
// force retrieval of referenced columns
for each (var refCol:ReferencedColumn in getLinkableDescendants(inputs, ReferencedColumn))
refCol.getInternalColumn();
if (linkableObjectIsBusy(inputs))
return;
var keyType:String;
var simpleInputs:Object = {};
var columnsByKeyType:Object = {}; // Object(keyType -> Array of IAttributeColumn)
for each (var obj:ILinkableObject in inputs.getObjects())
{
var name:String = inputs.getName(obj);
var column:IAttributeColumn = obj as IAttributeColumn;
if (column)
{
keyType = column.getMetadata(ColumnMetadata.KEY_TYPE);
var columnArray:Array = columnsByKeyType[keyType] || (columnsByKeyType[keyType] = [])
columnArray.push(column);
}
else
{
simpleInputs[name] = getSessionState(inputs.getObject(name));
}
}
var columnData:Object = {}; // Object(keyType -> {keys: [], columns: Object(name -> Array) })
for (keyType in columnsByKeyType)
{
var cols:Array = columnsByKeyType[keyType];
var joined:Array = ColumnUtils.joinColumns(cols, null, true);
var keys:Array = VectorUtils.pluck(joined.shift() as Array, 'localName');
var colMap:Object = {};
for (var i:int = 0; i < joined.length; i++)
colMap[ inputs.getName(cols[i]) ] = joined[i];
columnData[keyType] = {keys: keys, columns: colMap};
}
outputCSV.setCSVData(null);
outputCSV.metadata.setSessionState(null);
addAsyncResponder(
_service.invokeAsyncMethod('runScriptWithInputs', [scriptName.value, simpleInputs, columnData]),
handleScriptResult,
handleScriptError,
getSessionState(this)
);
}
private function handleScriptResult(event:ResultEvent, sessionState:Object):void
{
// ignore outdated response
if (WeaveAPI.SessionManager.computeDiff(sessionState, getSessionState(this)) !== undefined)
return;
var result:Object = event.result;
var columnNames:Array = result[COLUMN_NAMES]; // array of strings
var resultData:Array = result[RESULT_DATA]; // array of columns
if (resultData)
{
var rows:Array = VectorUtils.transpose(resultData);
rows.unshift(columnNames);
outputCSV.setCSVData(rows);
}
else
outputCSV.setCSVData(null);
}
private function handleScriptError(event:FaultEvent, sessionState:Object):void
{
// ignore outdated response
if (WeaveAPI.SessionManager.computeDiff(sessionState, getSessionState(this)) !== undefined)
return;
reportError(event);
}
override public function getHierarchyRoot():IWeaveTreeNode
{
if (!_rootNode)
{
var name:String = WeaveAPI.globalHashMap.getName(this);
var source:RDataSource = this;
_rootNode = new ColumnTreeNode({
label: name,
dataSource: this,
dependency: outputCSV,
hasChildBranches: false,
children: function():Array {
var csvRoot:IWeaveTreeNode = outputCSV.getHierarchyRoot();
return csvRoot.getChildren().map(function(csvNode:IColumnReference, ..._):IWeaveTreeNode {
var meta:Object = csvNode.getColumnMetadata();
meta[SCRIPT_OUTPUT_NAME] = meta[CSVDataSource.METADATA_COLUMN_NAME];
return generateHierarchyNode(meta);
});
}
});
}
return _rootNode;
}
override protected function generateHierarchyNode(metadata:Object):IWeaveTreeNode
{
if (!metadata)
return null;
return new ColumnTreeNode({
dataSource: this,
idFields: [SCRIPT_OUTPUT_NAME],
data: metadata
});
}
override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void
{
var name:String = proxyColumn.getMetadata(SCRIPT_OUTPUT_NAME);
var column:IAttributeColumn = outputCSV.getColumnById(name);
if (column)
proxyColumn.setInternalColumn(column);
else
proxyColumn.dataUnavailable();
}
}
}
|
revert RDataSource to previous revision
|
revert RDataSource to previous revision
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
5ad98797821215e084e57e5f78bab4a01c11365e
|
krew-framework/krewfw/core_internal/NotificationService.as
|
krew-framework/krewfw/core_internal/NotificationService.as
|
package krewfw.core_internal {
import flash.utils.Dictionary;
import krewfw.utils.krew;
import krewfw.core.KrewGameObject;
//------------------------------------------------------------
public class NotificationService {
private var _publishers:Dictionary = new Dictionary();
private var _listenerCount:int = 0;
private var _messageQueue:Vector.<Object> = new Vector.<Object>();
//------------------------------------------------------------
public function NotificationService() {
}
public function addListener(listener:KrewGameObject,
eventType:String, callback:Function):void {
if (!_publishers[eventType]) {
_publishers[eventType] = new NotificationPublisher(eventType);
krew.fwlog('+++ create publisher: ' + eventType + ' +++');
}
_publishers[eventType].addListener(listener, callback);
}
public function removeListener(listener:KrewGameObject, eventType:String):Boolean {
if (!_publishers[eventType]) {
krew.fwlog('[Error] Event publisher is absent: ' + eventType);
return false;
}
_publishers[eventType].removeListener(listener);
if (_publishers[eventType].numListener == 0) {
delete _publishers[eventType];
krew.fwlog('--- delete publisher: ' + eventType + ' ---');
}
return true;
}
public function postMessage(eventType:String, eventArgs:Object):void {
_messageQueue.push({
type: eventType,
args: eventArgs
});
}
public function broadcastMessage():void {
if (_messageQueue.length == 0) { return; }
var processingMsgs:Vector.<Object> = _messageQueue.slice(); // copy vector
_messageQueue = new Vector.<Object>(); // clear vector
for each (var msg:Object in processingMsgs) {
var eventType:String = msg.type;
if (!_publishers[eventType]) { continue; }
var eventArgs:Object = msg.args;
var publisher:NotificationPublisher = _publishers[eventType];
publisher.publish(eventArgs);
}
// ToDo: for の中で Message 投げられてたら再帰
}
}
}
|
package krewfw.core_internal {
import flash.utils.Dictionary;
import krewfw.utils.krew;
import krewfw.core.KrewGameObject;
//------------------------------------------------------------
public class NotificationService {
public static var MAX_LOOP_COUNT:int = 8;
private var _publishers:Dictionary = new Dictionary();
private var _listenerCount:int = 0;
private var _messageQueue:Vector.<Object> = new Vector.<Object>();
//------------------------------------------------------------
public function NotificationService() {}
public function addListener(listener:KrewGameObject,
eventType:String, callback:Function):void {
if (!_publishers[eventType]) {
_publishers[eventType] = new NotificationPublisher(eventType);
krew.fwlog('+++ create publisher: ' + eventType + ' +++');
}
_publishers[eventType].addListener(listener, callback);
}
public function removeListener(listener:KrewGameObject, eventType:String):Boolean {
if (!_publishers[eventType]) {
krew.fwlog('[Error] Event publisher is absent: ' + eventType);
return false;
}
_publishers[eventType].removeListener(listener);
if (_publishers[eventType].numListener == 0) {
delete _publishers[eventType];
krew.fwlog('--- delete publisher: ' + eventType + ' ---');
}
return true;
}
public function postMessage(eventType:String, eventArgs:Object):void {
_messageQueue.push({
type: eventType,
args: eventArgs
});
}
public function broadcastMessage(recallCount:int=0):void {
if (_messageQueue.length == 0) { return; }
var processingMsgs:Vector.<Object> = _messageQueue.slice(); // copy vector
_messageQueue = new Vector.<Object>(); // clear vector
for each (var msg:Object in processingMsgs) {
var eventType:String = msg.type;
if (!_publishers[eventType]) { continue; }
var eventArgs:Object = msg.args;
var publisher:NotificationPublisher = _publishers[eventType];
publisher.publish(eventArgs);
}
// イベントのハンドリングの中でさらに Message が投げられていた場合、
// 再帰して投げられるイベントがなくなるまで処理を継続する。
// ただし Actor 間でイベントを投げ合うループ構造ができてしまうと無限ループになるため
// セーフティとして試行回数には制限をかける
if (_messageQueue.length > 0 && recallCount < MAX_LOOP_COUNT) {
this.broadcastMessage(recallCount + 1);
} else {
// 処理しきれなかったイベントは諦める(そうしないとイベントの数が肥大化しうるから)
// * そもそもここが呼ばれる場合は設計が間違っている。
// このログは出力されないべきである
_messageQueue = new Vector.<Object>();
krew.fwlog('[Warning!!] Event handling seems to be infinite loop!');
}
}
}
}
|
Modify NotificationService
|
Modify NotificationService
|
ActionScript
|
mit
|
tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework,tatsuya-koyama/krewFramework
|
eed6b4179cb6fc23d0ba562327d1579af634096a
|
src/com/benoitfreslon/layoutmanager/LayoutLoader.as
|
src/com/benoitfreslon/layoutmanager/LayoutLoader.as
|
package com.benoitfreslon.layoutmanager {
import flash.display.MovieClip;
import flash.events.Event;
import flash.system.Capabilities;
import flash.utils.getDefinitionByName;
import starling.display.Button;
import starling.display.DisplayObject;
import starling.display.DisplayObjectContainer;
import starling.display.Image;
import starling.display.Quad;
import starling.display.Sprite;
import starling.text.TextField;
import starling.textures.Texture;
import starling.utils.AssetManager;
import starling.display.ButtonExtended;
/**
* Loader of Layout
* @version 1.04
* @author Benoît Freslon
*/
public class LayoutLoader {
private var _movieclip : MovieClip;
private var _displayObject : DisplayObjectContainer;
private var _rootObject : DisplayObjectContainer;
private var _assetManager : AssetManager;
static public var debug : Boolean = false;
private var onLoad : Function = function() : void {
};
/**
* Loader of Layout class.
*/
public function LayoutLoader() {
super();
debug = Capabilities.isDebugger
}
/**
* Load a layout from a MovieClip added in ActionScript.
* Embed a SWC file with all your layouts in your ActionScript 3.0 project and use this lib to load and display your layouts.
*
* @param displayObject The starling.display.DisplayObject where the layout should be displayed
* @param LayoutClass The layout class Embed in the SWC file.
* @param assetManager The AssetManager instance where all assets are loaded.
* @param callBack The callback function when the layout is loaded and displayed.
*/
public function loadLayout( rootObject : DisplayObjectContainer , LayoutClass : Class , assetManager : AssetManager , callBack : Function = null ) : void {
if ( debug )
trace( "LayoutLoader: loadLayout" , rootObject , LayoutClass , assetManager , callBack );
_rootObject = rootObject;
_displayObject = rootObject;
_assetManager = assetManager;
_movieclip = new LayoutClass();
_movieclip.addEventListener( Event.ENTER_FRAME , layoutLoaded );
if ( onLoad != null )
onLoad = callBack
}
public function loadLayoutIn( rootObject : DisplayObjectContainer , displayObject : DisplayObjectContainer , LayoutClass : Class , assetManager : AssetManager , callBack : Function = null ) : void {
if ( debug )
trace( "LayoutLoader: loadLayoutIn" , rootObject , displayObject , LayoutClass , assetManager , callBack );
_rootObject = rootObject
_displayObject = displayObject;
_assetManager = assetManager;
_movieclip = new LayoutClass();
_movieclip.addEventListener( Event.ENTER_FRAME , layoutLoaded );
if ( onLoad != null )
onLoad = callBack
}
private function layoutLoaded( e : Event ) : void {
if ( debug )
trace( "LayoutLoader: layoutLoaded" );
_movieclip.removeEventListener( Event.ENTER_FRAME , layoutLoaded );
parseMovieClip( _movieclip , _rootObject , _displayObject );
loaded();
}
private function parseMovieClip( mc : MovieClip , root : DisplayObjectContainer , container : DisplayObjectContainer ) : void {
var child : BFObject;
var n : int = mc.numChildren;
for ( var i : uint = 0 ; i < n ; ++i ) {
child = mc.getChildAt( i ) as BFObject;
if ( child ) {
if ( child.mainClass ) {
var a : Array = [ ButtonExtended ];
var objectClass : Class;
if ( child.className ) {
objectClass = getDefinitionByName( child.className ) as Class;
} else {
objectClass = getDefinitionByName( child.mainClass ) as Class;
}
var obj : DisplayObject;
if ( child.mainClass == "starling.display.Image" ) {
obj = addImage( objectClass , child as BFImage );
} else if ( child.mainClass == "starling.display.ButtonExtended" ) {
obj = addButton( objectClass , child as BFButton );
} else if ( child.mainClass == "starling.text.TextField" ) {
obj = addTextField( objectClass , child as BFTextField );
} else if ( child.mainClass == "starling.display.Sprite" ) {
obj = addSprite( objectClass , child as BFSprite );
} else {
throw new Error( "No mainClass defined in '" + child + "'" );
}
if ( child.hasOwnProperty( "params" ) ) {
for ( var metatags : String in child.params ) {
if ( obj.hasOwnProperty( metatags ) )
obj[ metatags ] = child.params[ metatags ];
}
}
obj.name = child.name;
obj.x = int( child.x );
obj.y = int( child.y );
//obj.scaleX = child.scaleX;
//obj.scaleY = child.scaleY;
if ( child.flipX ) {
obj.scaleX = -1;
}
if ( child.flipY ) {
obj.scaleY = -1;
}
obj.alpha = child.alpha;
obj.rotation = child.rotation;
obj.visible = child.isVisible;
container.addChild( obj );
if ( obj.hasOwnProperty( "tag" ) ) {
obj[ "tag" ] = child.tag;
}
if ( obj.hasOwnProperty( "userData" ) ) {
obj[ "userData" ] = child.userData;
}
if ( _rootObject.hasOwnProperty( child.name ) ) {
_rootObject[ child.name ] = obj as objectClass;
} else if ( child.name.split( "__id" ).length == 1 && child.name.split( "instance" ).length == 1 ) {
throw new Error( "No public property '" + child.name + "' declared in " + _rootObject );
}
} else {
//trace( new Error( "No className defined " + child ) );
}
}
}
}
private function loaded() : void {
_assetManager = null;
_displayObject = null;
_movieclip = null;
_rootObject = null;
onLoad();
}
private function addImage( objectClass : Class , child : BFImage ) : Image {
var tex : Texture = getTexture( child , child.texture , child.width , child.height )
var img : Image = new objectClass( tex ) as Image;
img.pivotX = int( img.width * child.pivotX );
img.pivotY = int( img.height * child.pivotY );
return img;
}
private function addSprite( objectClass : Class , child : BFSprite ) : Sprite {
var s : Sprite = new objectClass() as Sprite;
parseMovieClip( child as MovieClip , s as DisplayObjectContainer , s as DisplayObjectContainer );
return s;
}
private function addTextField( objectClass : Class , child : BFTextField ) : TextField {
var t : TextField = new objectClass( child.width , child.height , "" ) as TextField;
t.autoSize = child.autoSize;
t.fontName = child.fontName;
t.fontSize = child.fontSize;
t.color = child.color;
t.hAlign = child.hAlign;
t.vAlign = child.vAlign;
t.bold = child.bold;
t.italic = child.italic;
t.border = child.border;
t.underline = child.underline;
t.pivotX = int( t.width * child.pivotX );
t.pivotY = int( t.height * child.pivotY );
var text : String = child.text;
text = text.replace( "\\r" , "\r" );
text = text.replace( "\\n" , "\n" );
text = text.replace( "\\t" , "\t" );
t.text = text;
t.width = child.width;
t.height = child.height;
return t;
}
// TODO Parse BFButton and addChild objects inside Button
private function addButton( objectClass : Class , child : BFButton ) : Button {
var bt : Button = new objectClass( getTexture( child , child.upState , child.width , child.height ) ) as Button;
bt.fontBold = child.bold;
bt.fontColor = child.color;
bt.fontName = child.fontName;
bt.fontSize = child.fontSize;
bt.alphaWhenDisabled = child.alphaWhenDisabled;
bt.scaleWhenDown = child.scaleWhenDown;
bt.text = child.text;
bt.pivotX = int( bt.width * child.pivotX );
bt.pivotY = int( bt.height * child.pivotY );
if ( child.downState )
bt.downState = _assetManager.getTexture( child.downState );
if ( bt.hasOwnProperty( "overState" ) && child.overState )
bt[ "overState" ] = _assetManager.getTexture( child.overState );
if ( bt.hasOwnProperty( "onTouch" ) && _rootObject.hasOwnProperty( child.onTouch ) ) {
bt[ "onTouch" ] = _rootObject[ child.onTouch ];
} else if ( bt.hasOwnProperty( "onTouch" ) && child.onTouch != "" && !_rootObject.hasOwnProperty( child.onTouch ) ) {
throw new Error( "The public method '" + child.onTouch + "' is not defined in " + _rootObject ) ;
}
return bt;
}
private function getTexture( child : BFObject , textureName : String , w : Number , h : Number ) : Texture {
if ( textureName == "" ) {
//trace( new Error( "No texture defined in '" + child + " - name: "+child.name+"' in "+_displayObject+". Default texture used." ) );
return Texture.empty( w , h );
} else {
var tex : Texture = _assetManager.getTexture( textureName );
if ( tex == null ) {
trace( new Error( "Texture '" + textureName + "' defined in '" + child + " - name: " + child.name + "' in " + _displayObject + " doesn't exist. Default texture used." ));
return Texture.empty( w , h );
}
return tex;
}
}
}
}
|
package com.benoitfreslon.layoutmanager {
import flash.display.MovieClip;
import flash.events.Event;
import flash.system.Capabilities;
import flash.utils.getDefinitionByName;
import starling.display.Button;
import starling.display.ButtonExtended;
import starling.display.DisplayObject;
import starling.display.DisplayObjectContainer;
import starling.display.Image;
import starling.display.Quad;
import starling.display.Sprite;
import starling.text.TextField;
import starling.textures.Texture;
import starling.utils.AssetManager;
/**
* Loader of Layout
* @version 1.04
* @author Benoît Freslon
*/
public class LayoutLoader {
private var _movieclip : MovieClip;
private var _displayObject : DisplayObjectContainer;
private var _rootObject : DisplayObjectContainer;
private var _assetManager : AssetManager;
static public var debug : Boolean = false;
private var onLoad : Function = function() : void {
};
/**
* Loader of Layout class.
*/
public function LayoutLoader() {
super();
debug = Capabilities.isDebugger
}
/**
* Load a layout from a MovieClip added in ActionScript.
* Embed a SWC file with all your layouts in your ActionScript 3.0 project and use this lib to load and display your layouts.
*
* @param displayObject The starling.display.DisplayObject where the layout should be displayed
* @param LayoutClass The layout class Embed in the SWC file.
* @param assetManager The AssetManager instance where all assets are loaded.
* @param callBack The callback function when the layout is loaded and displayed.
*/
public function loadLayout( rootObject : DisplayObjectContainer , LayoutClass : Class , assetManager : AssetManager , callBack : Function = null ) : void {
if ( debug )
trace( "LayoutLoader: loadLayout" , rootObject , LayoutClass , assetManager , callBack );
_rootObject = rootObject;
_displayObject = rootObject;
_assetManager = assetManager;
_movieclip = new LayoutClass();
_movieclip.addEventListener( Event.ENTER_FRAME , layoutLoaded );
if ( onLoad != null )
onLoad = callBack
}
public function loadLayoutIn( rootObject : DisplayObjectContainer , displayObject : DisplayObjectContainer , LayoutClass : Class , assetManager : AssetManager , callBack : Function = null ) : void {
if ( debug )
trace( "LayoutLoader: loadLayoutIn" , rootObject , displayObject , LayoutClass , assetManager , callBack );
_rootObject = rootObject
_displayObject = displayObject;
_assetManager = assetManager;
_movieclip = new LayoutClass();
_movieclip.addEventListener( Event.ENTER_FRAME , layoutLoaded );
if ( onLoad != null )
onLoad = callBack
}
private function layoutLoaded( e : Event ) : void {
if ( debug )
trace( "LayoutLoader: layoutLoaded" );
_movieclip.removeEventListener( Event.ENTER_FRAME , layoutLoaded );
parseMovieClip( _movieclip , _rootObject , _displayObject );
loaded();
}
private function parseMovieClip( mc : MovieClip , root : DisplayObjectContainer , container : DisplayObjectContainer ) : void {
var child : BFObject;
var n : int = mc.numChildren;
for ( var i : uint = 0 ; i < n ; ++i ) {
child = mc.getChildAt( i ) as BFObject;
if ( child ) {
if ( child.mainClass ) {
var a : Array = [ ButtonExtended ];
var objectClass : Class;
if (debug) trace(child.className);
if ( child.className ) {
objectClass = getDefinitionByName( child.className ) as Class;
} else {
objectClass = getDefinitionByName( child.mainClass ) as Class;
}
var obj : DisplayObject;
if ( child.mainClass == "starling.display.Image" ) {
obj = addImage( objectClass , child as BFImage );
} else if ( child.mainClass == "starling.display.ButtonExtended" ) {
obj = addButton( objectClass , child as BFButton );
} else if ( child.mainClass == "starling.text.TextField" ) {
obj = addTextField( objectClass , child as BFTextField );
} else if ( child.mainClass == "starling.display.Sprite" ) {
obj = addSprite( objectClass , child as BFSprite );
} else {
throw new Error( "No mainClass defined in '" + child + "'" );
}
if ( child.hasOwnProperty( "params" ) ) {
for ( var metatags : String in child.params ) {
if ( obj.hasOwnProperty( metatags ) )
obj[ metatags ] = child.params[ metatags ];
}
}
obj.name = child.name;
obj.x = int( child.x );
obj.y = int( child.y );
//obj.scaleX = child.scaleX;
//obj.scaleY = child.scaleY;
if ( child.flipX ) {
obj.scaleX = -1;
}
if ( child.flipY ) {
obj.scaleY = -1;
}
obj.alpha = child.alpha;
obj.rotation = child.rotation;
obj.visible = child.isVisible;
container.addChild( obj );
if ( obj.hasOwnProperty( "tag" ) ) {
obj[ "tag" ] = child.tag;
}
if ( obj.hasOwnProperty( "userData" ) ) {
obj[ "userData" ] = child.userData;
}
if ( _rootObject.hasOwnProperty( child.name ) ) {
_rootObject[ child.name ] = obj as objectClass;
} else if ( child.name.split( "__id" ).length == 1 && child.name.split( "instance" ).length == 1 ) {
throw new Error( "No public property '" + child.name + "' declared in " + _rootObject );
}
} else {
//trace( new Error( "No className defined " + child ) );
}
}
}
}
private function loaded() : void {
_assetManager = null;
_displayObject = null;
_movieclip = null;
_rootObject = null;
onLoad();
}
private function addImage( objectClass : Class , child : BFImage ) : Image {
var tex : Texture = getTexture( child , child.texture , child.width , child.height )
var img : Image = new objectClass( tex ) as Image;
img.pivotX = int( img.width * child.pivotX );
img.pivotY = int( img.height * child.pivotY );
return img;
}
private function addSprite( objectClass : Class , child : BFSprite ) : Sprite {
var s : Sprite = new objectClass() as Sprite;
parseMovieClip( child as MovieClip , s as DisplayObjectContainer , s as DisplayObjectContainer );
return s;
}
private function addTextField( objectClass : Class , child : BFTextField ) : TextField {
var t : TextField = new objectClass( child.width , child.height , "" ) as TextField;
t.autoSize = child.autoSize;
t.fontName = child.fontName;
t.fontSize = child.fontSize;
t.color = child.color;
t.hAlign = child.hAlign;
t.vAlign = child.vAlign;
t.bold = child.bold;
t.italic = child.italic;
t.border = child.border;
t.underline = child.underline;
t.pivotX = int( t.width * child.pivotX );
t.pivotY = int( t.height * child.pivotY );
var text : String = child.text;
text = text.replace( "\\r" , "\r" );
text = text.replace( "\\n" , "\n" );
text = text.replace( "\\t" , "\t" );
t.text = text;
t.width = child.width;
t.height = child.height;
return t;
}
// TODO Parse BFButton and addChild objects inside Button
private function addButton( objectClass : Class , child : BFButton ) : Button {
var bt : Button = new objectClass( getTexture( child , child.upState , child.width , child.height ) ) as Button;
bt.fontBold = child.bold;
bt.fontColor = child.color;
bt.fontName = child.fontName;
bt.fontSize = child.fontSize;
bt.alphaWhenDisabled = child.alphaWhenDisabled;
bt.scaleWhenDown = child.scaleWhenDown;
bt.text = child.text;
bt.pivotX = int( bt.width * child.pivotX );
bt.pivotY = int( bt.height * child.pivotY );
if ( child.downState )
bt.downState = _assetManager.getTexture( child.downState );
if ( bt.hasOwnProperty( "overState" ) && child.overState )
bt[ "overState" ] = _assetManager.getTexture( child.overState );
if ( bt.hasOwnProperty( "onTouch" ) && _rootObject.hasOwnProperty( child.onTouch ) ) {
bt[ "onTouch" ] = _rootObject[ child.onTouch ];
} else if ( bt.hasOwnProperty( "onTouch" ) && child.onTouch != "" && !_rootObject.hasOwnProperty( child.onTouch ) ) {
throw new Error( "The public method '" + child.onTouch + "' is not defined in " + _rootObject ) ;
}
return bt;
}
private function getTexture( child : BFObject , textureName : String , w : Number , h : Number ) : Texture {
if ( textureName == "" ) {
//trace( new Error( "No texture defined in '" + child + " - name: "+child.name+"' in "+_displayObject+". Default texture used." ) );
return Texture.empty( w , h );
} else {
var tex : Texture = _assetManager.getTexture( textureName );
if ( tex == null ) {
trace( new Error( "Texture '" + textureName + "' defined in '" + child + " - name: " + child.name + "' in " + _displayObject + " doesn't exist. Default texture used." ));
return Texture.empty( w , h );
}
return tex;
}
}
}
}
|
Debug message
|
Debug message
|
ActionScript
|
mit
|
BenoitFreslon/benoitfreslon-layoutmanager
|
4ad0f6ea7e4e59c016584c8276895735f2406fcb
|
frameworks/projects/Core/as/src/org/apache/flex/core/HTMLElementWrapper.as
|
frameworks/projects/Core/as/src/org/apache/flex/core/HTMLElementWrapper.as
|
package org.apache.flex.core
{
COMPILE::JS
{
import org.apache.flex.events.BrowserEvent;
import org.apache.flex.events.EventDispatcher;
import goog.events;
}
[ExcludeClass]
COMPILE::AS3
public class HTMLElementWrapper {}
COMPILE::JS
public class HTMLElementWrapper extends EventDispatcher implements IStrand
{
//--------------------------------------
// Static Property
//--------------------------------------
static public var googFireListener:Function;
/**
* The properties that triggers the static initializer
*/
static public var installedOverride:Boolean = installOverride();
//--------------------------------------
// Static Function
//--------------------------------------
/**
* @param listener The listener object to call {goog.events.Listener}.
* @param eventObject The event object to pass to the listener.
* @return Result of listener.
*/
static public function fireListenerOverride(listener:Object, eventObject:BrowserEvent):Boolean
{
var e:BrowserEvent = new BrowserEvent();
e.wrappedEvent = eventObject.wrappedEvent;
return HTMLElementWrapper.googFireListener(listener, e);
}
/**
* Static initializer
*/
static public function installOverride():Boolean
{
HTMLElementWrapper.googFireListener = events.fireListener;
events.fireListener = HTMLElementWrapper.fireListenerOverride;
return true;
}
//--------------------------------------
// Property
//--------------------------------------
public var element:EventTarget;
public var model:IBead;
protected var beads:Array;
protected var internalDisplay:String = 'inline';
//--------------------------------------
// Function
//--------------------------------------
public function get MXMLDescriptor():Array
{
return null;
}
/**
* @param bead The new bead.
*/
public function addBead(bead:IBead):void
{
if (!beads)
{
beads = [];
}
beads.push(bead);
if (bead is IBeadModel)
{
model = bead;
}
bead.strand = this;
}
/**
* @param classOrInterface The requested bead type.
* @return The bead.
*/
public function getBeadByType(classOrInterface:Class):IBead
{
var bead:IBead, i:uint, n:uint;
n = beads.length;
for (i = 0; i < n; i++)
{
bead = beads[i];
if (bead is classOrInterface)
{
return bead;
}
}
return null;
}
/**
* @param bead The bead to remove.
* @return The bead.
*/
public function removeBead(bead:IBead):IBead
{
var i:uint, n:uint, value:Object;
n = beads.length;
for (i = 0; i < n; i++)
{
value = beads[i];
if (bead === value)
{
beads.splice(i, 1);
return bead;
}
}
return null;
}
}
}
|
package org.apache.flex.core
{
COMPILE::JS
{
import org.apache.flex.events.BrowserEvent;
import org.apache.flex.events.EventDispatcher;
import goog.events;
import goog.events.EventTarget;
}
COMPILE::JS
public class HTMLElementWrapper extends EventDispatcher implements IStrand
{
//--------------------------------------
// Static Property
//--------------------------------------
static public var googFireListener:Function;
/**
* The properties that triggers the static initializer
*/
static public var installedOverride:Boolean = installOverride();
//--------------------------------------
// Static Function
//--------------------------------------
/**
* @param listener The listener object to call {goog.events.Listener}.
* @param eventObject The event object to pass to the listener.
* @return Result of listener.
*/
static public function fireListenerOverride(listener:Object, eventObject:BrowserEvent):Boolean
{
var e:BrowserEvent = new BrowserEvent();
e.wrappedEvent = eventObject.wrappedEvent;
return HTMLElementWrapper.googFireListener(listener, e);
}
/**
* Static initializer
*/
static public function installOverride():Boolean
{
HTMLElementWrapper.googFireListener = goog.events.fireListener;
goog.events.fireListener = HTMLElementWrapper.fireListenerOverride;
return true;
}
//--------------------------------------
// Property
//--------------------------------------
public var element:EventTarget;
public var model:IBead;
protected var beads:Array;
protected var internalDisplay:String = 'inline';
//--------------------------------------
// Function
//--------------------------------------
public function get MXMLDescriptor():Array
{
return null;
}
/**
* @param bead The new bead.
*/
public function addBead(bead:IBead):void
{
if (!beads)
{
beads = [];
}
beads.push(bead);
if (bead is IBeadModel)
{
model = bead;
}
bead.strand = this;
}
/**
* @param classOrInterface The requested bead type.
* @return The bead.
*/
public function getBeadByType(classOrInterface:Class):IBead
{
var bead:IBead, i:uint, n:uint;
n = beads.length;
for (i = 0; i < n; i++)
{
bead = beads[i];
if (bead is classOrInterface)
{
return bead;
}
}
return null;
}
/**
* @param bead The bead to remove.
* @return The bead.
*/
public function removeBead(bead:IBead):IBead
{
var i:uint, n:uint, value:Object;
n = beads.length;
for (i = 0; i < n; i++)
{
value = beads[i];
if (bead === value)
{
beads.splice(i, 1);
return bead;
}
}
return null;
}
}
}
|
tweak HTMLElementWrapper to use a goog.events class
|
tweak HTMLElementWrapper to use a goog.events class
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
987d40ad3be7f15286746da058f5800c3c48375d
|
WeaveJS/src/weavejs/data/source/GeoJSONDataSource.as
|
WeaveJS/src/weavejs/data/source/GeoJSONDataSource.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.source
{
import weavejs.WeaveAPI;
import weavejs.api.data.ColumnMetadata;
import weavejs.api.data.DataType;
import weavejs.api.data.IDataSource;
import weavejs.api.data.IDataSource_File;
import weavejs.api.data.IWeaveTreeNode;
import weavejs.core.LinkableFile;
import weavejs.core.LinkableString;
import weavejs.data.column.GeometryColumn;
import weavejs.data.column.NumberColumn;
import weavejs.data.column.ProxyColumn;
import weavejs.data.column.StringColumn;
import weavejs.geom.GeneralizedGeometry;
import weavejs.geom.GeoJSON;
import weavejs.net.ResponseType;
import weavejs.util.ArrayUtils;
import weavejs.util.JS;
public class GeoJSONDataSource extends AbstractDataSource implements IDataSource_File
{
WeaveAPI.ClassRegistry.registerImplementation(IDataSource, GeoJSONDataSource, "GeoJSON file");
public function GeoJSONDataSource()
{
}
public const url:LinkableFile = Weave.linkableChild(this, new LinkableFile(null, null, ResponseType.JSON), handleFile);
public const keyType:LinkableString = Weave.linkableChild(this, LinkableString);
public const keyProperty:LinkableString = Weave.linkableChild(this, LinkableString);
/**
* Overrides the projection specified in the GeoJSON object.
*/
public const projection:LinkableString = Weave.linkableChild(this, LinkableString);
/**
* The GeoJSON data.
*/
private var jsonData:GeoJSONDataSourceData = null;
/**
* Gets the projection metadata used in the geometry column.
*/
public function getProjection():String
{
return projection.value
|| (jsonData ? jsonData.projection : null)
|| "EPSG:4326";
}
/**
* Gets the keyType metadata used in the columns.
*/
public function getKeyType():String
{
var kt:String = keyType.value;
if (!kt)
{
kt = url.value;
if (keyProperty.value)
kt += "#" + keyProperty.value;
}
return kt;
}
override protected function get initializationComplete():Boolean
{
return super.initializationComplete && !Weave.isBusy(url) && jsonData;
}
/**
* This gets called as a grouped callback.
*/
override protected function initialize(forceRefresh:Boolean = false):void
{
_rootNode = null;
if (Weave.detectChange(initialize, keyType, keyProperty))
{
if (jsonData)
jsonData.resetQKeys(getKeyType(), keyProperty.value);
}
// recalculate all columns previously requested because data may have changed.
super.initialize(true);
}
private function handleFile():void
{
if (Weave.isBusy(url))
return;
jsonData = null;
if (!url.result)
{
hierarchyRefresh.triggerCallbacks();
if (url.error)
JS.error(url.error);
return;
}
try
{
var obj:Object = url.result;
// make sure it's valid GeoJSON
if (!GeoJSON.isGeoJSONObject(obj))
throw new Error("Invalid GeoJSON file: " + url.value);
// parse data
jsonData = new GeoJSONDataSourceData(obj, getKeyType(), keyProperty.value);
hierarchyRefresh.triggerCallbacks();
}
catch (e:Error)
{
JS.error(e);
}
}
/**
* Gets the root node of the attribute hierarchy.
*/
override public function getHierarchyRoot():IWeaveTreeNode
{
if (!(_rootNode is GeoJSONDataSourceNode))
{
var meta:Object = {};
meta[ColumnMetadata.TITLE] = Weave.getRoot(this).getName(this);
var rootChildren:Array = [];
if (jsonData)
{
// include empty string for the geometry column
rootChildren = [''].concat(jsonData.propertyNames)
.map(function(n:String, i:*, a:*):*{ return generateHierarchyNode(n); })
.filter(function(n:Object, ..._):Boolean{ return n != null; });
}
_rootNode = new GeoJSONDataSourceNode(this, meta, rootChildren);
}
return _rootNode;
}
override protected function generateHierarchyNode(metadata:Object):IWeaveTreeNode
{
if (metadata == null || !jsonData)
return null;
if (metadata is String)
{
var str:String = metadata as String;
metadata = {};
metadata[GEOJSON_PROPERTY_NAME] = str;
}
if (metadata && metadata.hasOwnProperty(GEOJSON_PROPERTY_NAME))
{
metadata = getMetadataForProperty(metadata[GEOJSON_PROPERTY_NAME]);
return new GeoJSONDataSourceNode(this, metadata, null, [GEOJSON_PROPERTY_NAME]);
}
return null;
}
override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void
{
var propertyName:String = proxyColumn.getMetadata(GEOJSON_PROPERTY_NAME);
var metadata:Object = getMetadataForProperty(propertyName);
if (!metadata || !jsonData || (propertyName && jsonData.propertyNames.indexOf(propertyName) < 0))
{
proxyColumn.dataUnavailable();
return;
}
proxyColumn.setMetadata(metadata);
var dataType:String = metadata[ColumnMetadata.DATA_TYPE];
if (dataType == DataType.GEOMETRY)
{
var qkeys:Array = [];
var geoms:Array = [];
var i:int = 0;
var initGeoms:Function = function(stopTime:int):Number
{
if (!jsonData)
{
proxyColumn.dataUnavailable();
return 1;
}
for (; i < jsonData.qkeys.length; i++)
{
if (JS.now() > stopTime)
return i / jsonData.qkeys.length;
var geomsFromJson:Array = GeneralizedGeometry.fromGeoJson(jsonData.geometries[i]);
for each (var geom:GeneralizedGeometry in geomsFromJson)
{
qkeys.push(jsonData.qkeys[i]);
geoms.push(geom);
}
}
return 1;
}
var setGeoms:Function = function():void
{
var gc:GeometryColumn = new GeometryColumn(metadata);
gc.setRecords(qkeys, geoms);
proxyColumn.setInternalColumn(gc);
}
// high priority because not much can be done without data
WeaveAPI.Scheduler.startTask(proxyColumn, initGeoms, WeaveAPI.TASK_PRIORITY_HIGH, setGeoms);
}
else
{
var data:Array = ArrayUtils.pluck(jsonData.properties, propertyName);
var type:String = jsonData.propertyTypes[propertyName];
if (type == 'number')
{
var nc:NumberColumn = new NumberColumn(metadata);
nc.setRecords(jsonData.qkeys, data);
proxyColumn.setInternalColumn(nc);
}
else
{
var sc:StringColumn = new StringColumn(metadata);
sc.setRecords(jsonData.qkeys, data);
proxyColumn.setInternalColumn(sc);
}
}
}
private function getMetadataForProperty(propertyName:String):Object
{
if (!jsonData)
return null;
var meta:Object = null;
if (!propertyName)
{
meta = {};
meta[GEOJSON_PROPERTY_NAME] = '';
meta[ColumnMetadata.TITLE] = getGeomColumnTitle();
meta[ColumnMetadata.KEY_TYPE] = getKeyType();
meta[ColumnMetadata.DATA_TYPE] = DataType.GEOMETRY;
meta[ColumnMetadata.PROJECTION] = getProjection();
}
else if (jsonData.propertyNames.indexOf(propertyName) >= 0)
{
meta = {};
meta[GEOJSON_PROPERTY_NAME] = propertyName;
meta[ColumnMetadata.TITLE] = propertyName;
meta[ColumnMetadata.KEY_TYPE] = getKeyType();
if (propertyName == keyProperty.value)
meta[ColumnMetadata.DATA_TYPE] = getKeyType();
else
meta[ColumnMetadata.DATA_TYPE] = jsonData.propertyTypes[propertyName];
}
return meta;
}
private static const GEOJSON_PROPERTY_NAME:String = 'geoJsonPropertyName';
private function getGeomColumnTitle():String
{
return Weave.lang("{0} geometry", Weave.getRoot(this).getName(this));
}
}
}
|
/* ***** 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.source
{
import weavejs.WeaveAPI;
import weavejs.api.data.ColumnMetadata;
import weavejs.api.data.DataType;
import weavejs.api.data.IDataSource;
import weavejs.api.data.IDataSource_File;
import weavejs.api.data.IWeaveTreeNode;
import weavejs.core.LinkableFile;
import weavejs.core.LinkableString;
import weavejs.data.column.GeometryColumn;
import weavejs.data.column.NumberColumn;
import weavejs.data.column.ProxyColumn;
import weavejs.data.column.StringColumn;
import weavejs.geom.GeneralizedGeometry;
import weavejs.geom.GeoJSON;
import weavejs.net.ResponseType;
import weavejs.util.ArrayUtils;
import weavejs.util.JS;
public class GeoJSONDataSource extends AbstractDataSource implements IDataSource_File
{
WeaveAPI.ClassRegistry.registerImplementation(IDataSource, GeoJSONDataSource, "GeoJSON file");
public function GeoJSONDataSource()
{
}
public const url:LinkableFile = Weave.linkableChild(this, new LinkableFile(null, null, ResponseType.JSON), handleFile);
public const keyType:LinkableString = Weave.linkableChild(this, LinkableString);
public const keyProperty:LinkableString = Weave.linkableChild(this, LinkableString);
/**
* Overrides the projection specified in the GeoJSON object.
*/
public const projection:LinkableString = Weave.linkableChild(this, LinkableString);
/**
* The GeoJSON data.
*/
private var jsonData:GeoJSONDataSourceData = null;
/**
* Gets the projection metadata used in the geometry column.
*/
public function getProjection():String
{
return projection.value
|| (jsonData ? jsonData.projection : null)
|| "EPSG:4326";
}
/**
* Gets the keyType metadata used in the columns.
*/
public function getPropertyNames():Array/*Array<string>*/
{
return (jsonData && jsonData.propertyNames) ? [].concat(jsonData.propertyNames) : [];
}
public function getKeyType():String
{
var kt:String = keyType.value;
if (!kt)
{
kt = url.value;
if (keyProperty.value)
kt += "#" + keyProperty.value;
}
return kt;
}
override protected function get initializationComplete():Boolean
{
return super.initializationComplete && !Weave.isBusy(url) && jsonData;
}
/**
* This gets called as a grouped callback.
*/
override protected function initialize(forceRefresh:Boolean = false):void
{
_rootNode = null;
if (Weave.detectChange(initialize, keyType, keyProperty))
{
if (jsonData)
jsonData.resetQKeys(getKeyType(), keyProperty.value);
}
// recalculate all columns previously requested because data may have changed.
super.initialize(true);
}
private function handleFile():void
{
if (Weave.isBusy(url))
return;
jsonData = null;
if (!url.result)
{
hierarchyRefresh.triggerCallbacks();
if (url.error)
JS.error(url.error);
return;
}
try
{
var obj:Object = url.result;
// make sure it's valid GeoJSON
if (!GeoJSON.isGeoJSONObject(obj))
throw new Error("Invalid GeoJSON file: " + url.value);
// parse data
jsonData = new GeoJSONDataSourceData(obj, getKeyType(), keyProperty.value);
hierarchyRefresh.triggerCallbacks();
}
catch (e:Error)
{
JS.error(e);
}
}
/**
* Gets the root node of the attribute hierarchy.
*/
override public function getHierarchyRoot():IWeaveTreeNode
{
if (!(_rootNode is GeoJSONDataSourceNode))
{
var meta:Object = {};
meta[ColumnMetadata.TITLE] = Weave.getRoot(this).getName(this);
var rootChildren:Array = [];
if (jsonData)
{
// include empty string for the geometry column
rootChildren = [''].concat(jsonData.propertyNames)
.map(function(n:String, i:*, a:*):*{ return generateHierarchyNode(n); })
.filter(function(n:Object, ..._):Boolean{ return n != null; });
}
_rootNode = new GeoJSONDataSourceNode(this, meta, rootChildren);
}
return _rootNode;
}
override protected function generateHierarchyNode(metadata:Object):IWeaveTreeNode
{
if (metadata == null || !jsonData)
return null;
if (metadata is String)
{
var str:String = metadata as String;
metadata = {};
metadata[GEOJSON_PROPERTY_NAME] = str;
}
if (metadata && metadata.hasOwnProperty(GEOJSON_PROPERTY_NAME))
{
metadata = getMetadataForProperty(metadata[GEOJSON_PROPERTY_NAME]);
return new GeoJSONDataSourceNode(this, metadata, null, [GEOJSON_PROPERTY_NAME]);
}
return null;
}
override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void
{
var propertyName:String = proxyColumn.getMetadata(GEOJSON_PROPERTY_NAME);
var metadata:Object = getMetadataForProperty(propertyName);
if (!metadata || !jsonData || (propertyName && jsonData.propertyNames.indexOf(propertyName) < 0))
{
proxyColumn.dataUnavailable();
return;
}
proxyColumn.setMetadata(metadata);
var dataType:String = metadata[ColumnMetadata.DATA_TYPE];
if (dataType == DataType.GEOMETRY)
{
var qkeys:Array = [];
var geoms:Array = [];
var i:int = 0;
var initGeoms:Function = function(stopTime:int):Number
{
if (!jsonData)
{
proxyColumn.dataUnavailable();
return 1;
}
for (; i < jsonData.qkeys.length; i++)
{
if (JS.now() > stopTime)
return i / jsonData.qkeys.length;
var geomsFromJson:Array = GeneralizedGeometry.fromGeoJson(jsonData.geometries[i]);
for each (var geom:GeneralizedGeometry in geomsFromJson)
{
qkeys.push(jsonData.qkeys[i]);
geoms.push(geom);
}
}
return 1;
}
var setGeoms:Function = function():void
{
var gc:GeometryColumn = new GeometryColumn(metadata);
gc.setRecords(qkeys, geoms);
proxyColumn.setInternalColumn(gc);
}
// high priority because not much can be done without data
WeaveAPI.Scheduler.startTask(proxyColumn, initGeoms, WeaveAPI.TASK_PRIORITY_HIGH, setGeoms);
}
else
{
var data:Array = ArrayUtils.pluck(jsonData.properties, propertyName);
var type:String = jsonData.propertyTypes[propertyName];
if (type == 'number')
{
var nc:NumberColumn = new NumberColumn(metadata);
nc.setRecords(jsonData.qkeys, data);
proxyColumn.setInternalColumn(nc);
}
else
{
var sc:StringColumn = new StringColumn(metadata);
sc.setRecords(jsonData.qkeys, data);
proxyColumn.setInternalColumn(sc);
}
}
}
private function getMetadataForProperty(propertyName:String):Object
{
if (!jsonData)
return null;
var meta:Object = null;
if (!propertyName)
{
meta = {};
meta[GEOJSON_PROPERTY_NAME] = '';
meta[ColumnMetadata.TITLE] = getGeomColumnTitle();
meta[ColumnMetadata.KEY_TYPE] = getKeyType();
meta[ColumnMetadata.DATA_TYPE] = DataType.GEOMETRY;
meta[ColumnMetadata.PROJECTION] = getProjection();
}
else if (jsonData.propertyNames.indexOf(propertyName) >= 0)
{
meta = {};
meta[GEOJSON_PROPERTY_NAME] = propertyName;
meta[ColumnMetadata.TITLE] = propertyName;
meta[ColumnMetadata.KEY_TYPE] = getKeyType();
if (propertyName == keyProperty.value)
meta[ColumnMetadata.DATA_TYPE] = getKeyType();
else
meta[ColumnMetadata.DATA_TYPE] = jsonData.propertyTypes[propertyName];
}
return meta;
}
private static const GEOJSON_PROPERTY_NAME:String = 'geoJsonPropertyName';
private function getGeomColumnTitle():String
{
return Weave.lang("{0} geometry", Weave.getRoot(this).getName(this));
}
}
}
|
Add getPropertyNames to GeoJSONDataSource
|
Add getPropertyNames to GeoJSONDataSource
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
cd44b366835732e8433c6159395d3756cb1d562e
|
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
|
dolly-framework/src/test/actionscript/dolly/ClonerTest.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.ClassLevelCloneable;
import dolly.data.ClassLevelCopyableCloneable;
import dolly.data.PropertyLevelCloneable;
import dolly.data.PropertyLevelCopyableCloneable;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class ClonerTest {
private var classLevelCloneable:ClassLevelCloneable;
private var classLevelCloneableType:Type;
private var classLevelCopyableCloneable:ClassLevelCopyableCloneable;
private var classLevelCopyableCloneableType:Type;
private var propertyLevelCloneable:PropertyLevelCloneable;
private var propertyLevelCloneableType:Type;
private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable;
private var propertyLevelCopyableCloneableType:Type;
[Before]
public function before():void {
classLevelCloneable = new ClassLevelCloneable();
classLevelCloneable.property1 = "value 1";
classLevelCloneable.property2 = "value 2";
classLevelCloneable.property3 = "value 3";
classLevelCloneable.writableField = "value 4";
classLevelCloneableType = Type.forInstance(classLevelCloneable);
classLevelCopyableCloneable = new ClassLevelCopyableCloneable();
classLevelCopyableCloneable.property1 = "value 1";
classLevelCopyableCloneable.property2 = "value 2";
classLevelCopyableCloneable.property3 = "value 3";
classLevelCopyableCloneable.writableField = "value 4";
classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable);
propertyLevelCloneable = new PropertyLevelCloneable();
propertyLevelCloneable.property1 = "value 1";
propertyLevelCloneable.property2 = "value 2";
propertyLevelCloneable.property3 = "value 3";
propertyLevelCloneable.writableField = "value 4";
propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable);
propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable();
propertyLevelCopyableCloneable.property1 = "value 1";
propertyLevelCopyableCloneable.property2 = "value 2";
propertyLevelCopyableCloneable.property3 = "value 3";
propertyLevelCopyableCloneable.writableField = "value 4";
propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable);
}
[After]
public function after():void {
classLevelCloneable = null;
classLevelCloneableType = null;
classLevelCopyableCloneable = null;
classLevelCopyableCloneableType = null;
propertyLevelCloneable = null;
propertyLevelCloneableType = null;
propertyLevelCopyableCloneable = null;
propertyLevelCopyableCloneableType = null;
}
[Test]
public function testGetCloneableFieldsForTypeClassLevelCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypeClassLevelCopyableCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCopyableCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypePropertyLevelCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(propertyLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypePropertyLevelCopyableCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(propertyLevelCopyableCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testWithClassLevelCloneable():void {
const clone1:ClassLevelCloneable = Cloner.clone(classLevelCloneable);
assertNotNull(clone1);
assertNotNull(clone1.property1);
assertEquals(clone1.property1, classLevelCloneable.property1);
assertNotNull(clone1.property2);
assertEquals(clone1.property2, classLevelCloneable.property2);
assertNotNull(clone1.property3);
assertEquals(clone1.property3, classLevelCloneable.property3);
assertNotNull(clone1.writableField);
assertEquals(clone1.writableField, classLevelCloneable.writableField);
const clone2:ClassLevelCopyableCloneable = Cloner.clone(classLevelCopyableCloneable);
assertNotNull(clone2);
assertNotNull(clone2.property1);
assertEquals(clone2.property1, classLevelCloneable.property1);
assertNotNull(clone2.property2);
assertEquals(clone2.property2, classLevelCloneable.property2);
assertNotNull(clone2.property3);
assertEquals(clone2.property3, classLevelCloneable.property3);
assertNotNull(clone2.writableField);
assertEquals(clone2.writableField, classLevelCloneable.writableField);
}
[Test]
public function testCloneWithPropertyLevelMetadata():void {
const clone1:PropertyLevelCloneable = Cloner.clone(propertyLevelCloneable);
assertNotNull(clone1);
assertNull(clone1.property1);
assertNotNull(clone1.property2);
assertEquals(clone1.property2, propertyLevelCloneable.property2);
assertNotNull(clone1.property3);
assertEquals(clone1.property3, propertyLevelCloneable.property3);
assertNotNull(clone1.writableField);
assertEquals(clone1.writableField, propertyLevelCloneable.writableField);
const clone2:PropertyLevelCopyableCloneable = Cloner.clone(propertyLevelCopyableCloneable);
assertNotNull(clone2);
assertNotNull(clone2.property1);
assertEquals(clone2.property1, propertyLevelCloneable.property1);
assertNotNull(clone2.property2);
assertEquals(clone2.property2, propertyLevelCloneable.property2);
assertNotNull(clone2.property3);
assertEquals(clone2.property3, propertyLevelCloneable.property3);
assertNotNull(clone2.writableField);
assertEquals(clone2.writableField, propertyLevelCloneable.writableField);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.data.ClassLevelCloneable;
import dolly.data.ClassLevelCopyableCloneable;
import dolly.data.PropertyLevelCloneable;
import dolly.data.PropertyLevelCopyableCloneable;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;
import org.flexunit.asserts.assertNull;
use namespace dolly_internal;
public class ClonerTest {
private var classLevelCloneable:ClassLevelCloneable;
private var classLevelCloneableType:Type;
private var classLevelCopyableCloneable:ClassLevelCopyableCloneable;
private var classLevelCopyableCloneableType:Type;
private var propertyLevelCloneable:PropertyLevelCloneable;
private var propertyLevelCloneableType:Type;
private var propertyLevelCopyableCloneable:PropertyLevelCopyableCloneable;
private var propertyLevelCopyableCloneableType:Type;
[Before]
public function before():void {
classLevelCloneable = new ClassLevelCloneable();
classLevelCloneable.property1 = "value 1";
classLevelCloneable.property2 = "value 2";
classLevelCloneable.property3 = "value 3";
classLevelCloneable.writableField = "value 4";
classLevelCloneableType = Type.forInstance(classLevelCloneable);
classLevelCopyableCloneable = new ClassLevelCopyableCloneable();
classLevelCopyableCloneable.property1 = "value 1";
classLevelCopyableCloneable.property2 = "value 2";
classLevelCopyableCloneable.property3 = "value 3";
classLevelCopyableCloneable.writableField = "value 4";
classLevelCopyableCloneableType = Type.forInstance(classLevelCopyableCloneable);
propertyLevelCloneable = new PropertyLevelCloneable();
propertyLevelCloneable.property1 = "value 1";
propertyLevelCloneable.property2 = "value 2";
propertyLevelCloneable.property3 = "value 3";
propertyLevelCloneable.writableField = "value 4";
propertyLevelCloneableType = Type.forInstance(propertyLevelCloneable);
propertyLevelCopyableCloneable = new PropertyLevelCopyableCloneable();
propertyLevelCopyableCloneable.property1 = "value 1";
propertyLevelCopyableCloneable.property2 = "value 2";
propertyLevelCopyableCloneable.property3 = "value 3";
propertyLevelCopyableCloneable.writableField = "value 4";
propertyLevelCopyableCloneableType = Type.forInstance(propertyLevelCopyableCloneable);
}
[After]
public function after():void {
classLevelCloneable = null;
classLevelCloneableType = null;
classLevelCopyableCloneable = null;
classLevelCopyableCloneableType = null;
propertyLevelCloneable = null;
propertyLevelCloneableType = null;
propertyLevelCopyableCloneable = null;
propertyLevelCopyableCloneableType = null;
}
[Test]
public function testGetCloneableFieldsForTypeClassLevelCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypeClassLevelCopyableCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(classLevelCopyableCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypePropertyLevelCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(propertyLevelCloneableType);
assertNotNull(cloneableFields);
assertEquals(3, cloneableFields.length);
}
[Test]
public function testGetCloneableFieldsForTypePropertyLevelCopyableCloneable():void {
const cloneableFields:Vector.<Field> = Cloner.getCloneableFieldsForType(propertyLevelCopyableCloneableType);
assertNotNull(cloneableFields);
assertEquals(4, cloneableFields.length);
}
[Test]
public function testCloneClassLevelCloneable():void {
const clone:ClassLevelCloneable = Cloner.clone(classLevelCloneable);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, classLevelCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classLevelCloneable.writableField);
}
[Test]
public function testCloneClassLevelCopyableCloneable():void {
const clone:ClassLevelCopyableCloneable = Cloner.clone(classLevelCopyableCloneable);
assertNotNull(clone);
assertNotNull(clone.property1);
assertEquals(clone.property1, classLevelCloneable.property1);
assertNotNull(clone.property2);
assertEquals(clone.property2, classLevelCloneable.property2);
assertNotNull(clone.property3);
assertEquals(clone.property3, classLevelCloneable.property3);
assertNotNull(clone.writableField);
assertEquals(clone.writableField, classLevelCloneable.writableField);
}
[Test]
public function testCloneWithPropertyLevelMetadata():void {
const clone1:PropertyLevelCloneable = Cloner.clone(propertyLevelCloneable);
assertNotNull(clone1);
assertNull(clone1.property1);
assertNotNull(clone1.property2);
assertEquals(clone1.property2, propertyLevelCloneable.property2);
assertNotNull(clone1.property3);
assertEquals(clone1.property3, propertyLevelCloneable.property3);
assertNotNull(clone1.writableField);
assertEquals(clone1.writableField, propertyLevelCloneable.writableField);
const clone2:PropertyLevelCopyableCloneable = Cloner.clone(propertyLevelCopyableCloneable);
assertNotNull(clone2);
assertNotNull(clone2.property1);
assertEquals(clone2.property1, propertyLevelCloneable.property1);
assertNotNull(clone2.property2);
assertEquals(clone2.property2, propertyLevelCloneable.property2);
assertNotNull(clone2.property3);
assertEquals(clone2.property3, propertyLevelCloneable.property3);
assertNotNull(clone2.writableField);
assertEquals(clone2.writableField, propertyLevelCloneable.writableField);
}
}
}
|
Split method "testWithClassLevelCloneable" to a few.
|
Split method "testWithClassLevelCloneable" to a few.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
a462e54e46481de3f65b1daaea3f57214c8d73bd
|
src/as/com/threerings/miso/client/MisoScenePanel.as
|
src/as/com/threerings/miso/client/MisoScenePanel.as
|
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2010 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.miso.client {
import flash.utils.getTimer;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.events.MouseEvent;
import mx.core.ClassFactory;
import as3isolib.display.primitive.IsoBox;
import as3isolib.geom.Pt;
import as3isolib.geom.IsoMath;
import as3isolib.display.scene.IsoScene;
import as3isolib.display.IsoView;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.util.DelayUtil;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.MathUtil;
import com.threerings.util.Set;
import com.threerings.util.Sets;
import com.threerings.util.StringUtil;
import com.threerings.util.maps.WeakValueMap;
import com.threerings.media.tile.BaseTile;
import com.threerings.media.tile.Colorizer;
import com.threerings.media.tile.NoSuchTileSetError;
import com.threerings.media.tile.TileSet;
import com.threerings.media.tile.TileUtil;
import com.threerings.miso.client.MisoMetricsTransformation;
import com.threerings.miso.client.PrioritizedSceneLayoutRenderer;
import com.threerings.miso.data.MisoSceneModel;
import com.threerings.miso.data.ObjectInfo;
import com.threerings.miso.tile.FringeTile;
import com.threerings.miso.util.MisoContext;
import com.threerings.miso.util.ObjectSet;
import com.threerings.miso.util.MisoSceneMetrics;
public class MisoScenePanel extends Sprite
implements PlaceView
{
private var log :Log = Log.getLog(MisoScenePanel);
public function MisoScenePanel (ctx :MisoContext, metrics :MisoSceneMetrics)
{
_ctx = ctx;
// Excitingly, we get to override this globally for as3isolib...
IsoMath.transformationObject = new MisoMetricsTransformation(metrics,
metrics.tilehei * 3 / 4);
_metrics = metrics;
_isoView = new IsoView();
_isoView.setSize(DEF_WIDTH, DEF_HEIGHT);
_isoView.addEventListener(MouseEvent.CLICK, onClick);
addChild(_loading = createLoadingPanel());
}
/**
* Creates whatever we want to show while we're waiting to load our exciting scene tile data.
*/
protected function createLoadingPanel () :DisplayObject
{
// By default we just stick up a basic label for this...
var loadingText :TextField = new TextField();
loadingText.textColor = 0xFFFFFF;
var loadingFmt :TextFormat = new TextFormat();
loadingFmt.size = 24;
loadingText.defaultTextFormat = loadingFmt;
loadingText.autoSize = TextFieldAutoSize.LEFT;
_loadingProgressFunc = function (progress :Number) :void {
loadingText.text = "Loading... " + int(progress*100) + "%";
};
_loadingProgressFunc(0.0);
return loadingText;
}
protected function loadingProgress (progress :Number) :void
{
if (_loadingProgressFunc != null) {
_loadingProgressFunc(progress);
}
}
public function onClick (event :MouseEvent) :void
{
var viewPt :Point = _isoView.globalToLocal(new Point(event.stageX, event.stageY));
moveBy(new Point(viewPt.x - _isoView.width / 2, viewPt.y - _isoView.height / 2));
}
public function moveBy (pt :Point) :void
{
if (_pendingMoveBy != null) {
log.info("Already performing a move...");
return;
}
_pendingMoveBy = pt;
refreshBaseBlockScenes();
}
public function setSceneModel (model :MisoSceneModel) :void
{
_model = model;
_ctx.getTileManager().ensureLoaded(_model.getAllTilesets(), function() :void {
DelayUtil.delayFrame(function() :void {
refreshScene();
removeChild(_loading);
addChild(_isoView);
});
}, loadingProgress);
}
public function willEnterPlace (plobj :PlaceObject) :void
{
}
public function didLeavePlace (plobj :PlaceObject) :void
{
}
/** Computes the fringe tile for the specified coordinate. */
public function computeFringeTile (tx :int, ty :int) :BaseTile
{
return _ctx.getTileManager().getFringer().getFringeTile(_model, tx, ty, _fringes,
_masks);
}
protected function getBaseBlocks () :Set
{
var blocks :Set = Sets.newSetOf(int);
var size :Point = _isoView.size;
var xMove :int = (_pendingMoveBy == null ? 0 : _pendingMoveBy.x);
var yMove :int = (_pendingMoveBy == null ? 0 : _pendingMoveBy.y);
var minX :int = xMove;
var maxX :int = size.x + xMove;
var minY :int = yMove;
var maxY :int = BOTTOM_BUFFER + size.y + yMove;
var topLeft :Point = _isoView.localToIso(new Point(minX, minY));
var topRight :Point = _isoView.localToIso(new Point(maxX, minY));
var btmLeft :Point = _isoView.localToIso(new Point(minX, maxY));
var btmRight :Point = _isoView.localToIso(new Point(maxX, maxY));
for (var yy :int = topRight.y - 1; yy <= btmLeft.y + 1; yy++) {
for (var xx :int = topLeft.x - 1; xx <= btmRight.x + 1; xx++) {
// Toss out any that aren't actually in our view.
var blkTop :Point = _isoView.isoToLocal(new Pt(xx, yy, 0));
var blkRight :Point =
_isoView.isoToLocal(new Pt(xx + SceneBlock.BLOCK_SIZE, yy, 0));
var blkLeft :Point =
_isoView.isoToLocal(new Pt(xx, yy + SceneBlock.BLOCK_SIZE, 0));
var blkBtm :Point =
_isoView.isoToLocal(new Pt(xx + SceneBlock.BLOCK_SIZE,
yy + SceneBlock.BLOCK_SIZE, 0));
if (blkTop.y < maxY &&
blkBtm.y > minY &&
blkLeft.x < maxX &&
blkRight.x > minX) {
blocks.add(SceneBlock.getBlockKey(xx, yy));
}
}
}
return blocks;
}
protected function refreshBaseBlockScenes () :void
{
var blocks :Set = getBaseBlocks();
// Keep this to use in our function...
var thisRef :MisoScenePanel = this;
var resolving :Boolean = false;
blocks.forEach(function(blockKey :int) :void {
if (!_blocks.containsKey(blockKey)) {
var sceneBlock :SceneBlock =
new SceneBlock(blockKey, _objScene, _isoView, _metrics);
_pendingBlocks.add(sceneBlock);
sceneBlock.resolve(_ctx, _model, thisRef, blockResolved);
resolving = true;
}
});
if (!resolving) {
resolutionComplete();
}
}
protected function blockResolved (resolved :SceneBlock) :void
{
if (!_pendingBlocks.contains(resolved)) {
log.info("Trying to resolve non-pending block???: " + resolved.getKey());
}
// Move that guy from pending to ready...
_readyBlocks.add(resolved);
_pendingBlocks.remove(resolved);
if (_pendingBlocks.size() == 0) {
resolutionComplete();
}
}
protected function resolutionComplete () :void
{
// First, we add in our new blocks...
for each (var newBlock :SceneBlock in _readyBlocks.toArray()) {
newBlock.render();
_blocks.put(newBlock.getKey(), newBlock);
}
_readyBlocks = Sets.newSetOf(SceneBlock);
// Force to end of list so it's on top...
_isoView.removeScene(_objScene);
_isoView.addScene(_objScene);
_objScene.render();
DelayUtil.delayFrame(function() :void {
// Then we let the scene finally move if it's trying to...
if (_pendingMoveBy != null) {
_isoView.centerOnPt(new Pt(_pendingMoveBy.x + _isoView.currentX,
_pendingMoveBy.y + _isoView.currentY), false);
_pendingMoveBy = null;
}
// Now, take out any old blocks no longer in our valid blocks.
var blocks :Set = getBaseBlocks();
for each (var baseKey :int in _blocks.keys()) {
if (!blocks.contains(baseKey)) {
_blocks.remove(baseKey).release();
}
}
});
}
protected function refreshScene () :void
{
// Clear it out...
_isoView.removeAllScenes();
_objScene = new IsoScene();
_objScene.layoutRenderer = new ClassFactory(PrioritizedSceneLayoutRenderer);
refreshBaseBlockScenes();
}
/**
* Derived classes can override this method and provide a colorizer that will be used to
* colorize the supplied scene object when rendering.
*/
public function getColorizer (oinfo :ObjectInfo) :Colorizer
{
return null;
}
protected var _model :MisoSceneModel;
protected var _isoView :IsoView;
protected var _ctx :MisoContext;
protected var _metrics :MisoSceneMetrics;
/** What we display while we're loading up our tilesets. */
protected var _loading :DisplayObject;
/** If we should do something when we hear about progress updates, this is it. */
protected var _loadingProgressFunc :Function;
protected var _objScene :IsoScene;
protected var _blocks :Map = Maps.newMapOf(int);
protected var _pendingMoveBy :Point;
protected var _pendingBlocks :Set = Sets.newSetOf(SceneBlock);
protected var _readyBlocks :Set = Sets.newSetOf(SceneBlock);
protected var _masks :Map = Maps.newMapOf(int);
protected var _fringes :Map = new WeakValueMap(Maps.newMapOf(FringeTile));
protected const DEF_WIDTH :int = 985;
protected const DEF_HEIGHT :int = 560;
protected const BOTTOM_BUFFER :int = 250;
}
}
|
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2010 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.miso.client {
import flash.utils.getTimer;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.events.MouseEvent;
import mx.core.ClassFactory;
import as3isolib.display.primitive.IsoBox;
import as3isolib.geom.Pt;
import as3isolib.geom.IsoMath;
import as3isolib.display.scene.IsoScene;
import as3isolib.display.IsoView;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.util.DelayUtil;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.MathUtil;
import com.threerings.util.Set;
import com.threerings.util.Sets;
import com.threerings.util.StringUtil;
import com.threerings.util.maps.WeakValueMap;
import com.threerings.media.tile.BaseTile;
import com.threerings.media.tile.Colorizer;
import com.threerings.media.tile.NoSuchTileSetError;
import com.threerings.media.tile.TileSet;
import com.threerings.media.tile.TileUtil;
import com.threerings.miso.client.MisoMetricsTransformation;
import com.threerings.miso.client.PrioritizedSceneLayoutRenderer;
import com.threerings.miso.data.MisoSceneModel;
import com.threerings.miso.data.ObjectInfo;
import com.threerings.miso.tile.FringeTile;
import com.threerings.miso.util.MisoContext;
import com.threerings.miso.util.ObjectSet;
import com.threerings.miso.util.MisoSceneMetrics;
public class MisoScenePanel extends Sprite
implements PlaceView
{
private var log :Log = Log.getLog(MisoScenePanel);
public function MisoScenePanel (ctx :MisoContext, metrics :MisoSceneMetrics)
{
_ctx = ctx;
// Excitingly, we get to override this globally for as3isolib...
IsoMath.transformationObject = new MisoMetricsTransformation(metrics,
metrics.tilehei * 3 / 4);
_metrics = metrics;
_isoView = new IsoView();
_isoView.setSize(DEF_WIDTH, DEF_HEIGHT);
_isoView.addEventListener(MouseEvent.CLICK, onClick);
addChild(_loading = createLoadingPanel());
}
/**
* Creates whatever we want to show while we're waiting to load our exciting scene tile data.
*/
protected function createLoadingPanel () :DisplayObject
{
// By default we just stick up a basic label for this...
var loadingText :TextField = new TextField();
loadingText.textColor = 0xFFFFFF;
var loadingFmt :TextFormat = new TextFormat();
loadingFmt.size = 24;
loadingText.defaultTextFormat = loadingFmt;
loadingText.autoSize = TextFieldAutoSize.LEFT;
_loadingProgressFunc = function (progress :Number) :void {
loadingText.text = "Loading... " + int(progress*100) + "%";
};
_loadingProgressFunc(0.0);
return loadingText;
}
protected function loadingProgress (progress :Number) :void
{
if (_loadingProgressFunc != null) {
_loadingProgressFunc(progress);
}
}
public function onClick (event :MouseEvent) :void
{
var viewPt :Point = _isoView.globalToLocal(new Point(event.stageX, event.stageY));
moveBy(new Point(viewPt.x - _isoView.width / 2, viewPt.y - _isoView.height / 2));
}
public function moveBy (pt :Point) :void
{
if (_pendingMoveBy != null) {
log.info("Already performing a move...");
return;
}
_pendingMoveBy = pt;
refreshBaseBlockScenes();
}
public function setSceneModel (model :MisoSceneModel) :void
{
_model = model;
_ctx.getTileManager().ensureLoaded(_model.getAllTilesets(), function() :void {
DelayUtil.delayFrame(function() :void {
refreshScene();
removeChild(_loading);
addChild(_isoView);
});
}, loadingProgress);
}
public function willEnterPlace (plobj :PlaceObject) :void
{
}
public function didLeavePlace (plobj :PlaceObject) :void
{
}
/** Computes the fringe tile for the specified coordinate. */
public function computeFringeTile (tx :int, ty :int) :BaseTile
{
return _ctx.getTileManager().getFringer().getFringeTile(_model, tx, ty, _fringes,
_masks);
}
protected function getBaseBlocks () :Set
{
var blocks :Set = Sets.newSetOf(int);
var size :Point = _isoView.size;
var xMove :int = (_pendingMoveBy == null ? 0 : _pendingMoveBy.x);
var yMove :int = (_pendingMoveBy == null ? 0 : _pendingMoveBy.y);
var minX :int = xMove;
var maxX :int = size.x + xMove;
var minY :int = yMove;
var maxY :int = BOTTOM_BUFFER + size.y + yMove;
var topLeft :Point = _isoView.localToIso(new Point(minX, minY));
var topRight :Point = _isoView.localToIso(new Point(maxX, minY));
var btmLeft :Point = _isoView.localToIso(new Point(minX, maxY));
var btmRight :Point = _isoView.localToIso(new Point(maxX, maxY));
for (var yy :int = topRight.y - 1; yy <= btmLeft.y + 1; yy++) {
for (var xx :int = topLeft.x - 1; xx <= btmRight.x + 1; xx++) {
// Toss out any that aren't actually in our view.
var blkTop :Point = _isoView.isoToLocal(new Pt(xx, yy, 0));
var blkRight :Point =
_isoView.isoToLocal(new Pt(xx + SceneBlock.BLOCK_SIZE, yy, 0));
var blkLeft :Point =
_isoView.isoToLocal(new Pt(xx, yy + SceneBlock.BLOCK_SIZE, 0));
var blkBtm :Point =
_isoView.isoToLocal(new Pt(xx + SceneBlock.BLOCK_SIZE,
yy + SceneBlock.BLOCK_SIZE, 0));
if (blkTop.y < maxY &&
blkBtm.y > minY &&
blkLeft.x < maxX &&
blkRight.x > minX) {
blocks.add(SceneBlock.getBlockKey(xx, yy));
}
}
}
return blocks;
}
protected function refreshBaseBlockScenes () :void
{
_resStartTime = getTimer();
var blocks :Set = getBaseBlocks();
// Keep this to use in our function...
var thisRef :MisoScenePanel = this;
// Postpone calling complete til they're all queued up.
_skipComplete = true;
blocks.forEach(function(blockKey :int) :void {
if (!_blocks.containsKey(blockKey)) {
var sceneBlock :SceneBlock =
new SceneBlock(blockKey, _objScene, _isoView, _metrics);
_pendingBlocks.add(sceneBlock);
sceneBlock.resolve(_ctx, _model, thisRef, blockResolved);
}
});
_skipComplete = false;
if (_pendingBlocks.size() == 0) {
resolutionComplete();
}
}
protected function blockResolved (resolved :SceneBlock) :void
{
if (!_pendingBlocks.contains(resolved)) {
log.info("Trying to resolve non-pending block???: " + resolved.getKey());
}
// Move that guy from pending to ready...
_readyBlocks.add(resolved);
_pendingBlocks.remove(resolved);
if (_pendingBlocks.size() == 0 && !_skipComplete) {
resolutionComplete();
}
}
protected function resolutionComplete () :void
{
// First, we add in our new blocks...
for each (var newBlock :SceneBlock in _readyBlocks.toArray()) {
newBlock.render();
_blocks.put(newBlock.getKey(), newBlock);
}
_readyBlocks = Sets.newSetOf(SceneBlock);
// Force to end of list so it's on top...
_isoView.removeScene(_objScene);
_isoView.addScene(_objScene);
_objScene.render();
// Then we let the scene finally move if it's trying to...
if (_pendingMoveBy != null) {
_isoView.centerOnPt(new Pt(_pendingMoveBy.x + _isoView.currentX,
_pendingMoveBy.y + _isoView.currentY), false);
_pendingMoveBy = null;
}
// Now, take out any old blocks no longer in our valid blocks.
var blocks :Set = getBaseBlocks();
for each (var baseKey :int in _blocks.keys()) {
if (!blocks.contains(baseKey)) {
_blocks.remove(baseKey).release();
}
}
trace("Scene Block Resolution took: " + (getTimer() - _resStartTime) + "ms");
}
protected function refreshScene () :void
{
// Clear it out...
_isoView.removeAllScenes();
_objScene = new IsoScene();
_objScene.layoutRenderer = new ClassFactory(PrioritizedSceneLayoutRenderer);
refreshBaseBlockScenes();
}
/**
* Derived classes can override this method and provide a colorizer that will be used to
* colorize the supplied scene object when rendering.
*/
public function getColorizer (oinfo :ObjectInfo) :Colorizer
{
return null;
}
protected var _model :MisoSceneModel;
protected var _isoView :IsoView;
protected var _ctx :MisoContext;
protected var _metrics :MisoSceneMetrics;
/** What we display while we're loading up our tilesets. */
protected var _loading :DisplayObject;
/** If we should do something when we hear about progress updates, this is it. */
protected var _loadingProgressFunc :Function;
protected var _objScene :IsoScene;
protected var _blocks :Map = Maps.newMapOf(int);
protected var _pendingMoveBy :Point;
protected var _pendingBlocks :Set = Sets.newSetOf(SceneBlock);
protected var _readyBlocks :Set = Sets.newSetOf(SceneBlock);
protected var _masks :Map = Maps.newMapOf(int);
protected var _fringes :Map = new WeakValueMap(Maps.newMapOf(FringeTile));
protected var _resStartTime :int;
protected var _skipComplete :Boolean
protected const DEF_WIDTH :int = 985;
protected const DEF_HEIGHT :int = 560;
protected const BOTTOM_BUFFER :int = 250;
}
}
|
Fix a bug where we were finishing resolution of the entire scene multiple times if some blocks were basically already resolved.
|
Fix a bug where we were finishing resolution of the entire scene multiple times if some blocks were basically already resolved.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@957 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
b88ed87233021d175cc0779c232c564fe11e4ff6
|
mustella/as3/src/mustella/SendResultsToRunner.as
|
mustella/as3/src/mustella/SendResultsToRunner.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.net.*;
import flash.utils.*;
import flash.events.Event;
[Mixin]
/**
* A "marker" class that causes test scripts to write out
* bitmaps to the urls instead of reading and comparing
* so that baselines/reference-points can be created for
* future comparing.
*/
public class SendResultsToRunner
{
/**
* Mixin callback that gets everything ready to go.
* The UnitTester waits for an event before starting
*/
public static function init(root:DisplayObject):void
{
TestOutput.getInstance().addEventListener ("result", urlSender);
}
public static var midURL:String = "";
public static var regExp5:RegExp = /%3D/g;
public static var u:URLLoader;
/**
* the way out for the result data
*/
public static function urlSender (event:Event):void
{
var s:String = (event as MustellaLogEvent).msg;
var baseURL:String = "http://localhost:" + UnitTester.runnerPort;
/// trace it anyway
trace (s);
/// Notice what we've got. Send along to Runner if relevant
var loc:uint;
var final:String = "";
var skip:Boolean = false;
var noSend:Boolean = false;
if ( (loc = s.indexOf ("RESULT: ")) != -1) {
s = s.substr (loc + 8);
midURL = "/testCaseResult";
} else if ( (loc = s.indexOf ("ScriptComplete:")) != -1) {
midURL = "/ScriptComplete";
final = "?" + UnitTester.excludedCount;
skip = true;
} else if ( (loc = s.indexOf ("LengthOfTestcases:")) != -1) {
midURL = "/testCaseLength?";
final = s.substring (loc+ "LengthOfTestcases:".length+1);
skip = true;
} else if ( (loc = s.indexOf ("TestCase Start:")) != -1) {
/// not relevant
s = s.substr (loc + 15);
s = s.replace (" ", "");
midURL = "/testCaseStart?" + s ;
skip = true;
} else {
noSend = true;
}
if (!skip) {
/// this should be something like |, because it is confusing this way
/// putting it on, taking it off
s=s.replace (" msg=", "|msg=");
s=s.replace (" result=", "|result=");
s=s.replace (" phase=", "|phase=");
s=s.replace (" id=", "|id=");
s=s.replace (" elapsed=", "|elapsed=");
s=s.replace (" started=", "|started=");
s=s.replace (" extraInfo=", "|extraInfo=");
var hdrs:Array = s.split ("|");
var i:uint;
// rebuild url encoded
for (i=0;i<hdrs.length;i++) {
if (final =="")
final="?" + escape(hdrs[i]);
else
final+="&" + escape(hdrs[i]);
}
final = final.replace (regExp5, "=");
}
/**
* Probably we don't need to use URLLoader, since we don't care
* about the response, but for now, for debugging, using it
*/
if (!noSend) {
trace ("sending: " + baseURL + midURL + final + " at: " + new Date());
// var u:String= baseURL + midURL + final;
if (u == null)
{
u = new URLLoader();
u.addEventListener("complete", completeHandler);
u.addEventListener("complete", httpEvents);
u.addEventListener("ioError", httpEvents);
u.addEventListener("open", httpEvents);
u.addEventListener("progress", httpEvents);
u.addEventListener("httpStatus", httpEvents);
u.addEventListener("securityError", httpEvents);
}
UnitTester.pendingOutput++;
u.load (new URLRequest (baseURL + midURL + final));
/*
var sock:Socket = new Socket ("localhost", UnitTester.runnerPort);
sock.writeUTFBytes(u);
sock.flush();
sock.flush();
*/
}
}
public static function completeHandler (e:Event):void {
UnitTester.pendingOutput--;
}
public static function httpEvents (e:Event):void {
trace (e);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.net.*;
import flash.utils.*;
import flash.events.Event;
[Mixin]
/**
* A "marker" class that causes test scripts to write out
* bitmaps to the urls instead of reading and comparing
* so that baselines/reference-points can be created for
* future comparing.
*/
public class SendResultsToRunner
{
/**
* Mixin callback that gets everything ready to go.
* The UnitTester waits for an event before starting
*/
public static function init(root:DisplayObject):void
{
TestOutput.getInstance().addEventListener ("result", urlSender);
}
public static var midURL:String = "";
public static var regExp5:RegExp = /%3D/g;
/**
* the way out for the result data
*/
public static function urlSender (event:Event):void
{
var s:String = (event as MustellaLogEvent).msg;
var baseURL:String = "http://localhost:" + UnitTester.runnerPort;
/// trace it anyway
trace (s);
/// Notice what we've got. Send along to Runner if relevant
var loc:uint;
var final:String = "";
var skip:Boolean = false;
var noSend:Boolean = false;
if ( (loc = s.indexOf ("RESULT: ")) != -1) {
s = s.substr (loc + 8);
midURL = "/testCaseResult";
} else if ( (loc = s.indexOf ("ScriptComplete:")) != -1) {
midURL = "/ScriptComplete";
final = "?" + UnitTester.excludedCount;
skip = true;
} else if ( (loc = s.indexOf ("LengthOfTestcases:")) != -1) {
midURL = "/testCaseLength?";
final = s.substring (loc+ "LengthOfTestcases:".length+1);
skip = true;
} else if ( (loc = s.indexOf ("TestCase Start:")) != -1) {
/// not relevant
s = s.substr (loc + 15);
s = s.replace (" ", "");
midURL = "/testCaseStart?" + s ;
skip = true;
} else {
noSend = true;
}
if (!skip) {
/// this should be something like |, because it is confusing this way
/// putting it on, taking it off
s=s.replace (" msg=", "|msg=");
s=s.replace (" result=", "|result=");
s=s.replace (" phase=", "|phase=");
s=s.replace (" id=", "|id=");
s=s.replace (" elapsed=", "|elapsed=");
s=s.replace (" started=", "|started=");
s=s.replace (" extraInfo=", "|extraInfo=");
var hdrs:Array = s.split ("|");
var i:uint;
// rebuild url encoded
for (i=0;i<hdrs.length;i++) {
if (final =="")
final="?" + escape(hdrs[i]);
else
final+="&" + escape(hdrs[i]);
}
final = final.replace (regExp5, "=");
}
/**
* Probably we don't need to use URLLoader, since we don't care
* about the response, but for now, for debugging, using it
*/
if (!noSend) {
trace ("sending: " + baseURL + midURL + final + " at: " + new Date());
// var u:String= baseURL + midURL + final;
var u:URLLoader = new URLLoader (new URLRequest (baseURL + midURL + final));
/*
var sock:Socket = new Socket ("localhost", UnitTester.runnerPort);
sock.writeUTFBytes(u);
sock.flush();
sock.flush();
*/
u.addEventListener("complete", completeHandler);
u.addEventListener("complete", httpEvents);
u.addEventListener("ioError", httpEvents);
u.addEventListener("open", httpEvents);
u.addEventListener("progress", httpEvents);
u.addEventListener("httpStatus", httpEvents);
u.addEventListener("securityError", httpEvents);
u.load (new URLRequest (baseURL + midURL + final));
UnitTester.pendingOutput++;
dict[u] = baseURL + midURL + final;
}
}
public static var dict:Dictionary = new Dictionary();
public static function completeHandler (e:Event):void {
UnitTester.pendingOutput--;
//trace("received complete for", dict[e.target]);
delete dict[e.target];
}
public static function httpEvents (e:Event):void {
trace (e);
}
}
}
|
Revert last attempt
|
Revert last attempt
git-svn-id: 7d913817b0a978d84de757191e4bce372605a781@1395325 13f79535-47bb-0310-9956-ffa450edef68
|
ActionScript
|
apache-2.0
|
shyamalschandra/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk
|
22db576c50a98bb9aa176220d5fca4e31136b67b
|
src/aerys/minko/scene/node/texture/BitmapTexture.as
|
src/aerys/minko/scene/node/texture/BitmapTexture.as
|
package aerys.minko.scene.node.texture
{
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.geom.Matrix;
/**
* The BitmapTexture class enables the use of BitmapData objects as
* textures.
*
* @author Jean-Marc Le Roux
*
*/
public class BitmapTexture extends Texture
{
private static const TMP_MATRIX : Matrix = new Matrix();
private var _data : BitmapData = null;
private var _mipmapping : Boolean = false;
protected function get bitmapData() : BitmapData
{
return _data;
}
public function updateFromBitmapData(value : BitmapData,
smooth : Boolean = true,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = value.width;
var bitmapHeight : uint = value.height;
var w : int;
var h : int;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (!_data || _data.width != w || _data.height != h)
{
if (_data)
{
_data.dispose();
_data = null;
}
_data = new BitmapData(w, h, value.transparent, 0);
}
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_data.draw(value, TMP_MATRIX, null, null, null, smooth);
}
else
{
_data.draw(value, null, null, null, null, smooth);
}
resource.setContentFromBitmapData(_data, _mipmapping);
_data = null;
}
public function BitmapTexture(bitmapData : BitmapData = null,
mipmapping : Boolean = true,
styleProperty : int = -1)
{
super(null, styleProperty);
_mipmapping = mipmapping;
if (bitmapData)
updateFromBitmapData(bitmapData);
}
public static function fromDisplayObject(source : DisplayObject,
size : int = 0,
smooth : Boolean = false) : BitmapTexture
{
var bmp : BitmapData = new BitmapData(size || source.width,
size || source.height,
true,
0);
if (size)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(source.width / size, source.height / size);
}
bmp.draw(source, TMP_MATRIX, null, null, null, smooth);
return new BitmapTexture(bmp);
}
}
}
|
package aerys.minko.scene.node.texture
{
import aerys.minko.ns.minko;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.geom.Matrix;
/**
* The BitmapTexture class enables the use of BitmapData objects as
* textures.
*
* @author Jean-Marc Le Roux
*
*/
use namespace minko;
public class BitmapTexture extends Texture
{
private static const TMP_MATRIX : Matrix = new Matrix();
minko var _data : BitmapData = null;
private var _mipmapping : Boolean = false;
protected function get bitmapData() : BitmapData
{
return _data;
}
public function get mipmapping():Boolean
{
return _mipmapping;
}
public function updateFromBitmapData(value : BitmapData,
smooth : Boolean = true,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = value.width;
var bitmapHeight : uint = value.height;
var w : int;
var h : int;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (!_data || _data.width != w || _data.height != h)
{
if (_data)
{
_data.dispose();
_data = null;
}
_data = new BitmapData(w, h, value.transparent, 0);
}
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_data.draw(value, TMP_MATRIX, null, null, null, smooth);
}
else
{
_data.draw(value, null, null, null, null, smooth);
}
resource.setContentFromBitmapData(_data, _mipmapping);
_data = null;
}
public function BitmapTexture(bitmapData : BitmapData = null,
mipmapping : Boolean = true,
styleProperty : int = -1)
{
super(null, styleProperty);
_mipmapping = mipmapping;
if (bitmapData)
updateFromBitmapData(bitmapData);
}
public static function fromDisplayObject(source : DisplayObject,
size : int = 0,
smooth : Boolean = false) : BitmapTexture
{
var bmp : BitmapData = new BitmapData(size || source.width,
size || source.height,
true,
0);
if (size)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(source.width / size, source.height / size);
}
bmp.draw(source, TMP_MATRIX, null, null, null, smooth);
return new BitmapTexture(bmp);
}
}
}
|
Add namespace minko around parameter data
|
Add namespace minko around parameter data
M To have access to the bitmapData value (use for BitmapTextureEditorNode)
|
ActionScript
|
mit
|
aerys/minko-as3
|
1238d321d132704679391805a1118e92ac0fa6c2
|
src/aerys/minko/render/shader/compiler/Serializer.as
|
src/aerys/minko/render/shader/compiler/Serializer.as
|
package aerys.minko.render.shader.compiler
{
import aerys.minko.ns.minko_math;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import flash.geom.Point;
import flash.geom.Vector3D;
import flash.utils.getQualifiedClassName;
/**
* The Serializer class provides a set of static methods to serialize
* CPU values into Vector.<Number> than can be used as shader constants.
*
* @author Jean-Marc Le Roux
*
*/
public class Serializer
{
public function serializeKnownLength(data : Object,
target : Vector.<Number>,
offset : uint,
size : uint) : void
{
if (data is Number)
{
var intData : Number = Number(data);
if (size == 1)
{
target[offset] = intData;
}
else if (size == 2)
{
target[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff);
target[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff);
}
else if (size == 3)
{
target[offset] = ((intData & 0xFF0000) >>> 16) / 255.;
target[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.;
target[int(offset + 2)] = (intData & 0x0000FF) / 255.;
}
else if (size == 4)
{
target[offset] = ((intData & 0xFF000000) >>> 24) / 255.;
target[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.;
target[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.;
target[int(offset + 3)] = ((intData & 0x000000FF)) / 255.;
}
}
else if (data is Vector4)
{
var vectorData : Vector3D = Vector4(data).minko_math::_vector;
target[offset] = vectorData.x;
size >= 2 && (target[int(offset + 1)] = vectorData.y);
size >= 3 && (target[int(offset + 2)] = vectorData.z);
size >= 4 && (target[int(offset + 3)] = vectorData.w);
}
else if (data is Matrix4x4)
{
Matrix4x4(data).getRawData(target, offset, true);
}
else if (data is Vector.<Number>)
{
var vectorNumberData : Vector.<Number> = Vector.<Number>(data);
var vectorNumberDatalength : uint = vectorNumberData.length;
for (var k : int = 0; k < size && k < vectorNumberDatalength; ++k)
target[offset + k] = vectorNumberData[k];
}
else if (data is Vector.<Vector4>)
{
var vectorVectorData : Vector.<Vector4> = Vector.<Vector4>(data);
var vectorVectorDataLength : uint = vectorVectorData.length;
for (var j : uint = 0; j < vectorVectorDataLength; ++j)
{
vectorData = vectorVectorData[j].minko_math::_vector;
target[offset + 4 * j] = vectorData.x;
target[int(offset + 4 * j + 1)] = vectorData.y;
target[int(offset + 4 * j + 2)] = vectorData.z;
target[int(offset + 4 * j + 3)] = vectorData.w;
}
}
else if (data is Vector.<Matrix4x4>)
{
var matrixVectorData : Vector.<Matrix4x4> = Vector.<Matrix4x4>(data);
var matrixVectorDataLength : uint = matrixVectorData.length;
for (var i : uint = 0; i < matrixVectorDataLength; ++i)
matrixVectorData[i].getRawData(target, offset + i * 16, true);
}
else if (data == null)
{
throw new Error('You cannot serialize a null value.');
}
else
{
throw new Error('Unsupported type:' + getQualifiedClassName(data);
}
}
public function serializeUnknownLength(data : Object,
target : Vector.<Number>,
offset : uint) : void
{
if (data is Number)
{
target[offset] = Number(data);
}
else if (data is Point)
{
var pointData : Point = Point(data);
target[offset] = pointData.x;
target[int(offset + 1)] = pointData.y;
}
else if (data is Vector4)
{
var vectorData : Vector3D = Vector4(data).minko_math::_vector;
target[offset] = vectorData.x;
target[int(offset + 1)] = vectorData.y;
target[int(offset + 2)] = vectorData.z;
target[int(offset + 3)] = vectorData.w;
}
else if (data is Matrix4x4)
{
Matrix4x4(data).getRawData(target, offset, true);
}
else if (data is Array || data is Vector.<Number> || data is Vector.<Vector4> || data is Vector.<Matrix4x4>)
{
for each (var datum : Object in data)
{
serializeUnknownLength(datum, target, offset);
offset = target.length;
}
}
else if (data == null)
{
throw new Error('You cannot serialize a null value.');
}
else
{
throw new Error('Unsupported type:' + getQualifiedClassName(data));
}
}
}
}
|
package aerys.minko.render.shader.compiler
{
import aerys.minko.ns.minko_math;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
import flash.geom.Point;
import flash.geom.Vector3D;
import flash.utils.getQualifiedClassName;
/**
* The Serializer class provides a set of static methods to serialize
* CPU values into Vector.<Number> than can be used as shader constants.
*
* @author Jean-Marc Le Roux
*
*/
public class Serializer
{
public function serializeKnownLength(data : Object,
target : Vector.<Number>,
offset : uint,
size : uint) : void
{
if (data is Number)
{
var intData : Number = Number(data);
if (size == 1)
{
target[offset] = intData;
}
else if (size == 2)
{
target[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff);
target[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff);
}
else if (size == 3)
{
target[offset] = ((intData & 0xFF0000) >>> 16) / 255.;
target[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.;
target[int(offset + 2)] = (intData & 0x0000FF) / 255.;
}
else if (size == 4)
{
target[offset] = ((intData & 0xFF000000) >>> 24) / 255.;
target[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.;
target[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.;
target[int(offset + 3)] = ((intData & 0x000000FF)) / 255.;
}
}
else if (data is Vector4)
{
var vectorData : Vector3D = Vector4(data).minko_math::_vector;
target[offset] = vectorData.x;
size >= 2 && (target[int(offset + 1)] = vectorData.y);
size >= 3 && (target[int(offset + 2)] = vectorData.z);
size >= 4 && (target[int(offset + 3)] = vectorData.w);
}
else if (data is Matrix4x4)
{
Matrix4x4(data).getRawData(target, offset, true);
}
else if (data is Vector.<Number>)
{
var vectorNumberData : Vector.<Number> = Vector.<Number>(data);
var vectorNumberDatalength : uint = vectorNumberData.length;
for (var k : int = 0; k < size && k < vectorNumberDatalength; ++k)
target[offset + k] = vectorNumberData[k];
}
else if (data is Vector.<Vector4>)
{
var vectorVectorData : Vector.<Vector4> = Vector.<Vector4>(data);
var vectorVectorDataLength : uint = vectorVectorData.length;
for (var j : uint = 0; j < vectorVectorDataLength; ++j)
{
vectorData = vectorVectorData[j].minko_math::_vector;
target[offset + 4 * j] = vectorData.x;
target[int(offset + 4 * j + 1)] = vectorData.y;
target[int(offset + 4 * j + 2)] = vectorData.z;
target[int(offset + 4 * j + 3)] = vectorData.w;
}
}
else if (data is Vector.<Matrix4x4>)
{
var matrixVectorData : Vector.<Matrix4x4> = Vector.<Matrix4x4>(data);
var matrixVectorDataLength : uint = matrixVectorData.length;
for (var i : uint = 0; i < matrixVectorDataLength; ++i)
matrixVectorData[i].getRawData(target, offset + i * 16, true);
}
else if (data == null)
{
throw new Error('You cannot serialize a null value.');
}
else
{
throw new Error('Unsupported type:' + getQualifiedClassName(data));
}
}
public function serializeUnknownLength(data : Object,
target : Vector.<Number>,
offset : uint) : void
{
if (data is Number)
{
target[offset] = Number(data);
}
else if (data is Point)
{
var pointData : Point = Point(data);
target[offset] = pointData.x;
target[int(offset + 1)] = pointData.y;
}
else if (data is Vector4)
{
var vectorData : Vector3D = Vector4(data).minko_math::_vector;
target[offset] = vectorData.x;
target[int(offset + 1)] = vectorData.y;
target[int(offset + 2)] = vectorData.z;
target[int(offset + 3)] = vectorData.w;
}
else if (data is Matrix4x4)
{
Matrix4x4(data).getRawData(target, offset, true);
}
else if (data is Array || data is Vector.<Number> || data is Vector.<Vector4> || data is Vector.<Matrix4x4>)
{
for each (var datum : Object in data)
{
serializeUnknownLength(datum, target, offset);
offset = target.length;
}
}
else if (data == null)
{
throw new Error('You cannot serialize a null value.');
}
else
{
throw new Error('Unsupported type:' + getQualifiedClassName(data));
}
}
}
}
|
fix missing )
|
fix missing )
|
ActionScript
|
mit
|
aerys/minko-as3
|
de746b07f80aaa23572e45d2c240fec7afa0eef5
|
src/aerys/minko/render/material/phong/PhongEffect.as
|
src/aerys/minko/render/material/phong/PhongEffect.as
|
package aerys.minko.render.material.phong
{
import aerys.minko.render.DataBindingsProxy;
import aerys.minko.render.Effect;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.resource.texture.CubeTextureResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.render.shader.Shader;
import aerys.minko.scene.data.LightDataProvider;
import aerys.minko.scene.node.light.AmbientLight;
import aerys.minko.scene.node.light.DirectionalLight;
import aerys.minko.scene.node.light.PointLight;
import aerys.minko.type.enum.ShadowMappingQuality;
import aerys.minko.type.enum.ShadowMappingType;
public class PhongEffect extends Effect
{
private var _singlePassShader : Shader;
private var _baseShader : Shader;
public function PhongEffect(singlePassShader : Shader = null,
baseShader : Shader = null)
{
super();
_singlePassShader = singlePassShader || new PhongSinglePassShader(null, 0);
_baseShader = baseShader || new PhongBaseShader(null, .5);
}
override protected function initializePasses(sceneBindings : DataBindingsProxy,
meshBindings : DataBindingsProxy) : Vector.<Shader>
{
var passes : Vector.<Shader> = super.initializePasses(sceneBindings, meshBindings);
for (var lightId : uint = 0;
lightPropertyExists(sceneBindings, lightId, 'enabled');
++lightId)
{
if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType'))
{
var lightType : uint = getLightProperty(sceneBindings, lightId, 'type');
var shadowMappingType : uint = getLightProperty(
sceneBindings, lightId, 'shadowCastingType'
);
switch (shadowMappingType)
{
case ShadowMappingType.PCF:
if (lightType == PointLight.LIGHT_TYPE)
pushCubeShadowMappingPass(sceneBindings, lightId, passes);
else
pushPCFShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.DUAL_PARABOLOID:
pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.VARIANCE:
pushVarianceShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.EXPONENTIAL:
pushExponentialShadowMappingPass(sceneBindings, lightId, passes);
break ;
}
}
}
passes.push(new PhongSinglePassShader(null, 0));
return passes;
}
override protected function initializeFallbackPasses(sceneBindings : DataBindingsProxy,
meshBindings : DataBindingsProxy) : Vector.<Shader>
{
var passes : Vector.<Shader> = super.initializeFallbackPasses(sceneBindings, meshBindings);
var discardDirectional : Boolean = true;
for (var lightId : uint = 0;
lightPropertyExists(sceneBindings, lightId, 'enabled');
++lightId)
{
var lightType : uint = getLightProperty(sceneBindings, lightId, 'type');
if (lightType != AmbientLight.LIGHT_TYPE
&& getLightProperty(sceneBindings, lightId, 'enabled'))
{
if (lightType == DirectionalLight.LIGHT_TYPE && discardDirectional)
discardDirectional = false;
else
passes.push(new PhongAdditionalShader(null, 0, lightId));
}
if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType'))
{
var shadowMappingType : uint = getLightProperty(
sceneBindings, lightId, 'shadowCastingType'
);
switch (shadowMappingType)
{
case ShadowMappingType.PCF:
if (lightType == PointLight.LIGHT_TYPE)
pushCubeShadowMappingPass(sceneBindings, lightId, passes);
else
pushPCFShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.DUAL_PARABOLOID:
pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.VARIANCE:
pushVarianceShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.EXPONENTIAL:
pushExponentialShadowMappingPass(sceneBindings, lightId, passes);
break ;
}
}
}
passes.push(new PhongBaseShader(null, .5));
return passes;
}
private function pushPCFShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var textureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var renderTarget : RenderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new PCFShadowMapShader(lightId, lightId + 1, renderTarget));
}
private function pushDualParaboloidShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var frontTextureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMapFront'
);
var backTextureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMapBack'
);
var size : uint = frontTextureResource.width;
var frontRenderTarget : RenderTarget = new RenderTarget(
size, size, frontTextureResource, 0, 0xffffffff
);
var backRenderTarget : RenderTarget = new RenderTarget(
size, size, backTextureResource, 0, 0xffffffff
);
passes.push(
new ParaboloidShadowMapShader(lightId, true, lightId + 0.5, frontRenderTarget),
new ParaboloidShadowMapShader(lightId, false, lightId + 1, backRenderTarget)
);
}
private function pushCubeShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new PCFShadowMapShader(
lightId,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff),
i
));
}
private function pushVarianceShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var lightType : uint = getLightProperty(
sceneBindings, lightId, 'type'
);
if (lightType != PointLight.LIGHT_TYPE)
{
var textureResource : ITextureResource = null;
var renderTarget : RenderTarget = null;
if (hasShadowBlurPass(sceneBindings, lightId))
textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap');
else
textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap');
renderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new VarianceShadowMapShader(lightId, 4, lightId + 1, renderTarget));
}
else
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new VarianceShadowMapShader(
lightId,
i,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff)
));
}
}
private function pushExponentialShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>):void
{
var lightType : uint = getLightProperty(
sceneBindings, lightId, 'type'
);
if (lightType != PointLight.LIGHT_TYPE)
{
var textureResource : ITextureResource = null;
var renderTarget : RenderTarget = null;
if (hasShadowBlurPass(sceneBindings, lightId))
textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap');
else
textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap');
renderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new ExponentialShadowMapShader(lightId, 4, lightId + 1, renderTarget));
}
else
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new ExponentialShadowMapShader(
lightId,
i,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff)
));
}
}
private function hasShadowBlurPass(sceneBindings : DataBindingsProxy,
lightId : uint) : Boolean
{
var quality : uint = getLightProperty(sceneBindings, lightId, 'shadowQuality');
return quality > ShadowMappingQuality.HARD;
}
private function lightPropertyExists(sceneBindings : DataBindingsProxy,
lightId : uint,
propertyName : String) : Boolean
{
return sceneBindings.propertyExists(
LightDataProvider.getLightPropertyName(propertyName, lightId)
);
}
private function getLightProperty(sceneBindings : DataBindingsProxy,
lightId : uint,
propertyName : String) : *
{
return sceneBindings.getProperty(
LightDataProvider.getLightPropertyName(propertyName, lightId)
);
}
}
}
|
package aerys.minko.render.material.phong
{
import aerys.minko.render.DataBindingsProxy;
import aerys.minko.render.Effect;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.resource.texture.CubeTextureResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.render.shader.Shader;
import aerys.minko.scene.data.LightDataProvider;
import aerys.minko.scene.node.light.AmbientLight;
import aerys.minko.scene.node.light.DirectionalLight;
import aerys.minko.scene.node.light.PointLight;
import aerys.minko.type.enum.ShadowMappingQuality;
import aerys.minko.type.enum.ShadowMappingType;
public class PhongEffect extends Effect
{
private var _singlePassShader : Shader;
private var _baseShader : Shader;
public function PhongEffect(singlePassShader : Shader = null,
baseShader : Shader = null)
{
super();
_singlePassShader = singlePassShader || new PhongSinglePassShader(null, 0);
_baseShader = baseShader || new PhongBaseShader(null, .5);
}
override protected function initializePasses(sceneBindings : DataBindingsProxy,
meshBindings : DataBindingsProxy) : Vector.<Shader>
{
var passes : Vector.<Shader> = super.initializePasses(sceneBindings, meshBindings);
for (var lightId : uint = 0;
lightPropertyExists(sceneBindings, lightId, 'enabled');
++lightId)
{
if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType'))
{
var lightType : uint = getLightProperty(sceneBindings, lightId, 'type');
var shadowMappingType : uint = getLightProperty(
sceneBindings, lightId, 'shadowCastingType'
);
switch (shadowMappingType)
{
case ShadowMappingType.PCF:
if (lightType == PointLight.LIGHT_TYPE)
pushCubeShadowMappingPass(sceneBindings, lightId, passes);
else
pushPCFShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.DUAL_PARABOLOID:
pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.VARIANCE:
pushVarianceShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.EXPONENTIAL:
pushExponentialShadowMappingPass(sceneBindings, lightId, passes);
break ;
}
}
}
passes.push(_singlePassShader);
return passes;
}
override protected function initializeFallbackPasses(sceneBindings : DataBindingsProxy,
meshBindings : DataBindingsProxy) : Vector.<Shader>
{
var passes : Vector.<Shader> = super.initializeFallbackPasses(sceneBindings, meshBindings);
var discardDirectional : Boolean = true;
for (var lightId : uint = 0;
lightPropertyExists(sceneBindings, lightId, 'enabled');
++lightId)
{
var lightType : uint = getLightProperty(sceneBindings, lightId, 'type');
if (lightType != AmbientLight.LIGHT_TYPE
&& getLightProperty(sceneBindings, lightId, 'enabled'))
{
if (lightType == DirectionalLight.LIGHT_TYPE && discardDirectional)
discardDirectional = false;
else
passes.push(new PhongAdditionalShader(null, 0, lightId));
}
if (lightPropertyExists(sceneBindings, lightId, 'shadowCastingType'))
{
var shadowMappingType : uint = getLightProperty(
sceneBindings, lightId, 'shadowCastingType'
);
switch (shadowMappingType)
{
case ShadowMappingType.PCF:
if (lightType == PointLight.LIGHT_TYPE)
pushCubeShadowMappingPass(sceneBindings, lightId, passes);
else
pushPCFShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.DUAL_PARABOLOID:
pushDualParaboloidShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.VARIANCE:
pushVarianceShadowMappingPass(sceneBindings, lightId, passes);
break ;
case ShadowMappingType.EXPONENTIAL:
pushExponentialShadowMappingPass(sceneBindings, lightId, passes);
break ;
}
}
}
passes.push(_baseShader);
return passes;
}
private function pushPCFShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var textureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var renderTarget : RenderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new PCFShadowMapShader(lightId, lightId + 1, renderTarget));
}
private function pushDualParaboloidShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var frontTextureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMapFront'
);
var backTextureResource : TextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMapBack'
);
var size : uint = frontTextureResource.width;
var frontRenderTarget : RenderTarget = new RenderTarget(
size, size, frontTextureResource, 0, 0xffffffff
);
var backRenderTarget : RenderTarget = new RenderTarget(
size, size, backTextureResource, 0, 0xffffffff
);
passes.push(
new ParaboloidShadowMapShader(lightId, true, lightId + 0.5, frontRenderTarget),
new ParaboloidShadowMapShader(lightId, false, lightId + 1, backRenderTarget)
);
}
private function pushCubeShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new PCFShadowMapShader(
lightId,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff),
i
));
}
private function pushVarianceShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>) : void
{
var lightType : uint = getLightProperty(
sceneBindings, lightId, 'type'
);
if (lightType != PointLight.LIGHT_TYPE)
{
var textureResource : ITextureResource = null;
var renderTarget : RenderTarget = null;
if (hasShadowBlurPass(sceneBindings, lightId))
textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap');
else
textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap');
renderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new VarianceShadowMapShader(lightId, 4, lightId + 1, renderTarget));
}
else
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new VarianceShadowMapShader(
lightId,
i,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff)
));
}
}
private function pushExponentialShadowMappingPass(sceneBindings : DataBindingsProxy,
lightId : uint,
passes : Vector.<Shader>):void
{
var lightType : uint = getLightProperty(
sceneBindings, lightId, 'type'
);
if (lightType != PointLight.LIGHT_TYPE)
{
var textureResource : ITextureResource = null;
var renderTarget : RenderTarget = null;
if (hasShadowBlurPass(sceneBindings, lightId))
textureResource = getLightProperty(sceneBindings, lightId, 'rawShadowMap');
else
textureResource = getLightProperty(sceneBindings, lightId, 'shadowMap');
renderTarget = new RenderTarget(
textureResource.width, textureResource.height, textureResource, 0, 0xffffffff
);
passes.push(new ExponentialShadowMapShader(lightId, 4, lightId + 1, renderTarget));
}
else
{
var cubeTexture : CubeTextureResource = getLightProperty(
sceneBindings, lightId, 'shadowMap'
);
var textureSize : uint = cubeTexture.size;
for (var i : uint = 0; i < 6; ++i)
passes.push(new ExponentialShadowMapShader(
lightId,
i,
lightId + .1 * i,
new RenderTarget(textureSize, textureSize, cubeTexture, i, 0xffffffff)
));
}
}
private function hasShadowBlurPass(sceneBindings : DataBindingsProxy,
lightId : uint) : Boolean
{
var quality : uint = getLightProperty(sceneBindings, lightId, 'shadowQuality');
return quality > ShadowMappingQuality.HARD;
}
private function lightPropertyExists(sceneBindings : DataBindingsProxy,
lightId : uint,
propertyName : String) : Boolean
{
return sceneBindings.propertyExists(
LightDataProvider.getLightPropertyName(propertyName, lightId)
);
}
private function getLightProperty(sceneBindings : DataBindingsProxy,
lightId : uint,
propertyName : String) : *
{
return sceneBindings.getProperty(
LightDataProvider.getLightPropertyName(propertyName, lightId)
);
}
}
}
|
fix PhongEffect to properly push the _baseShader and _singlePassShader passes
|
fix PhongEffect to properly push the _baseShader and _singlePassShader passes
|
ActionScript
|
mit
|
aerys/minko-as3
|
8f4cdb13a23d698c19b6a4f007ca546a9d8a2023
|
org/appsroid/RegistryModify.as
|
org/appsroid/RegistryModify.as
|
package org.appsroid {
import flash.events.EventDispatcher;
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.ProgressEvent;
import flash.events.NativeProcessExitEvent;
import flash.filesystem.File;
import flash.events.Event;
public class RegistryModify extends EventDispatcher {
private var _np:NativeProcess;
private var _npi:NativeProcessStartupInfo;
private var _args:Vector.<String>;
private var exePath:String;
public var _output:String;
public function RegistryModify(_exePath:String) {
exePath = _exePath;
}
public function readValue(_rootKey:String, _path:String, _key:String):void {
_args = new Vector.<String>();
_args.push("-action:read", "-key:" + _key, "-path:" + _path, "-rootkey:" + _rootKey);
process();
}
public function writeValue(_rootKey:String, _path:String, _key:String, _value:String):void {
_args = new Vector.<String>();
_args.push("-action:write", "-key:" + _key, "-value:" + _value, "-path:" + _path, "-rootkey:" + _rootKey);
process();
}
public function writeDwordValue(_rootKey:String, _path:String, _key:String, _value:String):void {
_args = new Vector.<String>();
_args.push("-action:writedword", "-key:" + _key, "-value:" + _value, "-path:" + _path, "-rootkey:" + _rootKey);
process();
}
public function deleteKey(_rootKey:String, _path:String):void {
_args = new Vector.<String>();
_args.push("-action:delete", "-path:" + _path, "-rootkey:" + _rootKey);
process();
}
public function checkKey(_rootKey:String, _path:String):void {
_args = new Vector.<String>();
_args.push("-action:check", "-path:" + _path, "-rootkey:" + _rootKey);
process();
}
private function process():void {
_npi = new NativeProcessStartupInfo();
_npi.executable = File.applicationDirectory.resolvePath(exePath);
_npi.arguments = _args;
_np = new NativeProcess();
_np.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
_np.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
_np.addEventListener(NativeProcessExitEvent.EXIT, onExit);
_np.start(_npi);
}
private function onOutputData(e:ProgressEvent):void {
_output = String(_np.standardOutput.readUTFBytes(_np.standardOutput.bytesAvailable));
dispatchEvent(new Event("OutputData"));
}
private function onErrorData(e:ProgressEvent):void {
_output = String(_np.standardError.readUTFBytes(_np.standardError.bytesAvailable));
dispatchEvent(new Event("ErrorData"));
}
private function onExit(e:NativeProcessExitEvent):void {
_np.removeEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
_np.removeEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
_np.removeEventListener(NativeProcessExitEvent.EXIT, onExit);
_npi = null;
_np = null;
_args = null;
dispatchEvent(new Event(Event.COMPLETE));
}
}
}
|
package org.appsroid {
import flash.events.EventDispatcher;
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.ProgressEvent;
import flash.events.NativeProcessExitEvent;
import flash.filesystem.File;
import flash.events.Event;
public class RegistryModify extends EventDispatcher {
private var _np:NativeProcess;
private var _npi:NativeProcessStartupInfo;
private var _args:Vector.<String>;
private var exePath:String;
public var _output:String;
public function RegistryModify(_exePath:String) {
exePath = _exePath;
}
public function readValue(_rootKey:String, _path:String, _key:String):void {
_args = new Vector.<String>();
_args.push("-action:read", "-key:" + _key, "-path:" + _path, "-rootkey:" + _rootKey);
process();
}
public function writeValue(_rootKey:String, _path:String, _key:String, _value:String):void {
_args = new Vector.<String>();
_args.push("-action:write", "-key:" + _key, "-value:" + _value, "-path:" + _path, "-rootkey:" + _rootKey);
process();
}
public function writeDwordValue(_rootKey:String, _path:String, _key:String, _value:String):void {
_args = new Vector.<String>();
_args.push("-action:writedword", "-key:" + _key, "-value:" + _value, "-path:" + _path, "-rootkey:" + _rootKey);
process();
}
public function deleteKey(_rootKey:String, _path:String):void {
_args = new Vector.<String>();
_args.push("-action:delete", "-path:" + _path, "-rootkey:" + _rootKey);
process();
}
public function checkKey(_rootKey:String, _path:String):void {
_args = new Vector.<String>();
_args.push("-action:check", "-path:" + _path, "-rootkey:" + _rootKey);
process();
}
private function process():void {
_npi = new NativeProcessStartupInfo();
_npi.executable = File.applicationDirectory.resolvePath(exePath);
_npi.arguments = _args;
_np = new NativeProcess();
_np.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
_np.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
_np.addEventListener(NativeProcessExitEvent.EXIT, onExit);
_np.start(_npi);
}
private function onOutputData(e:ProgressEvent):void {
_output = String(_np.standardOutput.readUTFBytes(_np.standardOutput.bytesAvailable));
dispatchEvent(new Event("OutputData"));
}
private function onErrorData(e:ProgressEvent):void {
_output = String(_np.standardError.readUTFBytes(_np.standardError.bytesAvailable));
dispatchEvent(new Event("ErrorData"));
}
private function onExit(e:NativeProcessExitEvent):void {
_np.removeEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onOutputData);
_np.removeEventListener(ProgressEvent.STANDARD_ERROR_DATA, onErrorData);
_np.removeEventListener(NativeProcessExitEvent.EXIT, onExit);
_npi = null;
_np = null;
_args = null;
dispatchEvent(new Event(Event.COMPLETE));
}
}
}
|
Update RegistryModify.as
|
Update RegistryModify.as
|
ActionScript
|
mit
|
yaa110/Adobe-Air-Registry-Modifier
|
fcfba8058665c24f4879caacc1f807eeb312dc5d
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import dolly.utils.ClassUtil;
import dolly.utils.PropertyUtil;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.AccessorAccess;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
use namespace dolly_internal;
public class Cloner {
private static var _isClassPreparedForCloningMap:Dictionary = new Dictionary();
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function isTypePreparedForCloning(type:Type):Boolean {
return _isClassPreparedForCloningMap[type.clazz];
}
private static function failIfTypeIsNotCloneable(type:Type):void {
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
}
private static function prepareTypeForCloning(type:Type):void {
ClassUtil.registerAliasFor(type.clazz);
_isClassPreparedForCloningMap[type.clazz] = true;
}
dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> {
failIfTypeIsNotCloneable(type);
if (!isTypePreparedForCloning(type)) {
prepareTypeForCloning(type);
}
const result:Vector.<Field> = new Vector.<Field>();
for each(var field:Field in type.properties) {
if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) {
result.push(field);
}
}
return result;
}
dolly_internal static function doClone(source:*, deep:int, clonedObjectsMap:Dictionary = null, type:Type = null):* {
if (!clonedObjectsMap) {
clonedObjectsMap = new Dictionary();
}
if (!type) {
type = Type.forInstance(source);
}
if(!isTypePreparedForCloning(type)) {
prepareTypeForCloning(type);
}
const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type);
for each(var field:Field in fieldsToClone) {
// PropertyUtil.cloneProperty(source, clonedInstance, field.name);
var fieldType:Type = field.type;
if(isTypeCloneable(fieldType) && !isTypePreparedForCloning(fieldType)) {
prepareTypeForCloning(fieldType);
}
}
const byteArray:ByteArray = new ByteArray();
byteArray.writeObject(source);
byteArray.position = 0;
const clonedInstance:* = byteArray.readObject();
return clonedInstance;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
failIfTypeIsNotCloneable(type);
const deep:int = 2;
return doClone(source, deep, null, type);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import dolly.utils.ClassUtil;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.AccessorAccess;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
use namespace dolly_internal;
public class Cloner {
private static var _isClassPreparedForCloningMap:Dictionary = new Dictionary();
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function isTypePreparedForCloning(type:Type):Boolean {
return _isClassPreparedForCloningMap[type.clazz];
}
private static function failIfTypeIsNotCloneable(type:Type):void {
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
}
private static function prepareTypeForCloning(type:Type):void {
ClassUtil.registerAliasFor(type.clazz);
_isClassPreparedForCloningMap[type.clazz] = true;
}
dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> {
failIfTypeIsNotCloneable(type);
if (!isTypePreparedForCloning(type)) {
prepareTypeForCloning(type);
}
const result:Vector.<Field> = new Vector.<Field>();
for each(var field:Field in type.properties) {
if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) {
result.push(field);
}
}
return result;
}
dolly_internal static function doClone(source:*, type:Type = null):* {
if (!type) {
type = Type.forInstance(source);
}
if (!isTypePreparedForCloning(type)) {
prepareTypeForCloning(type);
}
const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type);
for each(var field:Field in fieldsToClone) {
var fieldType:Type = field.type;
if (isTypeCloneable(fieldType) && !isTypePreparedForCloning(fieldType)) {
prepareTypeForCloning(fieldType);
}
}
const byteArray:ByteArray = new ByteArray();
byteArray.writeObject(source);
byteArray.position = 0;
const clonedInstance:* = byteArray.readObject();
return clonedInstance;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
failIfTypeIsNotCloneable(type);
return doClone(source, type);
}
}
}
|
Remove params "deep" and "clonedObjectsMap" from method Cloner.doCLone().
|
Remove params "deep" and "clonedObjectsMap" from method Cloner.doCLone().
|
ActionScript
|
mit
|
Yarovoy/dolly
|
38189c49dbb766651e8e0af949cfab1865c83398
|
test/trace/trace_properties.as
|
test/trace/trace_properties.as
|
#if __SWF_VERSION__ == 5
// create a _global object, since it doesn't have one, these are ver 6 values
_global = new_empty_object ();
_global.ASSetNative = ASSetNative;
_global.ASSetNativeAccessor = ASSetNativeAccessor;
_global.ASSetPropFlags = ASSetPropFlags;
_global.ASconstructor = ASconstructor;
_global.ASnative = ASnative;
_global.Accessibility = Accessibility;
_global.Array = Array;
_global.AsBroadcaster = AsBroadcaster;
_global.AsSetupError = AsSetupError;
_global.Boolean = Boolean;
_global.Button = Button;
_global.Camera = Camera;
_global.Color = Color;
_global.ContextMenu = ContextMenu;
_global.ContextMenuItem = ContextMenuItem;
_global.Date = Date;
_global.Error = Error;
_global.Function = Function;
_global.Infinity = Infinity;
_global.Key = Key;
_global.LoadVars = LoadVars;
_global.LocalConnection = LocalConnection;
_global.Math = Math;
_global.Microphone = Microphone;
_global.Mouse = Mouse;
_global.MovieClip = MovieClip;
_global.MovieClipLoader = MovieClipLoader;
_global.NaN = NaN;
_global.NetConnection = NetConnection;
_global.NetStream = NetStream;
_global.Number = Number;
_global.Object = Object;
_global.PrintJob = PrintJob;
_global.RemoteLSOUsage = RemoteLSOUsage;
_global.Selection = Selection;
_global.SharedObject = SharedObject;
_global.Sound = Sound;
_global.Stage = Stage;
_global.String = String;
_global.System = System;
_global.TextField = TextField;
_global.TextFormat = TextFormat;
_global.TextSnapshot = TextSnapshot;
_global.Video = Video;
_global.XML = XML;
_global.XMLNode = XMLNode;
_global.XMLSocket = XMLSocket;
_global.clearInterval = clearInterval;
_global.clearTimeout = clearTimeout;
_global.enableDebugConsole = enableDebugConsole;
_global.escape = escape;
_global.flash = flash;
_global.isFinite = isFinite;
_global.isNaN = isNaN;
_global.o = o;
_global.parseFloat = parseFloat;
_global.parseInt = parseInt;
_global.setInterval = setInterval;
_global.setTimeout = setTimeout;
_global.showRedrawRegions = showRedrawRegions;
_global.textRenderer = textRenderer;
_global.trace = trace;
_global.unescape = unescape;
_global.updateAfterEvent = updateAfterEvent;
#endif
function new_empty_object () {
var hash = new Object ();
ASSetPropFlags (hash, null, 0, 7);
for (var prop in hash) {
hash[prop] = "to-be-deleted";
delete hash[prop];
}
return hash;
}
#if __SWF_VERSION__ >= 6
function hasOwnProperty (o, prop)
{
if (o.hasOwnProperty != undefined)
return o.hasOwnProperty (prop);
o.hasOwnProperty = _global.Object.prototype.hasOwnProperty;
var result = o.hasOwnProperty (prop);
delete o.hasOwnProperty;
return result;
}
#else
// this gets the same result as the above, with following limitations:
// - if there is a child __proto__[prop] with value that can't be changed, no
// test can be done and false is returned
// - native properties that have value undefined by default get overwritten by
// __proto__[prop]'s value (atleast in version 6 and 7) so their existance
// won't be detected by this function
function hasOwnProperty (o, prop)
{
if (o.__proto__ == undefined)
{
o.__proto__ = new_empty_object ();
o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa";
if (o[prop] != o.__proto__[prop]) {
result = true;
} else {
result = false;
}
ASSetPropFlags (o, "__proto__", 0, 2);
o.__proto__ = "to-be-deleted";
delete o.__proto__;
if (o.__proto__ != undefined) {
o.__proto__ = undefined;
if (o.__proto__ != undefined)
trace ("ERROR: Couldn't delete temporary __proto__");
}
return result;
}
if (hasOwnProperty (o.__proto__, prop))
{
var constant = false;
var old = o.__proto__[prop];
o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa";
if (o.__proto__[prop] != "safdlojasfljsaiofhiwjhefa") {
constant = true;
ASSetPropFlags (o.__proto__, prop, 0, 4);
o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa";
if (o.__proto__[prop] != "safdlojasfljsaiofhiwjhefa") {
if (o[prop] != o.__proto__[prop]) {
return true;
} else {
//trace ("ERROR: can't test property '" + prop +
// "', __proto__ has superconstant version");
return false;
}
}
}
if (o[prop] != o.__proto__[prop]) {
result = true;
} else {
result = false;
}
o.__proto__[prop] = old;
if (o.__proto__[prop] != old)
trace ("Error: Couldn't set __proto__[\"" + prop +
"\"] back to old value");
if (constant)
ASSetPropFlags (o.__proto__, prop, 4);
return result;
}
else
{
o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa";
if (o[prop] != o.__proto__[prop]) {
result = true;
} else {
result = false;
}
ASSetPropFlags (o, prop, 0, 4);
o.__proto__[prop] = "to-be-deleted";
delete o.__proto__[prop];
if (o.__proto__[prop] != undefined) {
o.__proto__[prop] = undefined;
if (o.__proto__[prop] != undefined)
trace ("ERROR: Couldn't delete temporary __proto__[\"" + prop + "\"]");
}
return result;
}
}
#endif
function new_info () {
return new_empty_object ();
}
function set_info (info, prop, id, value) {
info[prop + "_-_" + id] = value;
}
function get_info (info, prop, id) {
return info[prop + "_-_" + id];
}
function is_blaclisted (o, prop)
{
if (prop == "mySecretId" || prop == "globalSecretId")
return true;
if (o == _global.Camera && prop == "names")
return true;
if (o == _global.Microphone && prop == "names")
return true;
#if __SWF_VERSION__ < 6
if (prop == "__proto__" && o[prop] == undefined)
return true;
#endif
return false;
}
function trace_properties_recurse (o, prefix, identifier, level)
{
// to collect info about different properties
var info = new_info ();
// calculate indentation
var indentation = "";
for (var j = 0; j < level; j++) {
indentation = indentation + " ";
}
// mark the ones that are not hidden
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true)
set_info (info, prop, "hidden", false);
}
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
var hidden = new Array ();
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
if (get_info (info, prop, "hidden") != false) {
set_info (info, prop, "hidden", true);
hidden.push (prop);
}
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, hidden, 1, 0);
if (all.length == 0) {
trace (indentation + "no children");
return nextSecretId;
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// try changing value
var old = o[prop];
var val = "hello " + o[prop];
o[prop] = val;
if (o[prop] != val)
{
set_info (info, prop, "constant", true);
// try changing value after removing constant propflag
ASSetPropFlags (o, prop, 0, 4);
o[prop] = val;
if (o[prop] != val) {
set_info (info, prop, "superconstant", true);
} else {
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
ASSetPropFlags (o, prop, 4);
}
else
{
set_info (info, prop, "constant", false);
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// remove constant flag
ASSetPropFlags (o, prop, 0, 4);
// try deleting
var old = o[prop];
delete o[prop];
if (hasOwnProperty (o, prop))
{
set_info (info, prop, "permanent", true);
}
else
{
set_info (info, prop, "permanent", false);
o[prop] = old;
}
// put constant flag back, if it was set
if (get_info (info, prop, "constant") == true)
ASSetPropFlags (o, prop, 4);
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
// format propflags
var flags = "";
if (get_info (info, prop, "hidden") == true) {
flags += "h";
}
if (get_info (info, prop, "superpermanent") == true) {
flags += "P";
} else if (get_info (info, prop, "permanent") == true) {
flags += "p";
}
if (get_info (info, prop, "superconstant") == true) {
flags += "C";
} else if (get_info (info, prop, "constant") == true) {
flags += "c";
}
if (flags != "")
flags = " (" + flags + ")";
var value = "";
// add value depending on the type
if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") {
value += " : " + o[prop];
} else if (typeof (o[prop]) == "string") {
value += " : \"" + o[prop] + "\"";
}
// recurse if it's object or function and this is the place it has been
// named after
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
{
if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop ==
o[prop]["mySecretId"])
{
trace (indentation + prop + flags + " = " + typeof (o[prop]));
trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop, level + 1);
}
else
{
trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]);
}
}
else
{
trace (indentation + prop + flags + " = " + typeof (o[prop]) + value);
}
}
}
function generate_names (o, prefix, identifier)
{
// mark the ones that are not hidden
var nothidden = new Array ();
for (var prop in o) {
nothidden.push (prop);
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
for (var prop in o)
{
if (is_blaclisted (o, prop) == false) {
// only get the ones that are not only in the __proto__
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, null, 1, 0);
ASSetPropFlags (o, nothidden, 0, 1);
for (var i = 0; i < all.length; i++) {
var prop = all[i];
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") {
if (hasOwnProperty (o[prop], "mySecretId")) {
all[i] = null; // don't recurse to it again
} else {
o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") +
identifier + "." + prop;
}
}
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
if (prop != null) {
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
generate_names (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop);
}
}
}
function trace_properties (o, prefix, identifier)
{
_global["mySecretId"] = "_global";
_global.Object["mySecretId"] = "_global.Object";
_global.XMLNode["mySecretId"] = "_global.XMLNode";
generate_names (_global.Object, "_global", "Object");
generate_names (_global.XMLNode, "_global", "XMLNode");
generate_names (_global, "", "_global");
if (typeof (o) == "object" || typeof (o) == "function")
{
if (o["mySecretId"] == undefined) {
o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier;
generate_names (o, prefix, identifier);
}
if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"])
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o));
}
else
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
o["mySecretId"]);
}
trace_properties_recurse (o, prefix, identifier, 1);
}
else
{
var value = "";
if (typeof (o) == "number" || typeof (o) == "boolean") {
value += " : " + o;
} else if (typeof (o) == "string") {
value += " : \"" + o + "\"";
}
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o) + value);
}
}
|
#if __SWF_VERSION__ == 5
// create a _global object, since it doesn't have one, these are ver 6 values
_global = new_empty_object ();
_global.ASSetNative = ASSetNative;
_global.ASSetNativeAccessor = ASSetNativeAccessor;
_global.ASSetPropFlags = ASSetPropFlags;
_global.ASconstructor = ASconstructor;
_global.ASnative = ASnative;
_global.Accessibility = Accessibility;
_global.Array = Array;
_global.AsBroadcaster = AsBroadcaster;
_global.AsSetupError = AsSetupError;
_global.Boolean = Boolean;
_global.Button = Button;
_global.Camera = Camera;
_global.Color = Color;
_global.ContextMenu = ContextMenu;
_global.ContextMenuItem = ContextMenuItem;
_global.Date = Date;
_global.Error = Error;
_global.Function = Function;
_global.Infinity = Infinity;
_global.Key = Key;
_global.LoadVars = LoadVars;
_global.LocalConnection = LocalConnection;
_global.Math = Math;
_global.Microphone = Microphone;
_global.Mouse = Mouse;
_global.MovieClip = MovieClip;
_global.MovieClipLoader = MovieClipLoader;
_global.NaN = NaN;
_global.NetConnection = NetConnection;
_global.NetStream = NetStream;
_global.Number = Number;
_global.Object = Object;
_global.PrintJob = PrintJob;
_global.RemoteLSOUsage = RemoteLSOUsage;
_global.Selection = Selection;
_global.SharedObject = SharedObject;
_global.Sound = Sound;
_global.Stage = Stage;
_global.String = String;
_global.System = System;
_global.TextField = TextField;
_global.TextFormat = TextFormat;
_global.TextSnapshot = TextSnapshot;
_global.Video = Video;
_global.XML = XML;
_global.XMLNode = XMLNode;
_global.XMLSocket = XMLSocket;
_global.clearInterval = clearInterval;
_global.clearTimeout = clearTimeout;
_global.enableDebugConsole = enableDebugConsole;
_global.escape = escape;
_global.flash = flash;
_global.isFinite = isFinite;
_global.isNaN = isNaN;
_global.o = o;
_global.parseFloat = parseFloat;
_global.parseInt = parseInt;
_global.setInterval = setInterval;
_global.setTimeout = setTimeout;
_global.showRedrawRegions = showRedrawRegions;
_global.textRenderer = textRenderer;
_global.trace = trace;
_global.unescape = unescape;
_global.updateAfterEvent = updateAfterEvent;
#endif
function new_empty_object () {
var hash = new Object ();
ASSetPropFlags (hash, null, 0, 7);
for (var prop in hash) {
hash[prop] = "to-be-deleted";
delete hash[prop];
}
return hash;
}
#if __SWF_VERSION__ >= 6
function hasOwnProperty (o, prop)
{
if (o.hasOwnProperty != undefined)
return o.hasOwnProperty (prop);
o.hasOwnProperty = _global.Object.prototype.hasOwnProperty;
var result = o.hasOwnProperty (prop);
delete o.hasOwnProperty;
return result;
}
#else
// this gets the same result as the above, with following limitations:
// - if there is a child __proto__[prop] with value that can't be changed, no
// test can be done and false is returned
// - native properties that have value undefined by default get overwritten by
// __proto__[prop]'s value (atleast in version 6 and 7) so their existance
// won't be detected by this function
function hasOwnProperty (o, prop)
{
if (o.__proto__ == undefined)
{
o.__proto__ = new_empty_object ();
o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa";
if (o[prop] != o.__proto__[prop]) {
result = true;
} else {
result = false;
}
ASSetPropFlags (o, "__proto__", 0, 2);
o.__proto__ = "to-be-deleted";
delete o.__proto__;
if (o.__proto__ != undefined) {
o.__proto__ = undefined;
if (o.__proto__ != undefined)
trace ("ERROR: Couldn't delete temporary __proto__");
}
return result;
}
if (hasOwnProperty (o.__proto__, prop))
{
var constant = false;
var old = o.__proto__[prop];
o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa";
if (o.__proto__[prop] != "safdlojasfljsaiofhiwjhefa") {
constant = true;
ASSetPropFlags (o.__proto__, prop, 0, 4);
o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa";
if (o.__proto__[prop] != "safdlojasfljsaiofhiwjhefa") {
if (o[prop] != o.__proto__[prop]) {
return true;
} else {
//trace ("ERROR: can't test property '" + prop +
// "', __proto__ has superconstant version");
return false;
}
}
}
if (o[prop] != o.__proto__[prop]) {
result = true;
} else {
result = false;
}
o.__proto__[prop] = old;
if (o.__proto__[prop] != old)
trace ("Error: Couldn't set __proto__[\"" + prop +
"\"] back to old value");
if (constant)
ASSetPropFlags (o.__proto__, prop, 4);
return result;
}
else
{
o.__proto__[prop] = "safdlojasfljsaiofhiwjhefa";
if (o[prop] != o.__proto__[prop]) {
result = true;
} else {
result = false;
}
ASSetPropFlags (o, prop, 0, 4);
o.__proto__[prop] = "to-be-deleted";
delete o.__proto__[prop];
if (o.__proto__[prop] != undefined) {
o.__proto__[prop] = undefined;
if (o.__proto__[prop] != undefined)
trace ("ERROR: Couldn't delete temporary __proto__[\"" + prop + "\"]");
}
return result;
}
}
#endif
function new_info () {
return new_empty_object ();
}
function set_info (info, prop, id, value) {
info[prop + "_-_" + id] = value;
}
function get_info (info, prop, id) {
return info[prop + "_-_" + id];
}
function is_blaclisted (o, prop)
{
if (prop == "mySecretId" || prop == "globalSecretId")
return true;
if (o == _global.Camera && prop == "names")
return true;
if (o == _global.Microphone && prop == "names")
return true;
#if __SWF_VERSION__ < 6
if (prop == "__proto__" && o[prop] == undefined)
return true;
#endif
return false;
}
function trace_properties_recurse (o, prefix, identifier, level)
{
// to collect info about different properties
var info = new_info ();
// calculate indentation
var indentation = "";
for (var j = 0; j < level; j++) {
indentation = indentation + " ";
}
// mark the ones that are not hidden
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true)
set_info (info, prop, "hidden", false);
}
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
var hidden = new Array ();
for (var prop in o)
{
// only get the ones that are not only in the __proto__
if (is_blaclisted (o, prop) == false) {
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
if (get_info (info, prop, "hidden") != false) {
set_info (info, prop, "hidden", true);
hidden.push (prop);
}
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, hidden, 1, 0);
if (all.length == 0) {
trace (indentation + "no children");
return nextSecretId;
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// try changing value
var old = o[prop];
var val = "hello " + o[prop];
o[prop] = val;
if (o[prop] != val)
{
set_info (info, prop, "constant", true);
// try changing value after removing constant propflag
ASSetPropFlags (o, prop, 0, 4);
o[prop] = val;
if (o[prop] != val) {
set_info (info, prop, "superconstant", true);
} else {
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
ASSetPropFlags (o, prop, 4);
}
else
{
set_info (info, prop, "constant", false);
set_info (info, prop, "superconstant", false);
o[prop] = old;
}
}
for (var i = 0; i < all.length; i++)
{
var prop = all[i];
// remove constant flag
ASSetPropFlags (o, prop, 0, 4);
// try deleting
var old = o[prop];
delete o[prop];
if (hasOwnProperty (o, prop))
{
set_info (info, prop, "permanent", true);
}
else
{
set_info (info, prop, "permanent", false);
o[prop] = old;
}
// put constant flag back, if it was set
if (get_info (info, prop, "constant") == true)
ASSetPropFlags (o, prop, 4);
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
// format propflags
var flags = "";
if (get_info (info, prop, "hidden") == true) {
flags += "h";
}
if (get_info (info, prop, "superpermanent") == true) {
flags += "P";
} else if (get_info (info, prop, "permanent") == true) {
flags += "p";
}
if (get_info (info, prop, "superconstant") == true) {
flags += "C";
} else if (get_info (info, prop, "constant") == true) {
flags += "c";
}
if (flags != "")
flags = " (" + flags + ")";
var value = "";
// add value depending on the type
if (typeof (o[prop]) == "number" || typeof (o[prop]) == "boolean") {
value += " : " + o[prop];
} else if (typeof (o[prop]) == "string") {
value += " : \"" + o[prop] + "\"";
}
// recurse if it's object or function and this is the place it has been
// named after
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
{
if (prefix + (prefix != "" ? "." : "") + identifier + "." + prop ==
o[prop]["mySecretId"])
{
trace (indentation + prop + flags + " = " + typeof (o[prop]));
trace_properties_recurse (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop, level + 1);
}
else
{
trace (indentation + prop + flags + " = " + o[prop]["mySecretId"]);
}
}
else
{
trace (indentation + prop + flags + " = " + typeof (o[prop]) + value);
}
}
}
function generate_names (o, prefix, identifier)
{
// mark the ones that are not hidden
var nothidden = new Array ();
for (var prop in o) {
nothidden.push (prop);
}
// unhide everything
ASSetPropFlags (o, null, 0, 1);
var all = new Array ();
for (var prop in o)
{
if (is_blaclisted (o, prop) == false) {
// only get the ones that are not only in the __proto__
if (hasOwnProperty (o, prop) == true) {
all.push (prop);
}
}
}
all.sort ();
// hide the ones that were already hidden
ASSetPropFlags (o, null, 1, 0);
ASSetPropFlags (o, nothidden, 0, 1);
for (var i = 0; i < all.length; i++) {
var prop = all[i];
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function") {
if (hasOwnProperty (o[prop], "mySecretId")) {
all[i] = null; // don't recurse to it again
} else {
o[prop]["mySecretId"] = prefix + (prefix != "" ? "." : "") +
identifier + "." + prop;
}
}
}
for (var i = 0; i < all.length; i++) {
var prop = all[i];
if (prop != null) {
if (typeof (o[prop]) == "object" || typeof (o[prop]) == "function")
generate_names (o[prop], prefix + (prefix != "" ? "." : "") +
identifier, prop);
}
}
}
function trace_properties (o, prefix, identifier)
{
_global["mySecretId"] = "_global";
_global.Object["mySecretId"] = "_global.Object";
_global.XMLNode["mySecretId"] = "_global.XMLNode";
generate_names (_global.Object, "_global", "Object");
generate_names (_global.XMLNode, "_global", "XMLNode");
generate_names (_global, "", "_global");
if (typeof (o) == "object" || typeof (o) == "function")
{
if (!o.hasOwnProperty ("mySecretId")) {
o["mySecretId"] = prefix + (prefix != "" ? "." : "") + identifier;
generate_names (o, prefix, identifier);
}
if (prefix + (prefix != "" ? "." : "") + identifier == o["mySecretId"])
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o));
}
else
{
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
o["mySecretId"]);
}
trace_properties_recurse (o, prefix, identifier, 1);
}
else
{
var value = "";
if (typeof (o) == "number" || typeof (o) == "boolean") {
value += " : " + o;
} else if (typeof (o) == "string") {
value += " : \"" + o + "\"";
}
trace (prefix + (prefix != "" ? "." : "") + identifier + " = " +
typeof (o) + value);
}
}
|
use hasOwnProperty instead of != undefined to figure out if the object has the property
|
use hasOwnProperty instead of != undefined to figure out if the object has the property
|
ActionScript
|
lgpl-2.1
|
freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,freedesktop-unofficial-mirror/swfdec__swfdec,mltframework/swfdec
|
5e50685006af69b6cff3fa45a7c5d4318138cc18
|
src/com/jonas/net/Multipart.as
|
src/com/jonas/net/Multipart.as
|
package com.jonas.net
{
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLRequestHeader;
import flash.utils.ByteArray;
/**
*
* Based on RFC 1867 + real case observation
*
* RFC 1867
* https://tools.ietf.org/html/rfc1867
*
*/
public class Multipart
{
private var _url:String;
private var _fields:Array = [];
private var _files:Array = [];
private var _data:ByteArray = new ByteArray();
private var _encoding:String = 'utf-8'; //http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/charset-codes.html
public function Multipart(url:String = null) {
_url = url;
}
public function addFields(fields:Object):void {
for (var s:String in fields) {
addField(s, fields[s]);
}
}
public function addField(name:String, value:String):void {
_fields.push({name:name, value:value});
}
public function addFile(name:String, byteArray:ByteArray, mimeType:String, fileName:String):void {
_files.push({name:name, byteArray:byteArray, mimeType:mimeType, fileName:fileName});
}
public function clear():void {
_data = new ByteArray();
_fields = [];
_files = [];
}
public function get request():URLRequest
{
var boundary: String = (Math.round(Math.random()*100000000)).toString();
var n:uint;
var i:uint;
// Add fields
n = _fields.length;
for(i=0; i<n; i++){
_writeString('--' + boundary + '\r\n'
+ 'Content-Disposition: form-data; name="' + _fields[i].name+'"\r\n\r\n');
_writeString(_fields[i].value, _encoding);
_writeString('\r\n');
}
// Add files
n = _files.length;
for(i=0; i<n; i++){
_writeString('--'+boundary + '\r\n'
+'Content-Disposition: form-data; name="'+_files[i].name+'"; filename="'+_files[i].fileName+'"\r\n'
+'Content-Type: '+_files[i].mimeType+'\r\n\r\n');
_writeBytes(_files[i].byteArray);
_writeString('\r\n');
}
// Close
_writeString('--' + boundary + '--\r\n');
var r: URLRequest = new URLRequest(_url);
r.data = _data;
r.method = URLRequestMethod.POST;
r.requestHeaders.push( new URLRequestHeader('Content-type', 'multipart/form-data; boundary=' + boundary) );
return r;
}
public function get url():String
{
return _url;
}
public function set url(value:String):void
{
_url = value;
}
public function get encoding():String
{
return _encoding;
}
public function set encoding(value:String):void
{
_encoding = value;
}
private function _writeString(value:String, encoding:String = 'ascii'):void {
var b:ByteArray = new ByteArray();
b.writeMultiByte(value, encoding);
_data.writeBytes(b, 0, b.length);
}
private function _writeBytes(value:ByteArray):void {
//_writeString("....FILE....");
value.position = 0;
_data.writeBytes(value, 0, value.length);
}
}
}
|
/*
* Copyright 2017 Jonas Monnier
*
* 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.jonas.net
{
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLRequestHeader;
import flash.utils.ByteArray;
/**
*
* Based on RFC 1867 + real case observation
*
* RFC 1867
* https://tools.ietf.org/html/rfc1867
*
*/
public class Multipart
{
private var _url:String;
private var _fields:Array = [];
private var _files:Array = [];
private var _data:ByteArray = new ByteArray();
private var _encoding:String = 'utf-8'; //http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/charset-codes.html
public function Multipart(url:String = null) {
_url = url;
}
public function addFields(fields:Object):void {
for (var s:String in fields) {
addField(s, fields[s]);
}
}
public function addField(name:String, value:String):void {
_fields.push({name:name, value:value});
}
public function addFile(name:String, byteArray:ByteArray, mimeType:String, fileName:String):void {
_files.push({name:name, byteArray:byteArray, mimeType:mimeType, fileName:fileName});
}
public function clear():void {
_data = new ByteArray();
_fields = [];
_files = [];
}
public function get request():URLRequest
{
var boundary: String = (Math.round(Math.random()*100000000)).toString();
var n:uint;
var i:uint;
// Add fields
n = _fields.length;
for(i=0; i<n; i++){
_writeString('--' + boundary + '\r\n'
+ 'Content-Disposition: form-data; name="' + _fields[i].name+'"\r\n\r\n');
_writeString(_fields[i].value, _encoding);
_writeString('\r\n');
}
// Add files
n = _files.length;
for(i=0; i<n; i++){
_writeString('--'+boundary + '\r\n'
+'Content-Disposition: form-data; name="'+_files[i].name+'"; filename="'+_files[i].fileName+'"\r\n'
+'Content-Type: '+_files[i].mimeType+'\r\n\r\n');
_writeBytes(_files[i].byteArray);
_writeString('\r\n');
}
// Close
_writeString('--' + boundary + '--\r\n');
var r: URLRequest = new URLRequest(_url);
r.data = _data;
r.method = URLRequestMethod.POST;
r.requestHeaders.push( new URLRequestHeader('Content-type', 'multipart/form-data; boundary=' + boundary) );
return r;
}
public function get url():String
{
return _url;
}
public function set url(value:String):void
{
_url = value;
}
public function get encoding():String
{
return _encoding;
}
public function set encoding(value:String):void
{
_encoding = value;
}
private function _writeString(value:String, encoding:String = 'ascii'):void {
var b:ByteArray = new ByteArray();
b.writeMultiByte(value, encoding);
_data.writeBytes(b, 0, b.length);
}
private function _writeBytes(value:ByteArray):void {
//_writeString("....FILE....");
value.position = 0;
_data.writeBytes(value, 0, value.length);
}
}
}
|
Add licensing header
|
Add licensing header
|
ActionScript
|
apache-2.0
|
jimojon/Multipart.as
|
751be587ad49079857289643abfd0f0af00653ec
|
WEB-INF/lps/lfc/data/LzMediaLoader.as
|
WEB-INF/lps/lfc/data/LzMediaLoader.as
|
/******************************************************************************
* LzMediaLoader.as
*****************************************************************************/
//* A_LZ_COPYRIGHT_BEGIN ******************************************************
//* Copyright 2001-2006 Laszlo Systems, Inc. All Rights Reserved. *
//* Use is subject to license terms. *
//* A_LZ_COPYRIGHT_END ********************************************************
//==============================================================================
// DEFINE OBJECT: LzMediaLoader
// @keywords private
//==============================================================================
LzMediaLoader = Class(
"LzMediaLoader",
LzLoader,
function ( owner , args ) {
#pragma 'methodName=constructor'
super( owner ,args );
this.owner.loadperc = 0;
this.loadChecker = new _root.LzDelegate( this , "testLoad" );
this.removeLoadCheckerDel =
new _root.LzDelegate( this,
"removeLoadChecker", this, "onloaddone" );
this.timeout = canvas.medialoadtimeout;
//setup loadmovie stuff that never changes
this.mc.loader = this;
this.mc.mc = this.mc;
this.mc.timeout = this.timeout;
this.lastrequest = this.mc;
// [2005-08-28] We use the view's clip as the loadobj, so
// monitor it (as we would in LzLoader if we created a new
// loadobj).
if ($debug) {
LzLoader.debugLoadObj(this.mc, 'MediaLoadObj');
}
}
);
LzMediaLoader.prototype.LOADERDEPTH = 9;
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.removeLoadChecker = function() {
// Remove loadChecker delegate
this.loadChecker.unregisterAll();
this.removeLoadCheckerDel.unregisterAll();
}
//==============================================================================
// @keywords private
// [2005-08-29 ptw] It appears the intent here is that there is 1
// media loader per view with a resource, so we use the view's
// movieclip as the loadmovie, rather than creating another.
//==============================================================================
LzMediaLoader.prototype.getLoadMovie = function ( ){
// Abort any load in progress
this.unload( this.mc );
if (this.isaudio != true && this._oldmc != null) {
// restore regular loader if audio was used before.
this.mc.unload();
var m = this._oldmc;
this._oldmc = null;
this.mc = m;
} else if (this.isaudio == true && this._oldmc == null) {
this._oldmc = this.mc;
this.mc = new SoundMC(this.mc);
this.initializeRequestObj(mc);
if ($debug) {
LzLoader.debugLoadObj(this.mc, 'MediaLoadObj');
}
//_root.Debug.warn('getLoadMovie lmc %w %w', this.mc, this.mc.lmc)
} else {
//_root.Debug.warn('getLoadMovie not audio %2 %w', this.mc, this.mc.lmc)
}
// return the view's clip
return this.mc;
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.attachLoadMovie = function ( resc ){
var mc = this.getLoadMovie();
//Debug.warn('attachLoadMovie %w %w %w', resc, mc, this._oldmc)
if (this.isaudio == true && this._oldmc != null) {
// restore regular loader if audio was used before.
this.mc.unload();
var m = this._oldmc;
this._oldmc = null;
this.mc = m;
mc = m;
}
if (resc) {
mc.attachMovie( resc , "lmc", this.LOADERDEPTH );
if (this.mc.loading == true) LzLoadQueue.loadFinished( mc );
} else {
Debug.error('%w.attachMovie(%w)', this, resc);
}
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.startingLoad = function ( loadmc ){
this.checkonce = false;
this.loadChecker.register( _root.LzIdle, "onidle" );
}
//=============================================================================
// Media types which cannot be loaded directly (serverless) at runtime.
//
// We use a blacklist instead of a whitelist, because the user may
// want to access a URL which generates a supported format, but has an
// suffix from which it is not possible to deduce the file type, like
// .jsp or .php.
LzMediaLoader.unsupportedMediaTypes = {
"bmp": true,
"tiff": true,
"tif": true,
"wmf": true,
"wmv": true
};
LzMediaLoader.unsupportedMediaTypesSWF7 = {
"png": true,
"gif": true
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.request = function( req , cache , headers ) {
var o = { url: req , lzt: "media", timeout: this.timeout };
if ( cache == "none" ){
o.cache = false;
o.ccache = false;
} else if ( cache == "clientonly" ){
o.cache = false;
o.ccache = true;
} else if ( cache == "serveronly" ){
o.cache = true;
o.ccache = false;
} else {
o.cache = true;
o.ccache = true;
}
var policy = _root.LzView.__LZcheckProxyPolicy( req );
this.proxied = policy;
o.proxied = policy;
if (!this.proxied) {
// warn for unsupported media types
var suffix = null;
var si = req.lastIndexOf(".");
if (si != -1) {
suffix = req.substring(si+1, si.length).toLowerCase();
}
if ($debug) {
if (suffix != null && ((LzMediaLoader.unsupportedMediaTypes[suffix] == true)
||
((canvas.runtime == "swf7" || canvas.runtime == "swf6")
&& (LzMediaLoader.unsupportedMediaTypesSWF7[suffix] == true)))) {
_root.Debug.write("WARNING: serverless loading of resources with type '"
+ suffix + "' is not supported by the Flash player. " +
req);
}
}
if (suffix == 'mp3') {
this.isaudio = true;
} else {
this.isaudio = false;
}
//_root.Debug.write('suffix', suffix, this.isaudio);
}
if ( headers != null ) o.headers = headers;
super.request( o );
this.owner.setAttribute( "framesloadratio" , 0 );
this.owner.setAttribute( "loadratio" , 0 );
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.testLoad = function (){
//skip first check because this can get called before load starts, in
//which case load info is wrong
//getBytesTotal is wrong before the header of the movie has loaded
/*
_root.Debug.write('%w %w %w %w %w %w %w %w %w', this.mc.lmc, typeof(this.mc.lmc.getBytesTotal),
this.mc.lmc.getBytesLoaded(), typeof(this.mc.lmc.getBytesLoaded()),
this.mc.lmc.getBytesTotal(), typeof(this.mc.lmc.getBytesTotal()),
this.mc.lmc._currentframe, this.mc.lmc._framesloaded, this.mc.lmc._totalframes);
*/
if ( this.checkonce ){
var lr = this.mc.lmc.getBytesLoaded() / this.mc.lmc.getBytesTotal();
if (lr != this.owner["loadratio"]) {
this.owner.setAttribute("loadratio" , lr);
//reset timeout for media which is streaming
this.mc.loadtime = getTimer();
}
}
if ( this.checkonce && this.mc.lmc.getBytesTotal == void 0
&& this.mc.lmc._totalframes > 0 ) {
//a swf loaded from another domain will be sandboxed. no load
//information is available;
if ( !this.sentLoadStart ){
this.sentLoadStart = true;
if ( ! this.mc.loaded ) {
this.onstreamstart.sendEvent( this );
}
}
var nlp = this.mc.lmc._framesloaded /
this.mc.lmc._totalframes;
if ( nlp > this.owner.loadperc ){
//reset timeout for media which is streaming
//_root.Debug.write( "here" , this.mc.lmc._framesloaded ,
//this.mc.lmc._totalframes );
if (this.mc.lmc._totalframes > 0) {
var nlp = this.mc.lmc._framesloaded /
this.mc.lmc._totalframes;
if ( nlp > this.owner.loadperc ){
//reset timeout for media which is streaming
this.mc.loadtime = getTimer();
}
this.owner.loadperc = nlp;
this.owner.onloadperc.sendEvent( this.owner.loadperc );
this.owner.setAttribute( "framesloadratio" , nlp );
this.owner.setAttribute( "loadratio" , nlp );
if ( this.mc.lmc._totalframes == this.mc.lmc._framesloaded){
this.onloaddone.sendEvent( this );
this.returnData( this.mc );
}
}
}
}
if ( this.checkonce && this.mc.lmc._currentframe > 0
&& typeof(this.mc.lmc.getBytesTotal) != "undefined"
&& this.mc.lmc.getBytesTotal() > this.minHeader ) {
if ( !this.sentLoadStart ){
this.sentLoadStart = true;
//this assumes that an error swf will have already called back
//into the LFC by the time the load is detected. If this is
//wrong, then the view will send both onload and onrror.
if ( ! this.mc.loaded ) {
this.onstreamstart.sendEvent( this );
}
}
if (this.mc.lmc._totalframes > 0) {
var nlp = this.mc.lmc._framesloaded /
this.mc.lmc._totalframes;
if ( nlp > this.owner.loadperc ){
//reset timeout for media which is streaming
this.mc.loadtime = getTimer();
}
this.owner.loadperc = nlp;
this.owner.onloadperc.sendEvent( this.owner.loadperc );
this.owner.setAttribute( "framesloadratio" , nlp );
}
if ( this.mc.lmc.getBytesTotal() == this.mc.lmc.getBytesLoaded() ){
//load is done
this.onloaddone.sendEvent( this );
//if mc.loaded is set, means returnData has already been called
//(probably by error swf.)
if ( !this.mc.loaded ){
this.returnData( this.mc );
}
}
}
if ( !this.checkonce ){
this.sentLoadStart = false;
this.checkonce = true;
}
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.unload= function ( loadobj ){
super.unload( loadobj );
if ( this.owner.loadratio != 0 ){
this.owner.loadperc = 0;
this.owner.onloadperc.sendEvent( 0 );
this.owner.setAttribute( "loadratio" , 0 );
this.owner.setAttribute( "framesloadratio" , 0 );
}
this.removeLoadChecker();
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.getLoadMC= function (){
return this.mc.lmc;
}
|
/******************************************************************************
* LzMediaLoader.as
*****************************************************************************/
//* A_LZ_COPYRIGHT_BEGIN ******************************************************
//* Copyright 2001-2006 Laszlo Systems, Inc. All Rights Reserved. *
//* Use is subject to license terms. *
//* A_LZ_COPYRIGHT_END ********************************************************
//==============================================================================
// DEFINE OBJECT: LzMediaLoader
// @keywords private
//==============================================================================
LzMediaLoader = Class(
"LzMediaLoader",
LzLoader,
function ( owner , args ) {
#pragma 'methodName=constructor'
super( owner ,args );
this.owner.loadperc = 0;
this.loadChecker = new _root.LzDelegate( this , "testLoad" );
this.removeLoadCheckerDel =
new _root.LzDelegate( this,
"removeLoadChecker", this, "onloaddone" );
this.timeout = canvas.medialoadtimeout;
//setup loadmovie stuff that never changes
this.mc.loader = this;
this.mc.mc = this.mc;
this.mc.timeout = this.timeout;
this.lastrequest = this.mc;
// [2005-08-28] We use the view's clip as the loadobj, so
// monitor it (as we would in LzLoader if we created a new
// loadobj).
if ($debug) {
LzLoader.debugLoadObj(this.mc, 'MediaLoadObj');
}
}
);
LzMediaLoader.prototype.LOADERDEPTH = 9;
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.removeLoadChecker = function() {
// Remove loadChecker delegate
this.loadChecker.unregisterAll();
this.removeLoadCheckerDel.unregisterAll();
}
//==============================================================================
// @keywords private
// [2005-08-29 ptw] It appears the intent here is that there is 1
// media loader per view with a resource, so we use the view's
// movieclip as the loadmovie, rather than creating another.
//==============================================================================
LzMediaLoader.prototype.getLoadMovie = function ( ){
// Abort any load in progress
this.unload( this.mc );
if (this.isaudio != true && this._oldmc != null) {
// restore regular loader if audio was used before.
this.mc.unload();
var m = this._oldmc;
this._oldmc = null;
this.mc = m;
} else if (this.isaudio == true && this._oldmc == null) {
this._oldmc = this.mc;
this.mc = new SoundMC(this.mc);
this.initializeRequestObj(mc);
if ($debug) {
LzLoader.debugLoadObj(this.mc, 'MediaLoadObj');
}
//_root.Debug.warn('getLoadMovie lmc %w %w', this.mc, this.mc.lmc)
} else {
//_root.Debug.warn('getLoadMovie not audio %2 %w', this.mc, this.mc.lmc)
}
// return the view's clip
return this.mc;
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.attachLoadMovie = function ( resc ){
var mc = this.getLoadMovie();
//Debug.warn('attachLoadMovie %w %w %w', resc, mc, this._oldmc)
if (this.isaudio == true && this._oldmc != null) {
// restore regular loader if audio was used before.
this.mc.unload();
var m = this._oldmc;
this._oldmc = null;
this.mc = m;
mc = m;
}
if (resc) {
mc.attachMovie( resc , "lmc", this.LOADERDEPTH );
if (this.mc.loading == true) {
Debug.error('already loading', this.mc);
LzLoadQueue.loadFinished( mc );
}
} else {
Debug.error('%w.attachMovie(%w)', this, resc);
}
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.startingLoad = function ( loadmc ){
this.checkonce = false;
this.loadChecker.register( LzIdle, "onidle" );
this.removeLoadCheckerDel.register( this, "onloaddone" );
}
//=============================================================================
// Media types which cannot be loaded directly (serverless) at runtime.
//
// We use a blacklist instead of a whitelist, because the user may
// want to access a URL which generates a supported format, but has an
// suffix from which it is not possible to deduce the file type, like
// .jsp or .php.
LzMediaLoader.unsupportedMediaTypes = {
"bmp": true,
"tiff": true,
"tif": true,
"wmf": true,
"wmv": true
};
LzMediaLoader.unsupportedMediaTypesSWF7 = {
"png": true,
"gif": true
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.request = function( req , cache , headers ) {
var o = { url: req , lzt: "media", timeout: this.timeout };
if ( cache == "none" ){
o.cache = false;
o.ccache = false;
} else if ( cache == "clientonly" ){
o.cache = false;
o.ccache = true;
} else if ( cache == "serveronly" ){
o.cache = true;
o.ccache = false;
} else {
o.cache = true;
o.ccache = true;
}
var policy = _root.LzView.__LZcheckProxyPolicy( req );
this.proxied = policy;
o.proxied = policy;
if (!this.proxied) {
// warn for unsupported media types
var suffix = null;
var si = req.lastIndexOf(".");
if (si != -1) {
suffix = req.substring(si+1, si.length).toLowerCase();
}
if ($debug) {
if (suffix != null && ((LzMediaLoader.unsupportedMediaTypes[suffix] == true)
||
((canvas.runtime == "swf7" || canvas.runtime == "swf6")
&& (LzMediaLoader.unsupportedMediaTypesSWF7[suffix] == true)))) {
_root.Debug.write("WARNING: serverless loading of resources with type '"
+ suffix + "' is not supported by the Flash player. " +
req);
}
}
if (suffix == 'mp3') {
this.isaudio = true;
} else {
this.isaudio = false;
}
//_root.Debug.write('suffix', suffix, this.isaudio);
}
if ( headers != null ) o.headers = headers;
super.request( o );
this.owner.setAttribute( "framesloadratio" , 0 );
this.owner.setAttribute( "loadratio" , 0 );
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.testLoad = function (){
//skip first check because this can get called before load starts, in
//which case load info is wrong
//getBytesTotal is wrong before the header of the movie has loaded
/*
Debug.write('%w %w %w %w %w %w %w %w %w', this.mc.lmc, typeof(this.mc.lmc.getBytesTotal),
this.mc.lmc.getBytesLoaded(), typeof(this.mc.lmc.getBytesLoaded()),
this.mc.lmc.getBytesTotal(), typeof(this.mc.lmc.getBytesTotal()),
this.mc.lmc._currentframe, this.mc.lmc._framesloaded, this.mc.lmc._totalframes);
*/
if ( this.isjpeg && this.mc.lmc._height <= 0) {
//Debug.error('skipping 0 height jpeg');
return;
}
if ( this.checkonce ){
var lr = this.mc.lmc.getBytesLoaded() / this.mc.lmc.getBytesTotal();
if (lr != this.owner["loadratio"] && !isNaN(lr)) {
this.owner.setAttribute("loadratio" , lr);
//reset timeout for media which is streaming
this.mc.loadtime = getTimer();
}
}
if ( this.checkonce && this.mc.lmc.getBytesTotal == void 0
&& this.mc.lmc._totalframes > 0 ) {
//a swf loaded from another domain will be sandboxed. no load
//information is available;
if ( !this.sentLoadStart ){
this.sentLoadStart = true;
if ( ! this.mc.loaded ) {
this.onstreamstart.sendEvent( this );
}
}
var nlp = this.mc.lmc._framesloaded /
this.mc.lmc._totalframes;
if ( nlp >= this.owner.loadperc ){
//reset timeout for media which is streaming
//Debug.write( "here" , this.mc.lmc._framesloaded ,
//this.mc.lmc._totalframes );
if (this.mc.lmc._totalframes > 0) {
var nlp = this.mc.lmc._framesloaded /
this.mc.lmc._totalframes;
if ( nlp > this.owner.loadperc ){
//reset timeout for media which is streaming
this.mc.loadtime = getTimer();
}
this.owner.loadperc = nlp;
this.owner.onloadperc.sendEvent( this.owner.loadperc );
this.owner.setAttribute( "framesloadratio" , nlp );
this.owner.setAttribute( "loadratio" , nlp );
if ( this.mc.lmc._totalframes == this.mc.lmc._framesloaded){
this.onloaddone.sendEvent( this );
this.returnData( this.mc );
}
}
}
}
if ( this.checkonce && this.mc.lmc._currentframe > 0
&& typeof(this.mc.lmc.getBytesTotal) != "undefined"
&& this.mc.lmc.getBytesTotal() > this.minHeader ) {
if ( !this.sentLoadStart ){
this.sentLoadStart = true;
//this assumes that an error swf will have already called back
//into the LFC by the time the load is detected. If this is
//wrong, then the view will send both onload and onrror.
if ( ! this.mc.loaded ) {
this.onstreamstart.sendEvent( this );
}
}
if (this.mc.lmc._totalframes > 0) {
var nlp = this.mc.lmc._framesloaded /
this.mc.lmc._totalframes;
if ( nlp > this.owner.loadperc ){
//reset timeout for media which is streaming
this.mc.loadtime = getTimer();
}
this.owner.loadperc = nlp;
this.owner.onloadperc.sendEvent( this.owner.loadperc );
this.owner.setAttribute( "framesloadratio" , nlp );
}
if ( this.mc.lmc.getBytesTotal() == this.mc.lmc.getBytesLoaded() ){
//load is done
this.onloaddone.sendEvent( this );
//if mc.loaded is set, means returnData has already been called
//(probably by error swf.)
if ( !this.mc.loaded ){
this.returnData( this.mc );
}
}
}
if ( !this.checkonce ){
this.sentLoadStart = false;
this.checkonce = true;
}
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.unload= function ( loadobj ){
super.unload( loadobj );
if ( this.owner.loadratio != 0 ){
this.owner.loadperc = 0;
this.owner.onloadperc.sendEvent( 0 );
this.owner.setAttribute( "loadratio" , 0 );
this.owner.setAttribute( "framesloadratio" , 0 );
}
this.removeLoadChecker();
}
//==============================================================================
// @keywords private
//==============================================================================
LzMediaLoader.prototype.getLoadMC= function (){
return this.mc.lmc;
}
|
Change change.BGFgJ2908.txt by hqm@IBM-AA473F7AA76 /home/hqm/src/svn/openlaszlo/trunk/WEB-INF/lps/lfc/ on 2006-09-25 13:04:28 EDT
|
Change change.BGFgJ2908.txt by hqm@IBM-AA473F7AA76 /home/hqm/src/svn/openlaszlo/trunk/WEB-INF/lps/lfc/ on 2006-09-25 13:04:28 EDT
Summary: fix bug 2732, load checker in media loader leaves idle tasks running
New Features:
Bugs Fixed: LPP-2732 load tester delegate doesn't get removed
Technical Reviewer: adam (pending)
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
This bug doesn't happen in legals, so I back-ported the LzMediaLoader load checker code
from legals to trunk.
Tests:
test case in bug report
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@1916 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
53e205e71ec083a5257bd9a87a14fb8db99e3649
|
src/aerys/minko/render/resource/VertexBuffer3DResource.as
|
src/aerys/minko/render/resource/VertexBuffer3DResource.as
|
package aerys.minko.render.resource
{
import aerys.minko.ns.minko_stream;
import aerys.minko.type.Signal;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import flash.display3D.Context3D;
import flash.display3D.VertexBuffer3D;
/**
* VertexBuffer3DResource objects handle vertex buffers allocation
* and disposal using the Stage3D API.
*
* @author Jean-Marc Le Roux
*
*/
public final class VertexBuffer3DResource implements IResource
{
use namespace minko_stream;
private var _stream : VertexStream = null;
private var _update : Boolean = true;
private var _lengthChanged : Boolean = true;
private var _vertexBuffer : VertexBuffer3D = null;
private var _numVertices : uint = 0;
private var _disposed : Boolean = false;
private var _uploaded : Signal = new Signal('VertexBuffer3DRessource.uploaded');
public function get uploaded() : Signal
{
return _uploaded;
}
public function get numVertices() : uint
{
return _numVertices;
}
public function VertexBuffer3DResource(source : VertexStream)
{
_stream = source;
_stream.changed.add(vertexStreamChangedHandler);
}
private function vertexStreamChangedHandler(vertexStream : VertexStream) : void
{
_update = true;
_lengthChanged = vertexStream.numVertices != _numVertices;
}
public function getVertexBuffer3D(context : Context3DResource) : VertexBuffer3D
{
var update : Boolean = _update;
if (_disposed)
throw new Error('Unable to render a disposed buffer.');
if (_lengthChanged)
{
_lengthChanged = false;
_numVertices = _stream.numVertices;
if (_vertexBuffer)
_vertexBuffer.dispose();
_vertexBuffer = context.createVertexBuffer(
_numVertices,
_stream.format.numBytesPerVertex >>> 2
);
update = true;
}
if (_vertexBuffer != null && update)
{
_vertexBuffer.uploadFromByteArray(_stream._data, 0, 0, _numVertices);
_uploaded.execute(this);
_update = false;
if (!(_stream.usage & StreamUsage.READ) || _stream._localDispose)
_stream.disposeLocalData(false);
}
return _vertexBuffer;
}
public function dispose() : void
{
if (_vertexBuffer)
{
_vertexBuffer.dispose();
_vertexBuffer = null;
}
_disposed = true;
_stream = null;
_update = false;
_numVertices = 0;
}
}
}
|
package aerys.minko.render.resource
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.type.Signal;
import flash.display3D.Context3D;
import flash.display3D.VertexBuffer3D;
import flash.utils.ByteArray;
/**
* VertexBuffer3DResource objects handle vertex buffers allocation
* and disposal using the Stage3D API.
*
* @author Jean-Marc Le Roux
*
*/
public final class VertexBuffer3DResource implements IResource
{
use namespace minko_stream;
private var _stream : VertexStream = null;
private var _update : Boolean = true;
private var _lengthChanged : Boolean = true;
private var _vertexBuffer : VertexBuffer3D = null;
private var _numVertices : uint = 0;
private var _disposed : Boolean = false;
private var _uploaded : Signal = new Signal('VertexBuffer3DRessource.uploaded');
public function get uploaded() : Signal
{
return _uploaded;
}
public function get numVertices() : uint
{
return _numVertices;
}
public function VertexBuffer3DResource(source : VertexStream)
{
_stream = source;
_stream.changed.add(vertexStreamChangedHandler);
}
private function vertexStreamChangedHandler(vertexStream : VertexStream) : void
{
_update = true;
_lengthChanged = vertexStream.numVertices != _numVertices;
}
public function getVertexBuffer3D(context : Context3DResource) : VertexBuffer3D
{
var update : Boolean = _update;
if (_disposed)
throw new Error('Unable to render a disposed buffer.');
if (_lengthChanged)
{
_lengthChanged = false;
_numVertices = _stream.numVertices;
if (_vertexBuffer)
_vertexBuffer.dispose();
_vertexBuffer = context.createVertexBuffer(
_numVertices,
_stream.format.numBytesPerVertex >>> 2
);
update = true;
}
if (_vertexBuffer != null && update)
{
_vertexBuffer.uploadFromByteArray(_stream._data, 0, 0, _numVertices);
_uploaded.execute(this);
_update = false;
if (!(_stream.usage & StreamUsage.READ) || _stream._localDispose)
_stream.disposeLocalData(false);
}
return _vertexBuffer;
}
public function dispose() : void
{
if (_vertexBuffer)
{
_vertexBuffer.dispose();
_vertexBuffer = null;
}
_disposed = true;
_stream = null;
_update = false;
_numVertices = 0;
}
}
}
|
reorganize imports in VertexBuffer3DResource
|
reorganize imports in VertexBuffer3DResource
|
ActionScript
|
mit
|
aerys/minko-as3
|
03b13cd85fabace6c14128d5b80eb8644497cf89
|
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 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);
}
dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> {
const result:Vector.<Field> = new Vector.<Field>();
for each(var field:Field in type.fields) {
if (field.isStatic) {
continue;
}
if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) {
result.push(field);
}
}
return result;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
const clone:* = new (type.clazz)();
// Find all public writable fields in a hierarchy of a source object
// and assign their values to a clone object.
const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type);
var name:String;
for each(var field:Field in fieldsToClone) {
name = field.name;
clone[name] = source[name];
}
return clone;
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
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);
}
dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> {
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;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
const clone:* = new (type.clazz)();
// Find all public writable fields in a hierarchy of a source object
// and assign their values to a clone object.
const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type);
var name:String;
for each(var field:Field in fieldsToClone) {
name = field.name;
clone[name] = source[name];
}
return clone;
}
}
}
|
Optimize performance for finding of writable fields of Type.
|
Optimize performance for finding of writable fields of Type.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
468762a35ecf937508e0fd4876059f921f7d41e6
|
src/com/google/analytics/campaign/CampaignManager.as
|
src/com/google/analytics/campaign/CampaignManager.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.campaign
{
import com.google.analytics.core.Buffer;
import com.google.analytics.core.OrganicReferrer;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.VisualDebugMode;
import com.google.analytics.utils.Protocols;
import com.google.analytics.utils.URL;
import com.google.analytics.utils.Variables;
import com.google.analytics.v4.Configuration;
/**
* The CampaignManager class.
*/
public class CampaignManager
{
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _buffer:Buffer;
private var _domainHash:Number;
private var _referrer:String;
private var _timeStamp:Number;
/**
* Delimiter for campaign tracker.
*/
public static const trackingDelimiter:String = "|";
/**
* Creates a new CampaignManager instance.
*/
public function CampaignManager( config:Configuration, debug:DebugConfiguration, buffer:Buffer,
domainHash:Number, referrer:String, timeStamp:Number )
{
_config = config;
_debug = debug;
_buffer = buffer;
_domainHash = domainHash;
_referrer = referrer;
_timeStamp = timeStamp;
}
/**
* This method will return true if and only document referrer is invalid.
* Document referrer is considered to be invalid when it's empty (undefined,
* empty string, "-", or "0"), or it's not a valid URL (doesn't have protocol)
*
* @private
* @param {String} docRef Document referrer to be evaluated for validity.
*
* @return {Boolean} True if and only if document referrer is invalid.
*/
public static function isInvalidReferrer( referrer:String ):Boolean
{
if( (referrer == "") ||
(referrer == "-") ||
(referrer == "0") )
{
return true;
}
if( referrer.indexOf("://") > -1 )
{
var url:URL = new URL( referrer );
if( (url.protocol == Protocols.file) ||
(url.protocol == Protocols.none) )
{
return true;
}
}
return false;
}
/**
* Checks if the document referrer is from the google custom search engine.
* @private
* @return <code class="prettyprint">true</code> if the referrer is from google custom search engine.
*/
public static function isFromGoogleCSE( referrer:String, config:Configuration ):Boolean
{
var url:URL = new URL( referrer );
// verify that the referrer is google cse search query.
if( url.hostName.indexOf( config.google ) > -1 )
{
if( url.search.indexOf( config.googleSearchParam+"=" ) > -1 )
{
// check if this is google custom search engine.
if( url.path == "/"+config.googleCsePath )
{
return true;
}
}
}
return false;
}
/**
* Retrieves campaign information. If linker functionality is allowed, and
* the cookie parsed from search string is valid (hash matches), then load the
* __utmz value form search string, and write the value to cookie, then return
* "". Otherwise, attempt to retrieve __utmz value from cookie. Then
* retrieve campaign information from search string. If that fails, try
* organic campaigns next. If that fails, try referral campaigns next. If
* that fails, try direct campaigns next. If it still fails, return nothing.
* Finally, determine whether the campaign is duplicated. If the campaign is
* not duplicated, then write campaign information to cookie, and indicate
* there is a new campaign for gif hit. Else, just indicate this is a
* repeated click for campaign.
*
* @private
* @param {_gat.GA_Cookie_} inCookie GA_Cookie instance containing cookie
* values parsed in from URL (linker). This value should never be
* undefined.
* @param {Boolean} noSession Indicating whether a session has been
* initialized. If __utmb and/or __utmc cookies are not set, then session
* has either timed-out or havn't been initialized yet.
*
* @return {String} Gif hit key-value pair indicating wether this is a repeated
* click, or a brand new campaign for the visitor.
*/
public function getCampaignInformation( search:String, noSessionInformation:Boolean ):CampaignInfo
{
var campInfo:CampaignInfo = new CampaignInfo();
var campaignTracker:CampaignTracker;
var duplicateCampaign:Boolean = false;
var campNoOverride:Boolean = false;
var responseCount:int = 0;
/* Allow linker functionality, and cookie is parsed from URL, and the cookie
hash matches.
*/
if( _config.allowLinker && _buffer.isGenuine() )
{
if( !_buffer.hasUTMZ() )
{
return campInfo;
}
}
// retrieves tracker from search string
campaignTracker = getTrackerFromSearchString( search );
if( isValid( campaignTracker ) )
{
// check for no override flag in search string
campNoOverride = hasNoOverride( search );
// if no override is true, and there is a utmz value, then do nothing now
if( campNoOverride && !_buffer.hasUTMZ() )
{
return campInfo;
}
}
// Get organic campaign if there is no campaign tracker from search string.
if( !isValid( campaignTracker ) )
{
campaignTracker = getOrganicCampaign();
//If there is utmz cookie value, and organic keyword is being ignored, do nothing.
if( !_buffer.hasUTMZ() && isIgnoredKeyword( campaignTracker ) )
{
return campInfo;
}
}
/* Get referral campaign if there is no campaign tracker from search string
and organic campaign, and either utmb or utmc is missing (no session).
*/
if( !isValid( campaignTracker ) && noSessionInformation )
{
campaignTracker = getReferrerCampaign();
//If there is utmz cookie value, and referral domain is being ignored, do nothing
if( !_buffer.hasUTMZ() && isIgnoredReferral( campaignTracker ) )
{
return campInfo;
}
}
/* Get direct campaign if there is no campaign tracker from search string,
organic campaign, or referral campaign.
*/
if( !isValid( campaignTracker ) )
{
/* Only get direct campaign when there is no utmz cookie value, and there is
no session. (utmb or utmc is missing value)
*/
if( !_buffer.hasUTMZ() && noSessionInformation )
{
campaignTracker = getDirectCampaign();
}
}
//Give up (do nothing) if still cannot get campaign tracker.
if( !isValid( campaignTracker ) )
{
return campInfo;
}
//utmz cookie have value, check whether campaign is duplicated.
if( _buffer.hasUTMZ() && !_buffer.utmz.isEmpty() )
{
var oldTracker:CampaignTracker = new CampaignTracker();
oldTracker.fromTrackerString( _buffer.utmz.campaignTracking );
duplicateCampaign = ( oldTracker.toTrackerString() == campaignTracker.toTrackerString() );
responseCount = _buffer.utmz.responseCount;
}
/* Record as new campaign if and only if campaign is not duplicated, or there
is no session information.
*/
if( !duplicateCampaign || noSessionInformation )
{
var sessionCount:int = _buffer.utma.sessionCount;
responseCount++;
// if there is no session number, increment
if( sessionCount == 0 )
{
sessionCount = 1;
}
// construct utmz cookie
_buffer.utmz.domainHash = _domainHash;
_buffer.utmz.campaignCreation = _timeStamp;
_buffer.utmz.campaignSessions = sessionCount;
_buffer.utmz.responseCount = responseCount;
_buffer.utmz.campaignTracking = campaignTracker.toTrackerString();
_debug.info( _buffer.utmz.toString(), VisualDebugMode.geek );
// indicate new campaign
campInfo = new CampaignInfo( false, true );
}
else
{
// indicate repeated campaign
campInfo = new CampaignInfo( false, false );
}
return campInfo;
}
/**
* This method returns the organic campaign information.
* @private
* @return {_gat.GA_Campaign_.Tracker_} Returns undefined if referrer is not
* a matching organic campaign source. Otherwise, returns the campaign tracker object.
*/
public function getOrganicCampaign():CampaignTracker
{
var camp:CampaignTracker;
// if there is no referrer, or referrer is not a valid URL, or the referrer
// is google custom search engine, return an empty tracker
if( isInvalidReferrer( _referrer ) || isFromGoogleCSE( _referrer, _config ) )
{
return camp;
}
var ref:URL = new URL( _referrer );
var name:String = "";
if( ref.hostName != "" )
{
if( ref.hostName.indexOf( "." ) > -1 )
{
var tmp:Array = ref.hostName.split( "." );
switch( tmp.length)
{
case 2:
// case: http://domain.com
name = tmp[0];
break;
case 3:
//case: http://www.domain.com
name = tmp[1];
break;
}
}
}
// organic source match
if( _config.organic.match( name ) )
{
var currentOrganicSource:OrganicReferrer = _config.organic.getReferrerByName( name );
// extract keyword value from query string
var keyword:String = _config.organic.getKeywordValue( currentOrganicSource, ref.search );
camp = new CampaignTracker();
camp.source = currentOrganicSource.engine;
camp.name = "(organic)";
camp.medium = "organic";
camp.term = keyword;
}
return camp;
}
/**
* This method returns the referral campaign information.
*
* @private
* @return {_gat.GA_Campaign_.Tracker_} Returns nothing if there is no
* referrer. Otherwise, return referrer campaign tracker.
*/
public function getReferrerCampaign():CampaignTracker
{
var camp:CampaignTracker;
// if there is no referrer, or referrer is not a valid URL, or the referrer
// is google custom search engine, return an empty tracker
if( isInvalidReferrer( _referrer ) || isFromGoogleCSE( _referrer, _config ) )
{
return camp;
}
// get host name from referrer
var ref:URL = new URL( _referrer );
var hostname:String = ref.hostName;
var content:String = ref.path;
if( hostname.indexOf( "www." ) == 0 )
{
hostname = hostname.substr( 4 );
}
camp = new CampaignTracker();
camp.source = hostname;
camp.name = "(referral)";
camp.medium = "referral";
camp.content = content;
return camp;
}
/**
* Returns the direct campaign tracker string.
* @private
* @return {_gat.GA_Campaign_.Tracker_} Direct campaign tracker object.
*/
public function getDirectCampaign():CampaignTracker
{
var camp:CampaignTracker = new CampaignTracker();
camp.source = "(direct)";
camp.name = "(direct)";
camp.medium = "(none)";
return camp;
}
/**
* Indicates if the manager has no override with the search value.
*/
public function hasNoOverride( search:String ):Boolean
{
var key:CampaignKey = _config.campaignKey;
if( search == "" )
{
return false;
}
var variables:Variables = new Variables( search );
var value:String = "";
if( variables.hasOwnProperty( key.UCNO ) )
{
value = variables[ key.UCNO ];
switch( value )
{
case "1":
return true;
case "":
case "0":
default:
return false;
}
}
return false;
}
/**
* This method returns true if and only if campaignTracker is a valid organic
* campaign tracker (utmcmd=organic), and the keyword (utmctr) is contained in
* the ignore watch list (ORGANIC_IGNORE).
*
* @private
* @param {_gat.GA_Campaign_.Tracker_} campaignTracker Campaign tracker
* reference.
*
* @return {Boolean} Return true if and only if the campaign tracker is a valid
* organic campaign tracker, and the keyword is contained in the ignored
* watch list.
*/
public function isIgnoredKeyword( tracker:CampaignTracker ):Boolean
{
// organic campaign, try to match ignored keywords
if( tracker && (tracker.medium == "organic") )
{
return _config.organic.isIgnoredKeyword( tracker.term );
}
return false;
}
/**
* This method returns true if and only if campaignTracker is a valid
* referreal campaign tracker (utmcmd=referral), and the domain (utmcsr) is
* contained in the ignore watch list (REFERRAL_IGNORE).
*
* @private
* @param {String} campaignTracker String representation of the campaign
* tracker.
*
* @return {Boolean} Return true if and only if the campaign tracker is a
* valid referral campaign tracker, and the domain is contained in the
* ignored watch list.
*/
public function isIgnoredReferral( tracker:CampaignTracker ):Boolean
{
// referral campaign, try to match ignored domains
if( tracker && (tracker.medium == "referral") )
{
return _config.organic.isIgnoredReferral( tracker.source );
}
return false;
}
public function isValid( tracker:CampaignTracker ):Boolean
{
if( tracker && tracker.isValid() )
{
return true;
}
return false;
}
/**
* Retrieves campaign tracker from search string.
*
* @param {String} searchString Search string to retrieve campaign tracker from.
* @return {String} Return campaign tracker retrieved from search string.
*/
public function getTrackerFromSearchString( search:String ):CampaignTracker
{
var organicCampaign:CampaignTracker = getOrganicCampaign();
var camp:CampaignTracker = new CampaignTracker();
var key:CampaignKey = _config.campaignKey;
if( search == "" )
{
return camp;
}
var variables:Variables = new Variables( search );
//id
if( variables.hasOwnProperty( key.UCID ) )
{
camp.id = variables[ key.UCID ];
}
//source
if( variables.hasOwnProperty( key.UCSR ) )
{
camp.source = variables[ key.UCSR ];
}
//click id
if( variables.hasOwnProperty( key.UGCLID ) )
{
camp.clickId = variables[ key.UGCLID ];
}
//name
if( variables.hasOwnProperty( key.UCCN ) )
{
camp.name = variables[ key.UCCN ];
}
else
{
camp.name = "(not set)";
}
//medium
if( variables.hasOwnProperty( key.UCMD ) )
{
camp.medium = variables[ key.UCMD ];
}
else
{
camp.medium = "(not set)";
}
//term
if( variables.hasOwnProperty( key.UCTR ) )
{
camp.term = variables[ key.UCTR ];
}
else if( organicCampaign && organicCampaign.term != "" )
{
camp.term = organicCampaign.term;
}
//content
if( variables.hasOwnProperty( key.UCCT ) )
{
camp.content = variables[ key.UCCT ];
}
return camp;
}
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.campaign
{
import com.google.analytics.core.Buffer;
import com.google.analytics.core.OrganicReferrer;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.VisualDebugMode;
import com.google.analytics.utils.Variables;
import com.google.analytics.v4.Configuration;
import core.uri;
/**
* The CampaignManager class.
*/
public class CampaignManager
{
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _buffer:Buffer;
private var _domainHash:Number;
private var _referrer:String;
private var _timeStamp:Number;
/**
* Delimiter for campaign tracker.
*/
public static const trackingDelimiter:String = "|";
/**
* Creates a new CampaignManager instance.
*/
public function CampaignManager( config:Configuration, debug:DebugConfiguration, buffer:Buffer,
domainHash:Number, referrer:String, timeStamp:Number )
{
_config = config;
_debug = debug;
_buffer = buffer;
_domainHash = domainHash;
_referrer = referrer;
_timeStamp = timeStamp;
}
/**
* This method will return true if and only document referrer is invalid.
* Document referrer is considered to be invalid when it's empty (undefined,
* empty string, "-", or "0"), or it's not a valid URL (doesn't have protocol)
*
* @private
* @param {String} docRef Document referrer to be evaluated for validity.
*
* @return {Boolean} True if and only if document referrer is invalid.
*/
public static function isInvalidReferrer( referrer:String ):Boolean
{
if( (referrer == "") ||
(referrer == "-") ||
(referrer == "0") )
{
return true;
}
var url:uri = new uri( referrer );
if( (url.scheme == "file") ||
(url.scheme == "") )
{
return true;
}
return false;
}
/**
* Checks if the document referrer is from the google custom search engine.
* @private
* @return <code class="prettyprint">true</code> if the referrer is from google custom search engine.
*/
public static function isFromGoogleCSE( referrer:String, config:Configuration ):Boolean
{
var url:uri = new uri( referrer );
if( url.host.indexOf( config.google ) > -1 )
{
if( (url.path == "/"+config.googleCsePath ) &&
(url.query.indexOf( config.googleSearchParam+"=" ) > -1) )
{
return true;
}
}
return false;
}
/**
* Retrieves campaign information. If linker functionality is allowed, and
* the cookie parsed from search string is valid (hash matches), then load the
* __utmz value form search string, and write the value to cookie, then return
* "". Otherwise, attempt to retrieve __utmz value from cookie. Then
* retrieve campaign information from search string. If that fails, try
* organic campaigns next. If that fails, try referral campaigns next. If
* that fails, try direct campaigns next. If it still fails, return nothing.
* Finally, determine whether the campaign is duplicated. If the campaign is
* not duplicated, then write campaign information to cookie, and indicate
* there is a new campaign for gif hit. Else, just indicate this is a
* repeated click for campaign.
*
* @private
* @param {_gat.GA_Cookie_} inCookie GA_Cookie instance containing cookie
* values parsed in from URL (linker). This value should never be
* undefined.
* @param {Boolean} noSession Indicating whether a session has been
* initialized. If __utmb and/or __utmc cookies are not set, then session
* has either timed-out or havn't been initialized yet.
*
* @return {String} Gif hit key-value pair indicating wether this is a repeated
* click, or a brand new campaign for the visitor.
*/
public function getCampaignInformation( search:String, noSessionInformation:Boolean ):CampaignInfo
{
var campInfo:CampaignInfo = new CampaignInfo();
var campaignTracker:CampaignTracker;
var duplicateCampaign:Boolean = false;
var campNoOverride:Boolean = false;
var responseCount:int = 0;
/* Allow linker functionality, and cookie is parsed from URL, and the cookie
hash matches.
*/
if( _config.allowLinker && _buffer.isGenuine() )
{
if( !_buffer.hasUTMZ() )
{
return campInfo;
}
}
// retrieves tracker from search string
campaignTracker = getTrackerFromSearchString( search );
if( isValid( campaignTracker ) )
{
// check for no override flag in search string
campNoOverride = hasNoOverride( search );
// if no override is true, and there is a utmz value, then do nothing now
if( campNoOverride && !_buffer.hasUTMZ() )
{
return campInfo;
}
}
// Get organic campaign if there is no campaign tracker from search string.
if( !isValid( campaignTracker ) )
{
campaignTracker = getOrganicCampaign();
//If there is utmz cookie value, and organic keyword is being ignored, do nothing.
if( !_buffer.hasUTMZ() && isIgnoredKeyword( campaignTracker ) )
{
return campInfo;
}
}
/* Get referral campaign if there is no campaign tracker from search string
and organic campaign, and either utmb or utmc is missing (no session).
*/
if( !isValid( campaignTracker ) && noSessionInformation )
{
campaignTracker = getReferrerCampaign();
//If there is utmz cookie value, and referral domain is being ignored, do nothing
if( !_buffer.hasUTMZ() && isIgnoredReferral( campaignTracker ) )
{
return campInfo;
}
}
/* Get direct campaign if there is no campaign tracker from search string,
organic campaign, or referral campaign.
*/
if( !isValid( campaignTracker ) )
{
/* Only get direct campaign when there is no utmz cookie value, and there is
no session. (utmb or utmc is missing value)
*/
if( !_buffer.hasUTMZ() && noSessionInformation )
{
campaignTracker = getDirectCampaign();
}
}
//Give up (do nothing) if still cannot get campaign tracker.
if( !isValid( campaignTracker ) )
{
return campInfo;
}
//utmz cookie have value, check whether campaign is duplicated.
if( _buffer.hasUTMZ() && !_buffer.utmz.isEmpty() )
{
var oldTracker:CampaignTracker = new CampaignTracker();
oldTracker.fromTrackerString( _buffer.utmz.campaignTracking );
duplicateCampaign = ( oldTracker.toTrackerString() == campaignTracker.toTrackerString() );
responseCount = _buffer.utmz.responseCount;
}
/* Record as new campaign if and only if campaign is not duplicated, or there
is no session information.
*/
if( !duplicateCampaign || noSessionInformation )
{
var sessionCount:int = _buffer.utma.sessionCount;
responseCount++;
// if there is no session number, increment
if( sessionCount == 0 )
{
sessionCount = 1;
}
// construct utmz cookie
_buffer.utmz.domainHash = _domainHash;
_buffer.utmz.campaignCreation = _timeStamp;
_buffer.utmz.campaignSessions = sessionCount;
_buffer.utmz.responseCount = responseCount;
_buffer.utmz.campaignTracking = campaignTracker.toTrackerString();
_debug.info( _buffer.utmz.toString(), VisualDebugMode.geek );
// indicate new campaign
campInfo = new CampaignInfo( false, true );
}
else
{
// indicate repeated campaign
campInfo = new CampaignInfo( false, false );
}
return campInfo;
}
/**
* This method returns the organic campaign information.
* @private
* @return {_gat.GA_Campaign_.Tracker_} Returns undefined if referrer is not
* a matching organic campaign source. Otherwise, returns the campaign tracker object.
*/
public function getOrganicCampaign():CampaignTracker
{
var camp:CampaignTracker;
// if there is no referrer, or referrer is not a valid URL, or the referrer
// is google custom search engine, return an empty tracker
if( isInvalidReferrer( _referrer ) || isFromGoogleCSE( _referrer, _config ) )
{
return camp;
}
var ref:uri = new uri( _referrer );
var name:String;
if( (ref.host != "") && (ref.host.indexOf(".") > -1) )
{
var tmp:Array = ref.host.split( "." );
switch( tmp.length )
{
case 2:
name = tmp[0];
break;
case 3:
name = tmp[1];
}
}
// organic source match
if( _config.organic.match( name ) )
{
var currentOrganicSource:OrganicReferrer = _config.organic.getReferrerByName( name );
// extract keyword value from query string
var keyword:String = _config.organic.getKeywordValue( currentOrganicSource, ref.query );
camp = new CampaignTracker();
camp.source = currentOrganicSource.engine;
camp.name = "(organic)";
camp.medium = "organic";
camp.term = keyword;
}
return camp;
}
/**
* This method returns the referral campaign information.
*
* @private
* @return {_gat.GA_Campaign_.Tracker_} Returns nothing if there is no
* referrer. Otherwise, return referrer campaign tracker.
*/
public function getReferrerCampaign():CampaignTracker
{
var camp:CampaignTracker;
// if there is no referrer, or referrer is not a valid URL, or the referrer
// is google custom search engine, return an empty tracker
if( isInvalidReferrer( _referrer ) || isFromGoogleCSE( _referrer, _config ) )
{
return camp;
}
// get host name from referrer
var ref:uri = new uri( _referrer );
var hostname:String = ref.host;
var content:String = ref.path;
if( content == "" ) { content = "/"; } //fix empty path
if( hostname.indexOf( "www." ) == 0 )
{
hostname = hostname.substr( 4 );
}
camp = new CampaignTracker();
camp.source = hostname;
camp.name = "(referral)";
camp.medium = "referral";
camp.content = content;
return camp;
}
/**
* Returns the direct campaign tracker string.
* @private
* @return {_gat.GA_Campaign_.Tracker_} Direct campaign tracker object.
*/
public function getDirectCampaign():CampaignTracker
{
var camp:CampaignTracker = new CampaignTracker();
camp.source = "(direct)";
camp.name = "(direct)";
camp.medium = "(none)";
return camp;
}
/**
* Indicates if the manager has no override with the search value.
*/
public function hasNoOverride( search:String ):Boolean
{
var key:CampaignKey = _config.campaignKey;
if( search == "" )
{
return false;
}
var variables:Variables = new Variables( search );
var value:String = "";
if( variables.hasOwnProperty( key.UCNO ) )
{
value = variables[ key.UCNO ];
switch( value )
{
case "1":
return true;
case "":
case "0":
default:
return false;
}
}
return false;
}
/**
* This method returns true if and only if campaignTracker is a valid organic
* campaign tracker (utmcmd=organic), and the keyword (utmctr) is contained in
* the ignore watch list (ORGANIC_IGNORE).
*
* @private
* @param {_gat.GA_Campaign_.Tracker_} campaignTracker Campaign tracker
* reference.
*
* @return {Boolean} Return true if and only if the campaign tracker is a valid
* organic campaign tracker, and the keyword is contained in the ignored
* watch list.
*/
public function isIgnoredKeyword( tracker:CampaignTracker ):Boolean
{
// organic campaign, try to match ignored keywords
if( tracker && (tracker.medium == "organic") )
{
return _config.organic.isIgnoredKeyword( tracker.term );
}
return false;
}
/**
* This method returns true if and only if campaignTracker is a valid
* referreal campaign tracker (utmcmd=referral), and the domain (utmcsr) is
* contained in the ignore watch list (REFERRAL_IGNORE).
*
* @private
* @param {String} campaignTracker String representation of the campaign
* tracker.
*
* @return {Boolean} Return true if and only if the campaign tracker is a
* valid referral campaign tracker, and the domain is contained in the
* ignored watch list.
*/
public function isIgnoredReferral( tracker:CampaignTracker ):Boolean
{
// referral campaign, try to match ignored domains
if( tracker && (tracker.medium == "referral") )
{
return _config.organic.isIgnoredReferral( tracker.source );
}
return false;
}
public function isValid( tracker:CampaignTracker ):Boolean
{
if( tracker && tracker.isValid() )
{
return true;
}
return false;
}
/**
* Retrieves campaign tracker from search string.
*
* @param {String} searchString Search string to retrieve campaign tracker from.
* @return {String} Return campaign tracker retrieved from search string.
*/
public function getTrackerFromSearchString( search:String ):CampaignTracker
{
var organicCampaign:CampaignTracker = getOrganicCampaign();
var camp:CampaignTracker = new CampaignTracker();
var key:CampaignKey = _config.campaignKey;
if( search == "" )
{
return camp;
}
var variables:Variables = new Variables( search );
//id
if( variables.hasOwnProperty( key.UCID ) )
{
camp.id = variables[ key.UCID ];
}
//source
if( variables.hasOwnProperty( key.UCSR ) )
{
camp.source = variables[ key.UCSR ];
}
//click id
if( variables.hasOwnProperty( key.UGCLID ) )
{
camp.clickId = variables[ key.UGCLID ];
}
//name
if( variables.hasOwnProperty( key.UCCN ) )
{
camp.name = variables[ key.UCCN ];
}
else
{
camp.name = "(not set)";
}
//medium
if( variables.hasOwnProperty( key.UCMD ) )
{
camp.medium = variables[ key.UCMD ];
}
else
{
camp.medium = "(not set)";
}
//term
if( variables.hasOwnProperty( key.UCTR ) )
{
camp.term = variables[ key.UCTR ];
}
else if( organicCampaign && organicCampaign.term != "" )
{
camp.term = organicCampaign.term;
}
//content
if( variables.hasOwnProperty( key.UCCT ) )
{
camp.content = variables[ key.UCCT ];
}
return camp;
}
}
}
|
replace URL class by core.uri
|
replace URL class by core.uri
|
ActionScript
|
apache-2.0
|
dli-iclinic/gaforflash,mrthuanvn/gaforflash,mrthuanvn/gaforflash,Miyaru/gaforflash,jisobkim/gaforflash,Miyaru/gaforflash,dli-iclinic/gaforflash,drflash/gaforflash,soumavachakraborty/gaforflash,soumavachakraborty/gaforflash,Vigmar/gaforflash,jeremy-wischusen/gaforflash,DimaBaliakin/gaforflash,DimaBaliakin/gaforflash,drflash/gaforflash,jeremy-wischusen/gaforflash,jisobkim/gaforflash,Vigmar/gaforflash
|
5b756eedbbdb904b8734a717d2f871615e5ca7fd
|
src/tire/ui/WheelDataScreen.as
|
src/tire/ui/WheelDataScreen.as
|
/**
* User: booster
* Date: 05/03/15
* Time: 16:38
*/
package tire.ui {
import feathers.controls.Button;
import feathers.controls.Header;
import feathers.controls.List;
import feathers.controls.PanelScreen;
import feathers.controls.Slider;
import feathers.controls.ToggleSwitch;
import feathers.controls.renderers.DefaultListItemRenderer;
import feathers.controls.renderers.IListItemRenderer;
import feathers.data.ListCollection;
import feathers.layout.AnchorLayout;
import feathers.layout.AnchorLayoutData;
import starling.display.DisplayObject;
import starling.events.Event;
import tire.TirePhysics;
public class WheelDataScreen extends PanelScreen {
private var _wheelMassSlider:Slider;
private var _wheelRadiusSlider:Slider;
private var _wheelInertiaLocked:ToggleSwitch;
private var _wheelInertiaSlider:Slider;
private var _loadMassSlider:Slider;
private var _frontalAreaSlider:Slider;
private var _maxAccTorqueSlider:Slider;
private var _maxBrakingTorqueSlider:Slider;
private var _list:List;
private var _tirePhysics:TirePhysics;
public function get tirePhysics():TirePhysics { return _tirePhysics; }
public function set tirePhysics(value:TirePhysics):void { _tirePhysics = value; }
override protected function initialize():void {
super.initialize();
layout = new AnchorLayout();
title = "Wheel settings";
_wheelMassSlider = new Slider();
_wheelMassSlider.minimum = 5;
_wheelMassSlider.maximum = 30;
_wheelMassSlider.step = 0.1;
_wheelMassSlider.value = _tirePhysics.wheelMass;
_wheelMassSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.wheelMass = _wheelMassSlider.value;
if(_wheelInertiaLocked.isSelected)
_tirePhysics.validateInertia();
});
UiHelper.setupSlider(_wheelMassSlider);
_wheelRadiusSlider = new Slider();
_wheelRadiusSlider.minimum = 0.1;
_wheelRadiusSlider.maximum = 5;
_wheelRadiusSlider.step = 0.1;
_wheelRadiusSlider.value = tirePhysics.wheelRadius;
_wheelRadiusSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.wheelRadius = _wheelRadiusSlider.value;
if(_wheelInertiaLocked.isSelected)
_tirePhysics.validateInertia();
});
UiHelper.setupSlider(_wheelRadiusSlider);
_wheelInertiaSlider = new SecretSlider();
_wheelInertiaSlider.minimum = 0.1;
_wheelInertiaSlider.maximum = 50;
_wheelInertiaSlider.step = 0.1;
_wheelInertiaSlider.value = 20;
_wheelInertiaSlider.isEnabled = _tirePhysics.wheelInertiaLocked;
_wheelInertiaSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.wheelInertia = _wheelInertiaSlider.value;
});
UiHelper.setupSlider(_wheelInertiaSlider);
_wheelInertiaLocked = new ToggleSwitch();
_wheelInertiaLocked.onText = "Yes";
_wheelInertiaLocked.offText = "No";
_wheelInertiaLocked.isSelected = _tirePhysics.wheelInertiaLocked;
_wheelInertiaLocked.addEventListener(Event.CHANGE, function (e:Event):void {
var sliderItem:Object = null, sliderIndex:int = -1;
var count:int = _list.dataProvider.length;
for(var i:int = 0; i < count; ++i) {
var item:Object = _list.dataProvider.getItemAt(i);
if(item.accessory != _wheelInertiaSlider)
continue;
sliderItem = item;
sliderIndex = i;
break;
}
_tirePhysics.wheelInertiaLocked = _wheelInertiaLocked.isSelected;
if(! _tirePhysics.wheelInertiaLocked) {
sliderItem.enabled = false;
_tirePhysics.validateInertia();
}
else {
sliderItem.enabled = true;
_tirePhysics.wheelInertia = _wheelInertiaSlider.value;
}
_list.dataProvider.updateItemAt(sliderIndex);
});
_loadMassSlider = new Slider();
_loadMassSlider.minimum = 10;
_loadMassSlider.maximum = 1000;
_loadMassSlider.step = 10;
_loadMassSlider.value = _tirePhysics.carMass;
_loadMassSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.carMass = _loadMassSlider.value;
});
UiHelper.setupSlider(_loadMassSlider);
_frontalAreaSlider = new Slider();
_frontalAreaSlider.minimum = 0.5;
_frontalAreaSlider.maximum = 5;
_frontalAreaSlider.step = 0.1;
_frontalAreaSlider.value = _tirePhysics.frontalArea;
_frontalAreaSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.frontalArea = _frontalAreaSlider.value;
});
UiHelper.setupSlider(_frontalAreaSlider);
_maxAccTorqueSlider = new Slider();
_maxAccTorqueSlider.minimum = 100;
_maxAccTorqueSlider.maximum = 2000;
_maxAccTorqueSlider.step = 50;
_maxAccTorqueSlider.value = _tirePhysics.wheelTorque;
_maxAccTorqueSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.wheelTorque = _maxAccTorqueSlider.value;
});
UiHelper.setupSlider(_maxAccTorqueSlider);
_maxBrakingTorqueSlider = new Slider();
_maxBrakingTorqueSlider.minimum = 300;
_maxBrakingTorqueSlider.maximum = 6000;
_maxBrakingTorqueSlider.step = 50;
_maxBrakingTorqueSlider.value = _tirePhysics.brakeTorque;
_maxBrakingTorqueSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.brakeTorque = _maxBrakingTorqueSlider.value;
});
UiHelper.setupSlider(_maxBrakingTorqueSlider);
_list = new List();
_list.isSelectable = false;
_list.dataProvider = new ListCollection([
{ label : "Wheel mass", accessory : _wheelMassSlider },
{ label : "Wheel radius", accessory : _wheelRadiusSlider },
{ label : "Wheel inertia locked", accessory : _wheelInertiaLocked},
{ label : "Wheel inertia", accessory : _wheelInertiaSlider, enabled : _tirePhysics.wheelInertiaLocked},
{ label : "Load mass", accessory : _loadMassSlider},
{ label : "Frontal area", accessory : _frontalAreaSlider},
{ label : "Acc. torque", accessory : _maxAccTorqueSlider},
{ label : "Braking torque", accessory : _maxBrakingTorqueSlider},
]);
_list.layoutData = new AnchorLayoutData(0, 0, 0, 0);
_list.clipContent = false;
_list.autoHideBackground = true;
_list.itemRendererFactory = function():IListItemRenderer {
var renderer:DefaultListItemRenderer = new DefaultListItemRenderer();
renderer.itemHasEnabled = true;
return renderer;
};
// list.addEventListener(FeathersEventType.CREATION_COMPLETE, function(e:Event):void {
// _wheelInertiaSlider.isEnabled = _tirePhysics.wheelInertiaLocked;
// });
addChild(_list);
headerFactory = customHeaderFactory;
backButtonHandler = function ():void {
_tirePhysics.save();
dispatchEventWith(Event.COMPLETE);
};
}
private function customHeaderFactory():Header {
var header:Header = new Header();
var backButton:Button = new Button();
backButton.styleNameList.add(Button.ALTERNATE_NAME_BACK_BUTTON);
backButton.label = "Back";
backButton.addEventListener(Event.TRIGGERED, function(e:Event):void {
_tirePhysics.save();
dispatchEventWith(Event.COMPLETE);
});
header.leftItems = new <DisplayObject>[backButton];
return header;
}
}
}
import feathers.controls.Slider;
class SecretSlider extends Slider {
override public function set isEnabled(value:Boolean):void {
super.isEnabled = value;
}
override public function get isEnabled():Boolean {
return super.isEnabled;
}
}
|
/**
* User: booster
* Date: 05/03/15
* Time: 16:38
*/
package tire.ui {
import feathers.controls.Button;
import feathers.controls.Header;
import feathers.controls.List;
import feathers.controls.PanelScreen;
import feathers.controls.Slider;
import feathers.controls.ToggleSwitch;
import feathers.controls.renderers.DefaultListItemRenderer;
import feathers.controls.renderers.IListItemRenderer;
import feathers.data.ListCollection;
import feathers.layout.AnchorLayout;
import feathers.layout.AnchorLayoutData;
import starling.display.DisplayObject;
import starling.events.Event;
import tire.TirePhysics;
public class WheelDataScreen extends PanelScreen {
private var _wheelMassSlider:Slider;
private var _wheelRadiusSlider:Slider;
private var _wheelInertiaLocked:ToggleSwitch;
private var _wheelInertiaSlider:Slider;
private var _loadMassSlider:Slider;
private var _frontalAreaSlider:Slider;
private var _maxAccTorqueSlider:Slider;
private var _maxBrakingTorqueSlider:Slider;
private var _list:List;
private var _tirePhysics:TirePhysics;
public function get tirePhysics():TirePhysics { return _tirePhysics; }
public function set tirePhysics(value:TirePhysics):void { _tirePhysics = value; }
override protected function initialize():void {
super.initialize();
layout = new AnchorLayout();
title = "Wheel settings";
_wheelMassSlider = new Slider();
_wheelMassSlider.minimum = 5;
_wheelMassSlider.maximum = 30;
_wheelMassSlider.step = 0.1;
_wheelMassSlider.value = _tirePhysics.wheelMass;
_wheelMassSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.wheelMass = _wheelMassSlider.value;
if(_wheelInertiaLocked.isSelected)
_tirePhysics.validateInertia();
});
UiHelper.setupSlider(_wheelMassSlider);
_wheelRadiusSlider = new Slider();
_wheelRadiusSlider.minimum = 0.1;
_wheelRadiusSlider.maximum = 5;
_wheelRadiusSlider.step = 0.1;
_wheelRadiusSlider.value = tirePhysics.wheelRadius;
_wheelRadiusSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.wheelRadius = _wheelRadiusSlider.value;
if(_wheelInertiaLocked.isSelected)
_tirePhysics.validateInertia();
});
UiHelper.setupSlider(_wheelRadiusSlider);
_wheelInertiaSlider = new SecretSlider();
_wheelInertiaSlider.minimum = 0.1;
_wheelInertiaSlider.maximum = 50;
_wheelInertiaSlider.step = 0.1;
_wheelInertiaSlider.value = tirePhysics.wheelInertia;
_wheelInertiaSlider.isEnabled = _tirePhysics.wheelInertiaLocked;
_wheelInertiaSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.wheelInertia = _wheelInertiaSlider.value;
});
UiHelper.setupSlider(_wheelInertiaSlider);
_wheelInertiaLocked = new ToggleSwitch();
_wheelInertiaLocked.onText = "Yes";
_wheelInertiaLocked.offText = "No";
_wheelInertiaLocked.isSelected = _tirePhysics.wheelInertiaLocked;
_wheelInertiaLocked.addEventListener(Event.CHANGE, function (e:Event):void {
var sliderItem:Object = null, sliderIndex:int = -1;
var count:int = _list.dataProvider.length;
for(var i:int = 0; i < count; ++i) {
var item:Object = _list.dataProvider.getItemAt(i);
if(item.accessory != _wheelInertiaSlider)
continue;
sliderItem = item;
sliderIndex = i;
break;
}
_tirePhysics.wheelInertiaLocked = _wheelInertiaLocked.isSelected;
if(! _tirePhysics.wheelInertiaLocked) {
sliderItem.enabled = false;
_tirePhysics.validateInertia();
}
else {
sliderItem.enabled = true;
_tirePhysics.wheelInertia = _wheelInertiaSlider.value;
}
_list.dataProvider.updateItemAt(sliderIndex);
});
_loadMassSlider = new Slider();
_loadMassSlider.minimum = 10;
_loadMassSlider.maximum = 1000;
_loadMassSlider.step = 10;
_loadMassSlider.value = _tirePhysics.carMass;
_loadMassSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.carMass = _loadMassSlider.value;
});
UiHelper.setupSlider(_loadMassSlider);
_frontalAreaSlider = new Slider();
_frontalAreaSlider.minimum = 0.5;
_frontalAreaSlider.maximum = 5;
_frontalAreaSlider.step = 0.1;
_frontalAreaSlider.value = _tirePhysics.frontalArea;
_frontalAreaSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.frontalArea = _frontalAreaSlider.value;
});
UiHelper.setupSlider(_frontalAreaSlider);
_maxAccTorqueSlider = new Slider();
_maxAccTorqueSlider.minimum = 100;
_maxAccTorqueSlider.maximum = 2000;
_maxAccTorqueSlider.step = 50;
_maxAccTorqueSlider.value = _tirePhysics.wheelTorque;
_maxAccTorqueSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.wheelTorque = _maxAccTorqueSlider.value;
});
UiHelper.setupSlider(_maxAccTorqueSlider);
_maxBrakingTorqueSlider = new Slider();
_maxBrakingTorqueSlider.minimum = 300;
_maxBrakingTorqueSlider.maximum = 6000;
_maxBrakingTorqueSlider.step = 50;
_maxBrakingTorqueSlider.value = _tirePhysics.brakeTorque;
_maxBrakingTorqueSlider.addEventListener(Event.CHANGE, function (e:Event):void {
_tirePhysics.brakeTorque = _maxBrakingTorqueSlider.value;
});
UiHelper.setupSlider(_maxBrakingTorqueSlider);
_list = new List();
_list.isSelectable = false;
_list.dataProvider = new ListCollection([
{ label : "Wheel mass", accessory : _wheelMassSlider },
{ label : "Wheel radius", accessory : _wheelRadiusSlider },
{ label : "Wheel inertia locked", accessory : _wheelInertiaLocked},
{ label : "Wheel inertia", accessory : _wheelInertiaSlider, enabled : _tirePhysics.wheelInertiaLocked},
{ label : "Load mass", accessory : _loadMassSlider},
{ label : "Frontal area", accessory : _frontalAreaSlider},
{ label : "Acc. torque", accessory : _maxAccTorqueSlider},
{ label : "Braking torque", accessory : _maxBrakingTorqueSlider},
]);
_list.layoutData = new AnchorLayoutData(0, 0, 0, 0);
_list.clipContent = false;
_list.autoHideBackground = true;
_list.itemRendererFactory = function():IListItemRenderer {
var renderer:DefaultListItemRenderer = new DefaultListItemRenderer();
renderer.itemHasEnabled = true;
return renderer;
};
// list.addEventListener(FeathersEventType.CREATION_COMPLETE, function(e:Event):void {
// _wheelInertiaSlider.isEnabled = _tirePhysics.wheelInertiaLocked;
// });
addChild(_list);
headerFactory = customHeaderFactory;
backButtonHandler = function ():void {
_tirePhysics.save();
dispatchEventWith(Event.COMPLETE);
};
}
private function customHeaderFactory():Header {
var header:Header = new Header();
var backButton:Button = new Button();
backButton.styleNameList.add(Button.ALTERNATE_NAME_BACK_BUTTON);
backButton.label = "Back";
backButton.addEventListener(Event.TRIGGERED, function(e:Event):void {
_tirePhysics.save();
dispatchEventWith(Event.COMPLETE);
});
header.leftItems = new <DisplayObject>[backButton];
return header;
}
}
}
import feathers.controls.Slider;
class SecretSlider extends Slider {
override public function set isEnabled(value:Boolean):void {
super.isEnabled = value;
}
override public function get isEnabled():Boolean {
return super.isEnabled;
}
}
|
Initialize slider with current inertia instead of constant
|
Initialize slider with current inertia instead of constant
|
ActionScript
|
mit
|
b005t3r/TirePhysicsDemo,b005t3r/TirePhysicsDemo
|
02ba8882cc937cfa23812a84787cf6816ce20e7e
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
package org.arisgames.editor.util
{
public class AppConstants
{
//public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://davembp.local/server/services/aris/uploadhandler.php"; //davembp
// public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server/services/aris/uploadhandler.php"; //dev
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://www.arisgames.org/stagingserver1/services/aris/uploadHandler.php"; //staging
// public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp
// public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev
public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging
// Dynamic Events
public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged";
public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette";
public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded";
public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch";
public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected";
public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion";
public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem";
public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor";
public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker";
public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor";
public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor";
public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap";
public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange";
public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap";
public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap";
public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor";
public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor";
public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor";
public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR";
public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR";
public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS";
// Placemark Content
public static const CONTENTTYPE_PAGE:String = "Plaque";
public static const CONTENTTYPE_CHARACTER:String = "Character";
public static const CONTENTTYPE_ITEM:String = "Item";
public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group";
public static const CONTENTTYPE_PAGE_VAL:Number = 0;
public static const CONTENTTYPE_CHARACTER_VAL:Number = 1;
public static const CONTENTTYPE_ITEM_VAL:Number = 2;
public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3;
public static const CONTENTTYPE_PAGE_DATABASE:String = "Node";
public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc";
public static const CONTENTTYPE_ITEM_DATABASE:String = "Item";
public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30;
// Label Constants
public static const BUTTON_LOGIN:String = "Login!";
public static const BUTTON_REGISTER:String = "Register!";
public static const RADIO_FORGOTPASSWORD:String = "Forgot Password";
public static const RADIO_FORGOTUSERNAME:String = "Forgot Username";
// Media Types
public static const MEDIATYPE:String = "Media Types";
public static const MEDIATYPE_IMAGE:String = "Image";
public static const MEDIATYPE_AUDIO:String = "Audio";
public static const MEDIATYPE_VIDEO:String = "Video";
public static const MEDIATYPE_ICON:String = "Icon";
public static const MEDIATYPE_UPLOADNEW:String = "Upload New";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item";
// Requirement Types
public static const REQUIREMENTTYPE_LOCATION:String = "Location";
public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay";
public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete";
public static const REQUIREMENTTYPE_NODE:String = "Node";
// Requirement Options
public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM";
public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least qty of an Item";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than qty of an Item";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST:String = "Player Has Completed Quest";
public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND";
public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All";
public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR";
public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one";
// Defaults
public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1;
public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2;
public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3;
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
package org.arisgames.editor.util
{
public class AppConstants
{
//public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://davembp.local/server/services/aris/uploadhandler.php"; //davembp
// public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server/services/aris/uploadhandler.php"; //dev
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://www.arisgames.org/stagingserver1/services/aris/uploadHandler.php"; //staging
// public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp
// public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev
public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging
// Dynamic Events
public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged";
public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette";
public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded";
public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch";
public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected";
public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion";
public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem";
public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor";
public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker";
public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor";
public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor";
public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap";
public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange";
public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap";
public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap";
public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor";
public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor";
public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor";
public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR";
public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR";
public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS";
// Placemark Content
public static const CONTENTTYPE_PAGE:String = "Plaque";
public static const CONTENTTYPE_CHARACTER:String = "Character";
public static const CONTENTTYPE_ITEM:String = "Item";
public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group";
public static const CONTENTTYPE_PAGE_VAL:Number = 0;
public static const CONTENTTYPE_CHARACTER_VAL:Number = 1;
public static const CONTENTTYPE_ITEM_VAL:Number = 2;
public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3;
public static const CONTENTTYPE_PAGE_DATABASE:String = "Node";
public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc";
public static const CONTENTTYPE_ITEM_DATABASE:String = "Item";
public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30;
// Label Constants
public static const BUTTON_LOGIN:String = "Login!";
public static const BUTTON_REGISTER:String = "Register!";
public static const RADIO_FORGOTPASSWORD:String = "Forgot Password";
public static const RADIO_FORGOTUSERNAME:String = "Forgot Username";
// Media Types
public static const MEDIATYPE:String = "Media Types";
public static const MEDIATYPE_IMAGE:String = "Image";
public static const MEDIATYPE_AUDIO:String = "Audio";
public static const MEDIATYPE_VIDEO:String = "Video";
public static const MEDIATYPE_ICON:String = "Icon";
public static const MEDIATYPE_UPLOADNEW:String = "Upload New";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item";
// Requirement Types
public static const REQUIREMENTTYPE_LOCATION:String = "Location";
public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay";
public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete";
public static const REQUIREMENTTYPE_NODE:String = "Node";
// Requirement Options
public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM";
public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least Qty of an Item";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than Qty of an Item";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST:String = "Player Has Completed Quest";
public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND";
public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All";
public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR";
public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one";
// Defaults
public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1;
public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2;
public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3;
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
rename requirement to plaque/script
|
rename requirement to plaque/script
|
ActionScript
|
mit
|
fielddaylab/sifter-ios,fielddaylab/sifter-ios
|
225f361f8f2841b381cdbd172b526ff2e6133412
|
src/aerys/minko/render/resource/texture/TextureResource.as
|
src/aerys/minko/render/resource/texture/TextureResource.as
|
package aerys.minko.render.resource.texture
{
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.enum.SamplerFormat;
import flash.display.BitmapData;
import flash.display3D.Context3DTextureFormat;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Matrix;
import flash.utils.ByteArray;
/**
* @inheritdoc
* @author Jean-Marc Le Roux
*
*/
public class TextureResource implements ITextureResource
{
private static const MAX_SIZE : uint = 2048;
private static const TMP_MATRIX : Matrix = new Matrix();
private static const FORMAT_BGRA : String = Context3DTextureFormat.BGRA
private static const FORMAT_COMPRESSED : String = Context3DTextureFormat.COMPRESSED;
private static const FORMAT_COMPRESSED_ALPHA : String = Context3DTextureFormat.COMPRESSED_ALPHA;
private static const TEXTURE_FORMAT_TO_SAMPLER : Array = []
{
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_BGRA] = SamplerFormat.RGBA;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED] = SamplerFormat.COMPRESSED;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED_ALPHA] = SamplerFormat.COMPRESSED_ALPHA;
}
private var _texture : Texture = null;
private var _mipmap : Boolean = false;
private var _bitmapData : BitmapData = null;
private var _atf : ByteArray = null;
private var _atfFormat : uint = 0;
private var _format : String = FORMAT_BGRA;
private var _width : Number = 0;
private var _height : Number = 0;
private var _update : Boolean = false;
public function get format() : uint
{
return TEXTURE_FORMAT_TO_SAMPLER[_format];
}
public function get mipMapping() : Boolean
{
return _mipmap;
}
public function get width() : uint
{
return _width;
}
public function get height() : uint
{
return _height;
}
public function TextureResource(width : uint = 0,
height : uint = 0)
{
_width = width;
_height = height;
}
public function setContentFromBitmapData(bitmapData : BitmapData,
mipmap : Boolean,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = bitmapData.width;
var bitmapHeight : uint = bitmapData.height;
var w : int = 0;
var h : int = 0;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (w > MAX_SIZE)
w = MAX_SIZE;
if (h > MAX_SIZE)
h = MAX_SIZE;
if (_bitmapData == null || _bitmapData.width != w || _bitmapData.height != h)
_bitmapData = new BitmapData(w, h, bitmapData.transparent, 0);
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_bitmapData.draw(bitmapData, TMP_MATRIX);
}
else
{
_bitmapData.draw(bitmapData);
}
if (_texture
&& (mipmap != _mipmap
|| bitmapData.width != _width
|| bitmapData.height != _height))
{
_texture.dispose();
_texture = null;
}
_width = _bitmapData.width;
_height = _bitmapData.height;
_mipmap = mipmap;
_update = true;
}
public function setContentFromATF(atf : ByteArray) : void
{
_atf = atf;
_bitmapData = null;
_update = true;
atf.position = 6;
var formatByte : uint = atf.readUnsignedByte();
_atfFormat = formatByte & 7;
_width = 1 << atf.readUnsignedByte();
_height = 1 << atf.readUnsignedByte();
_mipmap = atf.readUnsignedByte() > 1;
atf.position = 0;
if (_atfFormat == 5)
_format = FORMAT_COMPRESSED_ALPHA;
else if (_atfFormat == 3)
_format = FORMAT_COMPRESSED;
}
public function getTexture(context : Context3DResource) : TextureBase
{
if (!_texture && _width && _height)
{
if (_texture)
_texture.dispose();
_texture = context.createTexture(
_width,
_height,
_format,
_bitmapData == null && _atf == null
);
}
if (_update)
{
_update = false;
uploadBitmapDataWithMipMaps();
}
_atf = null;
_bitmapData = null;
return _texture;
}
private function uploadBitmapDataWithMipMaps() : void
{
if (_bitmapData)
{
if (_mipmap)
{
var level : uint = 0;
var size : uint = _width > _height ? _width : _height;
var transparent : Boolean = _bitmapData.transparent;
var tmp : BitmapData = new BitmapData(size, size, transparent, 0);
var transform : Matrix = new Matrix();
while (size >= 1)
{
tmp.draw(_bitmapData, transform, null, null, null, true);
_texture.uploadFromBitmapData(tmp, level);
transform.scale(.5, .5);
level++;
size >>= 1;
if (tmp.transparent)
tmp.fillRect(tmp.rect, 0);
}
tmp.dispose();
}
else
{
_texture.uploadFromBitmapData(_bitmapData, 0);
}
_bitmapData.dispose();
}
else if (_atf)
{
_texture.uploadCompressedTextureFromByteArray(_atf, 0);
}
}
public function dispose() : void
{
if (_texture)
{
_texture.dispose();
_texture = null;
}
}
}
}
|
package aerys.minko.render.resource.texture
{
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.enum.SamplerFormat;
import flash.display.BitmapData;
import flash.display3D.Context3DTextureFormat;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Matrix;
import flash.utils.ByteArray;
/**
* @inheritdoc
* @author Jean-Marc Le Roux
*
*/
public class TextureResource implements ITextureResource
{
private static const MAX_SIZE : uint = 2048;
private static const TMP_MATRIX : Matrix = new Matrix();
private static const FORMAT_BGRA : String = Context3DTextureFormat.BGRA
private static const FORMAT_COMPRESSED : String = Context3DTextureFormat.COMPRESSED;
private static const FORMAT_COMPRESSED_ALPHA : String = Context3DTextureFormat.COMPRESSED_ALPHA;
private static const TEXTURE_FORMAT_TO_SAMPLER : Array = []
{
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_BGRA] = SamplerFormat.RGBA;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED] = SamplerFormat.COMPRESSED;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED_ALPHA] = SamplerFormat.COMPRESSED_ALPHA;
}
private var _texture : Texture = null;
private var _mipmap : Boolean = false;
private var _bitmapData : BitmapData = null;
private var _atf : ByteArray = null;
private var _atfFormat : uint = 0;
private var _format : String = FORMAT_BGRA;
private var _width : Number = 0;
private var _height : Number = 0;
private var _update : Boolean = false;
public function get format() : uint
{
return TEXTURE_FORMAT_TO_SAMPLER[_format];
}
public function get mipMapping() : Boolean
{
return _mipmap;
}
public function get width() : uint
{
return _width;
}
public function get height() : uint
{
return _height;
}
public function TextureResource(width : uint = 0,
height : uint = 0)
{
_width = width;
_height = height;
}
public function setContentFromBitmapData(bitmapData : BitmapData,
mipmap : Boolean,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = bitmapData.width;
var bitmapHeight : uint = bitmapData.height;
var w : int = 0;
var h : int = 0;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (w > MAX_SIZE)
w = MAX_SIZE;
if (h > MAX_SIZE)
h = MAX_SIZE;
if (_bitmapData == null || _bitmapData.width != w || _bitmapData.height != h)
_bitmapData = new BitmapData(w, h, bitmapData.transparent, 0);
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_bitmapData.draw(bitmapData, TMP_MATRIX);
}
else
{
_bitmapData.draw(bitmapData);
}
if (_texture
&& (mipmap != _mipmap
|| bitmapData.width != _width
|| bitmapData.height != _height))
{
_texture.dispose();
_texture = null;
}
_width = _bitmapData.width;
_height = _bitmapData.height;
_mipmap = mipmap;
_update = true;
}
public function setContentFromATF(atf : ByteArray) : void
{
_atf = atf;
_bitmapData = null;
_update = true;
var oldWidth : Number = _width;
var oldHeight : Number = _height;
var oldMipmap : Boolean = _mipmap;
atf.position = 6;
var formatByte : uint = atf.readUnsignedByte();
_atfFormat = formatByte & 7;
_width = 1 << atf.readUnsignedByte();
_height = 1 << atf.readUnsignedByte();
_mipmap = atf.readUnsignedByte() > 1;
atf.position = 0;
if (_atfFormat == 5)
_format = FORMAT_COMPRESSED_ALPHA;
else if (_atfFormat == 3)
_format = FORMAT_COMPRESSED;
if (_texture
&& (oldMipmap != _mipmap
|| oldWidth != _width
|| oldHeight != _height))
{
_texture.dispose();
_texture = null;
}
}
public function getTexture(context : Context3DResource) : TextureBase
{
if (!_texture && _width && _height)
{
if (_texture)
_texture.dispose();
_texture = context.createTexture(
_width,
_height,
_format,
_bitmapData == null && _atf == null
);
}
if (_update)
{
_update = false;
uploadBitmapDataWithMipMaps();
}
_atf = null;
_bitmapData = null;
return _texture;
}
private function uploadBitmapDataWithMipMaps() : void
{
if (_bitmapData)
{
if (_mipmap)
{
var level : uint = 0;
var size : uint = _width > _height ? _width : _height;
var transparent : Boolean = _bitmapData.transparent;
var tmp : BitmapData = new BitmapData(size, size, transparent, 0);
var transform : Matrix = new Matrix();
while (size >= 1)
{
tmp.draw(_bitmapData, transform, null, null, null, true);
_texture.uploadFromBitmapData(tmp, level);
transform.scale(.5, .5);
level++;
size >>= 1;
if (tmp.transparent)
tmp.fillRect(tmp.rect, 0);
}
tmp.dispose();
}
else
{
_texture.uploadFromBitmapData(_bitmapData, 0);
}
_bitmapData.dispose();
}
else if (_atf)
{
_texture.uploadCompressedTextureFromByteArray(_atf, 0);
}
}
public function dispose() : void
{
if (_texture)
{
_texture.dispose();
_texture = null;
}
}
}
}
|
Update src/aerys/minko/render/resource/texture/TextureResource.as
|
Update src/aerys/minko/render/resource/texture/TextureResource.as
fix bug Error #3679: Texture size does not match.
by analogy with setContentFromBitmapData
|
ActionScript
|
mit
|
aerys/minko-as3
|
d907b5474acccb9363899fb772694e123e9f9916
|
Game/Resources/elevatorScene/Scripts/LightsOutScript.as
|
Game/Resources/elevatorScene/Scripts/LightsOutScript.as
|
class LightsOutScript {
Hub @hub;
Entity @self;
LightsOutScript(Entity @entity){
@hub = Managers();
@self = @entity;
// Remove this if updates are not desired.
RegisterUpdate();
}
// Called by the engine for each frame.
void Update(float deltaTime) {
}
}
|
class LightsOutScript {
Hub @hub;
Entity @self;
LightsOutScript(Entity @entity){
@hub = Managers();
@self = @entity;
// Remove this if updates are not desired.
RegisterUpdate();
}
// Called by the engine for each frame.
void Update(float deltaTime) {
}
// Index goes first row 0 -> 4, second row 5 -> 9 etc.
void ButtonPress(int index) {
// Check if button is not pressed, in which case we invert its neighbors (check for out of bounds)
print("Pressed button nr `" + index + "`\n");
}
void b_0_0() {
ButtonPress(0);
}
void b_0_1() {
ButtonPress(1);
}
void b_0_2() {
ButtonPress(2);
}
void b_0_3() {
ButtonPress(3);
}
void b_0_4() {
ButtonPress(4);
}
void b_1_0() {
ButtonPress(5);
}
void b_1_1() {
ButtonPress(6);
}
void b_1_2() {
ButtonPress(7);
}
void b_1_3() {
ButtonPress(8);
}
void b_1_4() {
ButtonPress(9);
}
void b_2_0() {
ButtonPress(10);
}
void b_2_1() {
ButtonPress(11);
}
void b_2_2() {
ButtonPress(12);
}
void b_2_3() {
ButtonPress(13);
}
void b_2_4() {
ButtonPress(14);
}
void b_3_0() {
ButtonPress(15);
}
void b_3_1() {
ButtonPress(16);
}
void b_3_2() {
ButtonPress(17);
}
void b_3_3() {
ButtonPress(18);
}
void b_3_4() {
ButtonPress(19);
}
void b_4_0() {
ButtonPress(20);
}
void b_4_1() {
ButtonPress(21);
}
void b_4_2() {
ButtonPress(22);
}
void b_4_3() {
ButtonPress(23);
}
void b_4_4() {
ButtonPress(24);
}
}
|
Add methods on the lights out script that the button triggers will call. They all call a generic one that handles the game logic. I would prefer to just pass a parameter via the trigger but I don't know if we support that.
|
Add methods on the lights out script that the button triggers will call. They all call a generic one that handles the game logic. I would prefer to just pass a parameter via the trigger but I don't know if we support that.
|
ActionScript
|
mit
|
Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/LargeGameProjectEngine
|
df5f5ace27f6ae08a6db32efe4f17dd75aa2291c
|
src/as/com/threerings/presents/client/Communicator.as
|
src/as/com/threerings/presents/client/Communicator.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.presents.client {
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.TimerEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.Timer;
import com.threerings.util.Log;
import com.threerings.io.FrameAvailableEvent;
import com.threerings.io.FrameReader;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.presents.data.AuthCodes;
import com.threerings.presents.net.AuthRequest;
import com.threerings.presents.net.AuthResponse;
import com.threerings.presents.net.AuthResponseData;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.net.LogoffRequest;
import com.threerings.presents.net.UpstreamMessage;
import com.threerings.presents.net.ThrottleUpdatedMessage;
public class Communicator
{
public function Communicator (client :Client)
{
_client = client;
}
public function logon () :void
{
// create our input/output business
_outBuffer = new ByteArray();
_outBuffer.endian = Endian.BIG_ENDIAN;
_outStream = new ObjectOutputStream(_outBuffer);
_inStream = new ObjectInputStream();
_portIdx = 0;
logonToPort();
}
public function logoff () :void
{
if (_socket == null) {
return;
}
postMessage(new LogoffRequest());
}
public function postMessage (msg :UpstreamMessage) :void
{
if (_writer == null) {
log.warning("Posting message prior to opening socket", "msg", msg);
}
_outq.push(msg);
}
/**
* This method is strangely named, and it does two things which is
* bad style. Either log on to the next port, or save that the port
* we just logged on to was a good one.
*/
protected function logonToPort (logonWasSuccessful :Boolean = false) :Boolean
{
var ports :Array = _client.getPorts();
if (!logonWasSuccessful) {
if (_portIdx >= ports.length) {
return false;
}
if (_portIdx != 0) {
_client.reportLogonTribulations(new LogonError(AuthCodes.TRYING_NEXT_PORT, true));
removeListeners();
}
// create the socket and set up listeners
_socket = new Socket();
_socket.endian = Endian.BIG_ENDIAN;
_socket.addEventListener(Event.CONNECT, socketOpened);
_socket.addEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.addEventListener(Event.CLOSE, socketClosed);
_frameReader = new FrameReader(_socket);
_frameReader.addEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived);
}
var host :String = _client.getHostname();
var pport :int = ports[0];
var ppidx :int = Math.max(0, ports.indexOf(pport));
var port :int = (ports[(_portIdx + ppidx) % ports.length] as int);
if (logonWasSuccessful) {
_portIdx = -1; // indicate that we're no longer trying new ports
} else {
log.info("Connecting [host=" + host + ", port=" + port + "].");
_socket.connect(host, port);
}
return true;
}
protected function removeListeners () :void
{
_socket.removeEventListener(Event.CONNECT, socketOpened);
_socket.removeEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.removeEventListener(Event.CLOSE, socketClosed);
_frameReader.removeEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived);
}
protected function shutdown (logonError :Error) :void
{
if (_socket != null) {
if (_socket.connected) {
try {
_socket.close();
} catch (err :Error) {
log.warning("Error closing failed socket [error=" + err + "].");
}
}
removeListeners();
_socket = null;
_outStream = null;
_inStream = null;
_frameReader = null;
_outBuffer = null;
}
if (_writer != null) {
_writer.stop();
_writer = null;
}
_client.notifyObservers(ClientEvent.CLIENT_DID_LOGOFF, null);
_client.cleanup(logonError);
}
/**
* Sends all pending messages from our outgoing message queue. If we hit our throttle while
* sending, we stop and wait for the next time around when we'll try sending them again.
*/
protected function sendPendingMessages (event :TimerEvent) :void
{
while (_outq.length > 0) {
// if we've exceeded our throttle, stop for now
if (_client.getOutgoingMessageThrottle().throttleOp()) {
if (_tqsize != _outq.length) {
// only log when our outq size changes
_tqsize = _outq.length;
log.info("Throttling outgoing messages", "queue", _outq.length,
"throttle", _client.getOutgoingMessageThrottle());
}
return;
}
_tqsize = 0;
// grab the next message from the queue and send it
var msg :UpstreamMessage = (_outq.shift() as UpstreamMessage);
sendMessage(msg);
// if this was a logoff request, shutdown
if (msg is LogoffRequest) {
shutdown(null);
} else if (msg is ThrottleUpdatedMessage) {
_client.finalizeOutgoingMessageThrottle(ThrottleUpdatedMessage(msg).messagesPerSec);
}
}
}
/**
* Writes a single message to our outgoing socket.
*/
protected function sendMessage (msg :UpstreamMessage) :void
{
if (_outStream == null) {
log.warning("No socket, dropping msg [msg=" + msg + "].");
return;
}
// write the message (ends up in _outBuffer)
_outStream.writeObject(msg);
// Log.debug("outBuffer: " + StringUtil.unhexlate(_outBuffer));
// Frame it by writing the length, then the bytes.
// We add 4 to the length, because the length is of the entire frame
// including the 4 bytes used to encode the length!
_socket.writeInt(_outBuffer.length + 4);
_socket.writeBytes(_outBuffer);
_socket.flush();
// clean up the output buffer
_outBuffer.length = 0;
_outBuffer.position = 0;
// make a note of our most recent write time
updateWriteStamp();
}
/**
* Called when a frame of data from the server is ready to be decoded into a DownstreamMessage.
*/
protected function inputFrameReceived (event :FrameAvailableEvent) :void
{
// convert the frame data into a message from the server
var frameData :ByteArray = event.getFrameData();
_inStream.setSource(frameData);
var msg :DownstreamMessage;
try {
msg = (_inStream.readObject(DownstreamMessage) as DownstreamMessage);
} catch (e :Error) {
log.warning("Error processing downstream message: " + e);
log.logStackTrace(e);
return;
}
if (frameData.bytesAvailable > 0) {
log.warning("Beans! We didn't fully read a frame, is there a bug in some streaming " +
"code? [bytesLeftOver=" + frameData.bytesAvailable + ", msg=" + msg + "].");
}
if (_omgr != null) {
// if we're logged on, then just do the normal thing
_omgr.processMessage(msg);
return;
}
// otherwise, this would be the AuthResponse to our logon attempt
var rsp :AuthResponse = (msg as AuthResponse);
var data :AuthResponseData = rsp.getData();
if (data.code !== AuthResponseData.SUCCESS) {
shutdown(new Error(data.code));
return;
}
// logon success
_omgr = new ClientDObjectMgr(this, _client);
_client.setAuthResponseData(data);
}
/**
* Called when the connection to the server was successfully opened.
*/
protected function socketOpened (event :Event) :void
{
logonToPort(true);
// check for a logoff message
for each (var message :UpstreamMessage in _outq) {
if (message is LogoffRequest) {
// don't bother authing, just bail
log.info("Logged off prior to socket opening, shutting down");
shutdown(null);
return;
}
}
// kick off our writer thread now that we know we're ready to write
_writer = new Timer(1);
_writer.addEventListener(TimerEvent.TIMER, sendPendingMessages);
_writer.start();
// clear the queue, the server doesn't like anything sent prior to auth
_outq.length = 0;
// well that's great! let's logon
postMessage(new AuthRequest(_client.getCredentials(), _client.getVersion(),
_client.getBootGroups()));
}
/**
* Called when there is an io error with the socket.
*/
protected function socketError (event :IOErrorEvent) :void
{
// if we're trying ports, try the next one.
if (_portIdx != -1) {
_portIdx++;
if (logonToPort()) {
return;
}
}
// total failure
log.warning("Socket error: " + event, "target", event.target);
Log.dumpStack();
shutdown(new Error("Socket closed unexpectedly."));
}
/**
* Called when the connection to the server was closed.
*/
protected function socketClosed (event :Event) :void
{
log.info("Socket was closed: " + event);
_client.notifyObservers(ClientEvent.CLIENT_CONNECTION_FAILED);
shutdown(null);
}
/**
* Returns the time at which we last sent a packet to the server.
*/
internal function getLastWrite () :uint
{
return _lastWrite;
}
/**
* Makes a note of the time at which we last communicated with the server.
*/
internal function updateWriteStamp () :void
{
_lastWrite = flash.utils.getTimer();
}
protected var _client :Client;
protected var _omgr :ClientDObjectMgr;
protected var _outBuffer :ByteArray;
protected var _outStream :ObjectOutputStream;
protected var _inStream :ObjectInputStream;
protected var _frameReader :FrameReader;
protected var _socket :Socket;
protected var _lastWrite :uint;
protected var _outq :Array = new Array();
protected var _writer :Timer;
protected var _tqsize :int = 0;
protected const log :Log = Log.getLog(this);
/** The current port we'll try to connect to. */
protected var _portIdx :int = -1;
}
}
|
//
// $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.presents.client {
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.TimerEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.Timer;
import com.threerings.util.Log;
import com.threerings.io.FrameAvailableEvent;
import com.threerings.io.FrameReader;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.presents.data.AuthCodes;
import com.threerings.presents.net.AuthRequest;
import com.threerings.presents.net.AuthResponse;
import com.threerings.presents.net.AuthResponseData;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.net.LogoffRequest;
import com.threerings.presents.net.UpstreamMessage;
import com.threerings.presents.net.ThrottleUpdatedMessage;
public class Communicator
{
public function Communicator (client :Client)
{
_client = client;
}
public function logon () :void
{
// create our input/output business
_outBuffer = new ByteArray();
_outBuffer.endian = Endian.BIG_ENDIAN;
_outStream = new ObjectOutputStream(_outBuffer);
_inStream = new ObjectInputStream();
_portIdx = 0;
logonToPort();
}
public function logoff () :void
{
if (_socket == null) {
return;
}
postMessage(new LogoffRequest());
}
public function postMessage (msg :UpstreamMessage) :void
{
_outq.push(msg);
if (_writer != null) {
sendPendingMessages(null);
} else {
log.warning("Posting message prior to opening socket", "msg", msg);
}
}
/**
* This method is strangely named, and it does two things which is
* bad style. Either log on to the next port, or save that the port
* we just logged on to was a good one.
*/
protected function logonToPort (logonWasSuccessful :Boolean = false) :Boolean
{
var ports :Array = _client.getPorts();
if (!logonWasSuccessful) {
if (_portIdx >= ports.length) {
return false;
}
if (_portIdx != 0) {
_client.reportLogonTribulations(new LogonError(AuthCodes.TRYING_NEXT_PORT, true));
removeListeners();
}
// create the socket and set up listeners
_socket = new Socket();
_socket.endian = Endian.BIG_ENDIAN;
_socket.addEventListener(Event.CONNECT, socketOpened);
_socket.addEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.addEventListener(Event.CLOSE, socketClosed);
_frameReader = new FrameReader(_socket);
_frameReader.addEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived);
}
var host :String = _client.getHostname();
var pport :int = ports[0];
var ppidx :int = Math.max(0, ports.indexOf(pport));
var port :int = (ports[(_portIdx + ppidx) % ports.length] as int);
if (logonWasSuccessful) {
_portIdx = -1; // indicate that we're no longer trying new ports
} else {
log.info("Connecting [host=" + host + ", port=" + port + "].");
_socket.connect(host, port);
}
return true;
}
protected function removeListeners () :void
{
_socket.removeEventListener(Event.CONNECT, socketOpened);
_socket.removeEventListener(IOErrorEvent.IO_ERROR, socketError);
_socket.removeEventListener(Event.CLOSE, socketClosed);
_frameReader.removeEventListener(FrameAvailableEvent.FRAME_AVAILABLE, inputFrameReceived);
}
protected function shutdown (logonError :Error) :void
{
if (_socket != null) {
if (_socket.connected) {
try {
_socket.close();
} catch (err :Error) {
log.warning("Error closing failed socket [error=" + err + "].");
}
}
removeListeners();
_socket = null;
_outStream = null;
_inStream = null;
_frameReader = null;
_outBuffer = null;
}
if (_writer != null) {
_writer.stop();
_writer = null;
}
_client.notifyObservers(ClientEvent.CLIENT_DID_LOGOFF, null);
_client.cleanup(logonError);
}
/**
* Sends all pending messages from our outgoing message queue. If we hit our throttle while
* sending, we stop and wait for the next time around when we'll try sending them again.
*/
protected function sendPendingMessages (event :TimerEvent) :void
{
while (_outq.length > 0) {
// if we've exceeded our throttle, stop for now
if (_client.getOutgoingMessageThrottle().throttleOp()) {
if (!_notedThrottle) {
log.info("Throttling outgoing messages", "queue", _outq.length,
"throttle", _client.getOutgoingMessageThrottle());
_notedThrottle = true;
}
return;
}
_notedThrottle = false;
// grab the next message from the queue and send it
var msg :UpstreamMessage = (_outq.shift() as UpstreamMessage);
sendMessage(msg);
// if this was a logoff request, shutdown
if (msg is LogoffRequest) {
shutdown(null);
} else if (msg is ThrottleUpdatedMessage) {
_client.finalizeOutgoingMessageThrottle(ThrottleUpdatedMessage(msg).messagesPerSec);
}
}
}
/**
* Writes a single message to our outgoing socket.
*/
protected function sendMessage (msg :UpstreamMessage) :void
{
if (_outStream == null) {
log.warning("No socket, dropping msg [msg=" + msg + "].");
return;
}
// write the message (ends up in _outBuffer)
_outStream.writeObject(msg);
// Log.debug("outBuffer: " + StringUtil.unhexlate(_outBuffer));
// Frame it by writing the length, then the bytes.
// We add 4 to the length, because the length is of the entire frame
// including the 4 bytes used to encode the length!
_socket.writeInt(_outBuffer.length + 4);
_socket.writeBytes(_outBuffer);
_socket.flush();
// clean up the output buffer
_outBuffer.length = 0;
_outBuffer.position = 0;
// make a note of our most recent write time
updateWriteStamp();
}
/**
* Called when a frame of data from the server is ready to be decoded into a DownstreamMessage.
*/
protected function inputFrameReceived (event :FrameAvailableEvent) :void
{
// convert the frame data into a message from the server
var frameData :ByteArray = event.getFrameData();
_inStream.setSource(frameData);
var msg :DownstreamMessage;
try {
msg = (_inStream.readObject(DownstreamMessage) as DownstreamMessage);
} catch (e :Error) {
log.warning("Error processing downstream message: " + e);
log.logStackTrace(e);
return;
}
if (frameData.bytesAvailable > 0) {
log.warning("Beans! We didn't fully read a frame, is there a bug in some streaming " +
"code? [bytesLeftOver=" + frameData.bytesAvailable + ", msg=" + msg + "].");
}
if (_omgr != null) {
// if we're logged on, then just do the normal thing
_omgr.processMessage(msg);
return;
}
// otherwise, this would be the AuthResponse to our logon attempt
var rsp :AuthResponse = (msg as AuthResponse);
var data :AuthResponseData = rsp.getData();
if (data.code !== AuthResponseData.SUCCESS) {
shutdown(new Error(data.code));
return;
}
// logon success
_omgr = new ClientDObjectMgr(this, _client);
_client.setAuthResponseData(data);
}
/**
* Called when the connection to the server was successfully opened.
*/
protected function socketOpened (event :Event) :void
{
logonToPort(true);
// check for a logoff message
for each (var message :UpstreamMessage in _outq) {
if (message is LogoffRequest) {
// don't bother authing, just bail
log.info("Logged off prior to socket opening, shutting down");
shutdown(null);
return;
}
}
// kick off our writer thread now that we know we're ready to write
_writer = new Timer(1);
_writer.addEventListener(TimerEvent.TIMER, sendPendingMessages);
_writer.start();
// clear the queue, the server doesn't like anything sent prior to auth
_outq.length = 0;
// well that's great! let's logon
postMessage(new AuthRequest(_client.getCredentials(), _client.getVersion(),
_client.getBootGroups()));
}
/**
* Called when there is an io error with the socket.
*/
protected function socketError (event :IOErrorEvent) :void
{
// if we're trying ports, try the next one.
if (_portIdx != -1) {
_portIdx++;
if (logonToPort()) {
return;
}
}
// total failure
log.warning("Socket error: " + event, "target", event.target);
Log.dumpStack();
shutdown(new Error("Socket closed unexpectedly."));
}
/**
* Called when the connection to the server was closed.
*/
protected function socketClosed (event :Event) :void
{
log.info("Socket was closed: " + event);
_client.notifyObservers(ClientEvent.CLIENT_CONNECTION_FAILED);
shutdown(null);
}
/**
* Returns the time at which we last sent a packet to the server.
*/
internal function getLastWrite () :uint
{
return _lastWrite;
}
/**
* Makes a note of the time at which we last communicated with the server.
*/
internal function updateWriteStamp () :void
{
_lastWrite = flash.utils.getTimer();
}
protected var _client :Client;
protected var _omgr :ClientDObjectMgr;
protected var _outBuffer :ByteArray;
protected var _outStream :ObjectOutputStream;
protected var _inStream :ObjectInputStream;
protected var _frameReader :FrameReader;
protected var _socket :Socket;
protected var _lastWrite :uint;
protected var _outq :Array = new Array();
protected var _writer :Timer;
protected var _notedThrottle :Boolean = false;
protected const log :Log = Log.getLog(this);
/** The current port we'll try to connect to. */
protected var _portIdx :int = -1;
}
}
|
Cut client latency by attempting to send upstream messages immediately.
|
Cut client latency by attempting to send upstream messages
immediately.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5592 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
e2d49ec3dfa440aaf7d0a6ab4c5019317083c6c7
|
src/net/manaca/application/config/ConfigFileHelper.as
|
src/net/manaca/application/config/ConfigFileHelper.as
|
package net.manaca.application.config
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import mx.core.ByteArrayAsset;
import net.manaca.errors.IllegalArgumentError;
public class ConfigFileHelper extends EventDispatcher
{
public function ConfigFileHelper()
{
super();
}
public var configXML:XML;
public function init(config:*):void
{
if(config is Class)
{
var clZ:Class = config as Class;
var ba:ByteArrayAsset = ByteArrayAsset(new clZ()) ;
configXML = new XML(ba.readUTFBytes(ba.length));
}
else if(config is XML)
{
configXML = XML(config);
}
else if(config is String && String(config).length > 0)
{
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE,
loaderConfig_completeHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR,
loaderConfig_errorHandler);
loader.load(new URLRequest(String(config)));
trace("start loading config file : " + config);
return;
}
else
{
throw new IllegalArgumentError("invalid config argument:" + config);
}
dispatchEvent(new Event(Event.COMPLETE));
}
//==========================================================================
// Event handlers
//==========================================================================
private function loaderConfig_completeHandler(event:Event):void
{
try
{
configXML = XML(event.target.data);
}
catch(error:Error)
{
trace("Config file error : " + error.toString());
}
dispatchEvent(new Event(Event.COMPLETE));
}
private function loaderConfig_errorHandler(event:IOErrorEvent):void
{
throw new IllegalArgumentError("load config file error:" + event);
}
}
}
|
package net.manaca.application.config
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import mx.core.ByteArrayAsset;
import net.manaca.errors.IllegalArgumentError;
/**
*
* @author sean
*
*/
public class ConfigFileHelper extends EventDispatcher
{
//==========================================================================
// Constructor
//==========================================================================
/**
* 构造一个<code>ConfigFileHelper</code>实例.
*
*/
public function ConfigFileHelper()
{
super();
}
//==========================================================================
// Properties
//==========================================================================
public var configXML:XML;
//==========================================================================
// Methods
//==========================================================================
public function init(config:*):void
{
if(config is Class)
{
var clZ:Class = config as Class;
var ba:ByteArrayAsset = ByteArrayAsset(new clZ()) ;
configXML = new XML(ba.readUTFBytes(ba.length));
}
else if(config is XML)
{
configXML = XML(config);
}
else if(config is String && String(config).length > 0)
{
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE,
loaderConfig_completeHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR,
loaderConfig_errorHandler);
loader.load(new URLRequest(String(config)));
trace("start loading config file : " + config);
return;
}
else
{
throw new IllegalArgumentError("invalid config argument:" + config);
}
dispatchEvent(new Event(Event.COMPLETE));
}
//==========================================================================
// Event handlers
//==========================================================================
private function loaderConfig_completeHandler(event:Event):void
{
try
{
configXML = XML(event.target.data);
}
catch(error:Error)
{
trace("Config file error : " + error.toString());
}
dispatchEvent(new Event(Event.COMPLETE));
}
private function loaderConfig_errorHandler(event:IOErrorEvent):void
{
throw new IllegalArgumentError("load config file error:" + event);
}
}
}
|
update ConfigFileHelper docs
|
update ConfigFileHelper docs
|
ActionScript
|
mit
|
wersling/manaca,wersling/manaca
|
31263962657413bdaa6a5c8f6f3ee818f824fac4
|
lib/src_linux/com/amanitadesign/steam/FRESteamWorks.as
|
lib/src_linux/com/amanitadesign/steam/FRESteamWorks.as
|
/*
* FRESteamWorks.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero>
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam {
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.StatusEvent;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class FRESteamWorks extends EventDispatcher {
[Event(name="steam_response", type="com.amanitadesign.steam.SteamEvent")]
private static const PATH:String = "NativeApps/Linux/APIWrapper";
private var _file:File;
private var _process:NativeProcess;
private var _tm:int;
private var _init:Boolean = false;
private var _error:Boolean = false;
private var _crashHandlerArgs:Array = null;
public var isReady:Boolean = false;
private static const AIRSteam_Init:int = 0;
private static const AIRSteam_RunCallbacks:int = 1;
private static const AIRSteam_RequestStats:int = 2;
private static const AIRSteam_SetAchievement:int = 3;
private static const AIRSteam_ClearAchievement:int = 4;
private static const AIRSteam_IsAchievement:int = 5;
private static const AIRSteam_GetStatInt:int = 6;
private static const AIRSteam_GetStatFloat:int = 7;
private static const AIRSteam_SetStatInt:int = 8;
private static const AIRSteam_SetStatFloat:int = 9;
private static const AIRSteam_StoreStats:int = 10;
private static const AIRSteam_ResetAllStats:int = 11;
private static const AIRSteam_GetFileCount:int = 12;
private static const AIRSteam_GetFileSize:int = 13;
private static const AIRSteam_FileExists:int = 14;
private static const AIRSteam_FileWrite:int = 15;
private static const AIRSteam_FileRead:int = 16;
private static const AIRSteam_FileDelete:int = 17;
private static const AIRSteam_IsCloudEnabledForApp:int = 18;
private static const AIRSteam_SetCloudEnabledForApp:int = 19;
private static const AIRSteam_GetUserID:int = 20;
private static const AIRSteam_GetPersonaName:int = 21;
private static const AIRSteam_UseCrashHandler:int = 22;
public function FRESteamWorks (target:IEventDispatcher = null) {
_file = File.applicationDirectory.resolvePath(PATH);
_process = new NativeProcess();
_process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, eventDispatched);
_process.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, errorCallback);
super(target);
}
public function dispose():void {
if(_process.running) {
_process.closeInput();
_process.exit();
}
clearInterval(_tm);
isReady = false;
}
private function startProcess():void {
var startupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
startupInfo.executable = _file;
_process.start(startupInfo);
}
public function init():Boolean {
if(!_file.exists) return false;
try {
startProcess();
} catch(e:Error) {
return false;
}
// try to start the process a second time, but this time ignoring any
// potential errors since we will definitely get one about the process
// already running. this seems to give the runtime enough time to check
// for any stderr output of the initial call to startProcess(), so that we
// now can check if it actually started: in case it couldn't one of the
// libraries it depends on, it prints something like "error while loading
// shared libraries" to stderr, which we're trying to detect here.
// process.running is unreliable, in that it's always set to true,
// even if the process didn't start at all
try {
startProcess();
} catch(e:Error) {
// no-op
}
if(!_process.running) return false;
if(_process.standardError.bytesAvailable > 0) return false;
// initialization seems to be successful
_init = true;
// UseCrashHandler has to be called before Steam_Init
// but we still have to make sure the process is actually running
// so FRESteamWorks#useCrashHandler just sets _crashHandlerArgs
// and the actual call is handled here
if(_crashHandlerArgs) {
if(!callWrapper(AIRSteam_UseCrashHandler, _crashHandlerArgs))
return false;
}
if(!callWrapper(AIRSteam_Init)) return false;
isReady = readBoolResponse();
if(isReady) _tm = setInterval(runCallbacks, 100);
return isReady;
}
private function errorCallback(e:IOErrorEvent):void {
_error = true;
// the process doesn't accept our input anymore, so just stop it
clearInterval(_tm);
if(_process.running) {
try {
_process.closeInput();
} catch(e:*) {
// no-op
}
_process.exit();
}
}
private function callWrapper(funcName:int, params:Array = null):Boolean {
_error = false;
if(!_process.running) return false;
var stdin:IDataOutput = _process.standardInput;
stdin.writeUTFBytes(funcName + "\n");
if (params) {
for(var i:int = 0; i < params.length; ++i) {
if(params[i] is ByteArray) {
var length:uint = params[i].length;
// length + 1 for the added newline
stdin.writeUTFBytes(String(length + 1) + "\n");
stdin.writeBytes(params[i]);
stdin.writeUTFBytes("\n");
} else {
stdin.writeUTFBytes(String(params[i]) + "\n");
}
}
}
return !_error;
}
private function waitForData(output:IDataInput):uint {
while(!output.bytesAvailable) {
// wait
if(!_process.running) return 0;
}
return output.bytesAvailable;
}
private function readBoolResponse():Boolean {
if(!_process.running) return false;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(1);
return (response == "t");
}
private function readIntResponse():int {
if(!_process.running) return 0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail);
return parseInt(response, 10);
}
private function readFloatResponse():Number {
if(!_process.running) return 0.0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return parseFloat(response);
}
private function readStringResponse():String {
if(!_process.running) return "";
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var data:String = stdout.readUTFBytes(avail)
var newline:uint = data.indexOf("\n");
var buf:String = data.substring(newline);
var length:uint = parseInt(data.substring(0, newline), 10);
while(buf.length < length) {
avail = waitForData(stdout);
buf += stdout.readUTFBytes(avail);
}
return buf;
}
private function eventDispatched(e:ProgressEvent):void {
var stderr:IDataInput = _process.standardError;
var avail:uint = stderr.bytesAvailable;
var data:String = stderr.readUTFBytes(avail);
var pattern:RegExp = /__event__<(\d+),(\d+)>/g;
var result:Object;
while((result = pattern.exec(data))) {
var req_type:int = new int(result[1]);
var response:int = new int(result[2]);
var steamEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response);
dispatchEvent(steamEvent);
}
}
public function requestStats():Boolean {
if(!callWrapper(AIRSteam_RequestStats)) return false;
return readBoolResponse();
}
public function runCallbacks():Boolean {
if(!callWrapper(AIRSteam_RunCallbacks)) return false;
return true;
}
public function getUserID():String {
if(!callWrapper(AIRSteam_GetUserID)) return "";
return readStringResponse();
}
public function getPersonaName():String {
if(!callWrapper(AIRSteam_GetPersonaName)) return "";
return readStringResponse();
}
public function useCrashHandler(appID:uint, version:String, date:String, time:String):Boolean {
// only allow calls before SteamAPI_Init was called
if(_init) return false;
_crashHandlerArgs = [appID, version, date, time];
return true;
}
public function setAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_SetAchievement, [id])) return false;
return readBoolResponse();
}
public function clearAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_ClearAchievement, [id])) return false;
return readBoolResponse();
}
public function isAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_IsAchievement, [id])) return false;
return readBoolResponse();
}
public function getStatInt(id:String):int {
if(!callWrapper(AIRSteam_GetStatInt, [id])) return 0;
return readIntResponse();
}
public function getStatFloat(id:String):Number {
if(!callWrapper(AIRSteam_GetStatFloat, [id])) return 0.0;
return readFloatResponse();
}
public function setStatInt(id:String, value:int):Boolean {
if(!callWrapper(AIRSteam_SetStatInt, [id, value])) return false;
return readBoolResponse();
}
public function setStatFloat(id:String, value:Number):Boolean {
if(!callWrapper(AIRSteam_SetStatFloat, [id, value])) return false;
return readBoolResponse();
}
public function storeStats():Boolean {
if(!callWrapper(AIRSteam_StoreStats)) return false;
return readBoolResponse();
}
public function resetAllStats(bAchievementsToo:Boolean):Boolean {
if(!callWrapper(AIRSteam_ResetAllStats, [bAchievementsToo])) return false;
return readBoolResponse();
}
public function getFileCount():int {
if(!callWrapper(AIRSteam_GetFileCount)) return 0;
return readIntResponse();
}
public function getFileSize(fileName:String):int {
if(!callWrapper(AIRSteam_GetFileSize, [fileName])) return 0;
return readIntResponse();
}
public function fileExists(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileExists, [fileName])) return false;
return readBoolResponse();
}
public function fileWrite(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileWrite, [fileName, data])) return false;
return readBoolResponse();
}
public function fileRead(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileRead, [fileName])) return false;
var success:Boolean = readBoolResponse();
if(success) {
var content:String = readStringResponse();
data.writeUTFBytes(content);
data.position = 0;
}
return success;
}
public function fileDelete(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileDelete, [fileName])) return false;
return readBoolResponse();
}
public function isCloudEnabledForApp():Boolean {
if(!callWrapper(AIRSteam_IsCloudEnabledForApp)) return false;
return readBoolResponse();
}
public function setCloudEnabledForApp(enabled:Boolean):Boolean {
if(!callWrapper(AIRSteam_SetCloudEnabledForApp, [enabled])) return false;
return readBoolResponse();
}
}
}
|
/*
* FRESteamWorks.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero>
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam {
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.StatusEvent;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import flash.utils.clearInterval;
import flash.utils.setInterval;
public class FRESteamWorks extends EventDispatcher {
[Event(name="steam_response", type="com.amanitadesign.steam.SteamEvent")]
private static const PATH:String = "NativeApps/Linux/APIWrapper";
private var _file:File;
private var _process:NativeProcess;
private var _tm:int;
private var _init:Boolean = false;
private var _error:Boolean = false;
private var _crashHandlerArgs:Array = null;
public var isReady:Boolean = false;
private static const AIRSteam_Init:int = 0;
private static const AIRSteam_RunCallbacks:int = 1;
private static const AIRSteam_RequestStats:int = 2;
private static const AIRSteam_SetAchievement:int = 3;
private static const AIRSteam_ClearAchievement:int = 4;
private static const AIRSteam_IsAchievement:int = 5;
private static const AIRSteam_GetStatInt:int = 6;
private static const AIRSteam_GetStatFloat:int = 7;
private static const AIRSteam_SetStatInt:int = 8;
private static const AIRSteam_SetStatFloat:int = 9;
private static const AIRSteam_StoreStats:int = 10;
private static const AIRSteam_ResetAllStats:int = 11;
private static const AIRSteam_GetFileCount:int = 12;
private static const AIRSteam_GetFileSize:int = 13;
private static const AIRSteam_FileExists:int = 14;
private static const AIRSteam_FileWrite:int = 15;
private static const AIRSteam_FileRead:int = 16;
private static const AIRSteam_FileDelete:int = 17;
private static const AIRSteam_IsCloudEnabledForApp:int = 18;
private static const AIRSteam_SetCloudEnabledForApp:int = 19;
private static const AIRSteam_GetUserID:int = 20;
private static const AIRSteam_GetPersonaName:int = 21;
private static const AIRSteam_UseCrashHandler:int = 22;
public function FRESteamWorks (target:IEventDispatcher = null) {
_file = File.applicationDirectory.resolvePath(PATH);
_process = new NativeProcess();
_process.addEventListener(ProgressEvent.STANDARD_ERROR_DATA, eventDispatched);
_process.addEventListener(IOErrorEvent.STANDARD_INPUT_IO_ERROR, errorCallback);
super(target);
}
public function dispose():void {
if(_process.running) {
_process.closeInput();
_process.exit();
}
clearInterval(_tm);
isReady = false;
}
private function startProcess():void {
var startupInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
startupInfo.executable = _file;
_process.start(startupInfo);
}
public function init():Boolean {
if(!_file.exists) return false;
try {
startProcess();
} catch(e:Error) {
return false;
}
// try to start the process a second time, but this time ignoring any
// potential errors since we will definitely get one about the process
// already running. this seems to give the runtime enough time to check
// for any stderr output of the initial call to startProcess(), so that we
// now can check if it actually started: in case it couldn't one of the
// libraries it depends on, it prints something like "error while loading
// shared libraries" to stderr, which we're trying to detect here.
// process.running is unreliable, in that it's always set to true,
// even if the process didn't start at all
try {
startProcess();
} catch(e:Error) {
// no-op
}
if(!_process.running) return false;
if(_process.standardError.bytesAvailable > 0) return false;
// initialization seems to be successful
_init = true;
// UseCrashHandler has to be called before Steam_Init
// but we still have to make sure the process is actually running
// so FRESteamWorks#useCrashHandler just sets _crashHandlerArgs
// and the actual call is handled here
if(_crashHandlerArgs) {
if(!callWrapper(AIRSteam_UseCrashHandler, _crashHandlerArgs))
return false;
}
if(!callWrapper(AIRSteam_Init)) return false;
isReady = readBoolResponse();
if(isReady) _tm = setInterval(runCallbacks, 100);
return isReady;
}
private function errorCallback(e:IOErrorEvent):void {
_error = true;
// the process doesn't accept our input anymore, so just stop it
clearInterval(_tm);
if(_process.running) {
try {
_process.closeInput();
} catch(e:*) {
// no-op
}
_process.exit();
}
}
private function callWrapper(funcName:int, params:Array = null):Boolean {
_error = false;
if(!_process.running) return false;
var stdin:IDataOutput = _process.standardInput;
stdin.writeUTFBytes(funcName + "\n");
if (params) {
for(var i:int = 0; i < params.length; ++i) {
if(params[i] is ByteArray) {
var length:uint = params[i].length;
// length + 1 for the added newline
stdin.writeUTFBytes(String(length + 1) + "\n");
stdin.writeBytes(params[i]);
stdin.writeUTFBytes("\n");
} else {
stdin.writeUTFBytes(String(params[i]) + "\n");
}
}
}
return !_error;
}
private function waitForData(output:IDataInput):uint {
while(!output.bytesAvailable) {
// wait
if(!_process.running) return 0;
}
return output.bytesAvailable;
}
private function readBoolResponse():Boolean {
if(!_process.running) return false;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(1);
return (response == "t");
}
private function readIntResponse():int {
if(!_process.running) return 0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail);
return parseInt(response, 10);
}
private function readFloatResponse():Number {
if(!_process.running) return 0.0;
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var response:String = stdout.readUTFBytes(avail)
return parseFloat(response);
}
private function readStringResponse():String {
if(!_process.running) return "";
var stdout:IDataInput = _process.standardOutput;
var avail:uint = waitForData(stdout);
var data:String = stdout.readUTFBytes(avail)
var newline:uint = data.indexOf("\n");
var buf:String = data.substring(newline + 1);
var length:uint = parseInt(data.substring(0, newline), 10);
while(buf.length < length) {
avail = waitForData(stdout);
buf += stdout.readUTFBytes(avail);
}
return buf;
}
private function eventDispatched(e:ProgressEvent):void {
var stderr:IDataInput = _process.standardError;
var avail:uint = stderr.bytesAvailable;
var data:String = stderr.readUTFBytes(avail);
var pattern:RegExp = /__event__<(\d+),(\d+)>/g;
var result:Object;
while((result = pattern.exec(data))) {
var req_type:int = new int(result[1]);
var response:int = new int(result[2]);
var steamEvent:SteamEvent = new SteamEvent(SteamEvent.STEAM_RESPONSE, req_type, response);
dispatchEvent(steamEvent);
}
}
public function requestStats():Boolean {
if(!callWrapper(AIRSteam_RequestStats)) return false;
return readBoolResponse();
}
public function runCallbacks():Boolean {
if(!callWrapper(AIRSteam_RunCallbacks)) return false;
return true;
}
public function getUserID():String {
if(!callWrapper(AIRSteam_GetUserID)) return "";
return readStringResponse();
}
public function getPersonaName():String {
if(!callWrapper(AIRSteam_GetPersonaName)) return "";
return readStringResponse();
}
public function useCrashHandler(appID:uint, version:String, date:String, time:String):Boolean {
// only allow calls before SteamAPI_Init was called
if(_init) return false;
_crashHandlerArgs = [appID, version, date, time];
return true;
}
public function setAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_SetAchievement, [id])) return false;
return readBoolResponse();
}
public function clearAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_ClearAchievement, [id])) return false;
return readBoolResponse();
}
public function isAchievement(id:String):Boolean {
if(!callWrapper(AIRSteam_IsAchievement, [id])) return false;
return readBoolResponse();
}
public function getStatInt(id:String):int {
if(!callWrapper(AIRSteam_GetStatInt, [id])) return 0;
return readIntResponse();
}
public function getStatFloat(id:String):Number {
if(!callWrapper(AIRSteam_GetStatFloat, [id])) return 0.0;
return readFloatResponse();
}
public function setStatInt(id:String, value:int):Boolean {
if(!callWrapper(AIRSteam_SetStatInt, [id, value])) return false;
return readBoolResponse();
}
public function setStatFloat(id:String, value:Number):Boolean {
if(!callWrapper(AIRSteam_SetStatFloat, [id, value])) return false;
return readBoolResponse();
}
public function storeStats():Boolean {
if(!callWrapper(AIRSteam_StoreStats)) return false;
return readBoolResponse();
}
public function resetAllStats(bAchievementsToo:Boolean):Boolean {
if(!callWrapper(AIRSteam_ResetAllStats, [bAchievementsToo])) return false;
return readBoolResponse();
}
public function getFileCount():int {
if(!callWrapper(AIRSteam_GetFileCount)) return 0;
return readIntResponse();
}
public function getFileSize(fileName:String):int {
if(!callWrapper(AIRSteam_GetFileSize, [fileName])) return 0;
return readIntResponse();
}
public function fileExists(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileExists, [fileName])) return false;
return readBoolResponse();
}
public function fileWrite(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileWrite, [fileName, data])) return false;
return readBoolResponse();
}
public function fileRead(fileName:String, data:ByteArray):Boolean {
if(!callWrapper(AIRSteam_FileRead, [fileName])) return false;
var success:Boolean = readBoolResponse();
if(success) {
var content:String = readStringResponse();
data.writeUTFBytes(content);
data.position = 0;
}
return success;
}
public function fileDelete(fileName:String):Boolean {
if(!callWrapper(AIRSteam_FileDelete, [fileName])) return false;
return readBoolResponse();
}
public function isCloudEnabledForApp():Boolean {
if(!callWrapper(AIRSteam_IsCloudEnabledForApp)) return false;
return readBoolResponse();
}
public function setCloudEnabledForApp(enabled:Boolean):Boolean {
if(!callWrapper(AIRSteam_SetCloudEnabledForApp, [enabled])) return false;
return readBoolResponse();
}
}
}
|
Fix off-by-one
|
[swc] Fix off-by-one
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
6795646f9a38db0ff873364b0d99c6dce2033190
|
src/com/pivotshare/hls/loader/FragmentDemuxedStream.as
|
src/com/pivotshare/hls/loader/FragmentDemuxedStream.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package com.pivotshare.hls.loader {
import flash.display.DisplayObject;
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flash.utils.Timer;
import com.pivotshare.hls.loader.FragmentStream;
import org.mangui.hls.constant.HLSLoaderTypes;
import org.mangui.hls.demux.Demuxer;
import org.mangui.hls.demux.DemuxHelper;
import org.mangui.hls.demux.ID3Tag;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSLoadMetrics;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.HLS;
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.model.Fragment;
import org.mangui.hls.model.FragmentData;
import org.mangui.hls.utils.AES;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
import org.mangui.hls.utils.Hex;
}
/**
* HLS Fragment Demuxed Streamer.
* Tries to parallel URLStream design pattern, but is incomplete.
*
* This class encapsulates Demuxing, but in an inefficient way. This is not
* meant to be performant for sequential Fragments in play.
*
* @class FragmentDemuxedStream
* @extends EventDispatcher
* @author HGPA
*/
public class FragmentDemuxedStream extends EventDispatcher {
/*
* DisplayObject needed by AES decrypter.
*/
private var _displayObject : DisplayObject;
/*
* Fragment being loaded.
*/
private var _fragment : Fragment;
/*
* URLStream used to download current Fragment.
*/
private var _fragmentStream : FragmentStream;
/*
* Metrics for this stream.
*/
private var _metrics : HLSLoadMetrics;
/*
* Demuxer needed for this Fragment.
*/
private var _demux : Demuxer;
/*
* Options for streaming and demuxing.
*/
private var _options : Object;
//
//
//
// Public Methods
//
//
//
/**
* Create a FragmentStream.
*
* This constructor takes a reference to main DisplayObject, e.g. stage,
* necessary for AES decryption control.
*
* TODO: It would be more appropriate to create a factory that itself
* takes the DisplayObject (or a more flexible version of AES).
*
* @constructor
* @param {DisplayObject} displayObject
*/
public function FragmentDemuxedStream(displayObject : DisplayObject) : void {
_displayObject = displayObject;
_fragment = null;
_fragmentStream = null;
_metrics = null;
_demux = null;
_options = new Object();
};
/*
* Return FragmentData of Fragment currently being downloaded.
* Of immediate interest is the `bytes` field.
*
* @method getFragment
* @return {Fragment}
*/
public function getFragment() : Fragment {
return _fragment;
}
/*
* Close the stream.
*
* @method close
*/
public function close() : void {
if (_fragmentStream) {
_fragmentStream.close();
}
if (_demux) {
_demux.cancel();
_demux = null;
}
}
/**
* Load a Fragment.
*
* This class/methods DOES NOT user reference of parameter. Instead it
* clones the Fragment and manipulates this internally.
*
* @method load
* @param {Fragment} fragment - Fragment with details (cloned)
* @param {ByteArray} key - Encryption Key
* @return {HLSLoadMetrics}
*/
public function load(fragment : Fragment, key : ByteArray, options : Object) : HLSLoadMetrics {
_options = options;
// Clone Fragment, with new initilizations of deep fields
// Passing around references is what is causing problems.
// FragmentData is initialized as part of construction
_fragment = new Fragment(
fragment.url,
fragment.duration,
fragment.level,
fragment.seqnum,
fragment.start_time,
fragment.continuity,
fragment.program_date,
fragment.decrypt_url,
fragment.decrypt_iv, // We need this reference
fragment.byterange_start_offset,
fragment.byterange_end_offset,
new Vector.<String>()
)
_fragmentStream = new FragmentStream(_displayObject);
_fragmentStream.addEventListener(IOErrorEvent.IO_ERROR, onStreamError);
_fragmentStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onStreamError);
_fragmentStream.addEventListener(ProgressEvent.PROGRESS, onStreamProgress);
_fragmentStream.addEventListener(Event.COMPLETE, onStreamComplete);
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug("FragmentDemuxedStream#load: " + fragmentString);
}
_metrics = _fragmentStream.load(_fragment, key);
return _metrics;
}
//
//
//
// FragmentStream Event Listeners
//
//
//
/**
*
* @method onFragmentStreamProgress
* @param {ProgressEvent} evt
*/
private function onStreamProgress(evt : ProgressEvent) : void {
_fragment = _fragmentStream.getFragment();
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug2("FragmentDemuxedStream#onStreamProgress: " +
fragmentString + " Progress - " + evt.bytesLoaded + " of " + evt.bytesTotal);
Log.debug2("FragmentDemuxedStream#onStreamProgress: " +
fragmentString + " Fragment status - bytes.position / bytes.length / bytesLoaded " +
_fragment.data.bytes.position + " / " +
_fragment.data.bytes.length + " / " +
_fragment.data.bytesLoaded);
}
// If we are loading a partial Fragment then only parse when it has
// completed loading to desired portion (See onFragmentStreamComplete)
/*
if (fragment.byterange_start_offset != -1) {
return;
}
*/
// START PARSING METRICS
if (_metrics.parsing_begin_time == 0) {
_metrics.parsing_begin_time = getTimer();
}
// Demuxer has not yet been initialized as this is probably first
// call to onFragmentStreamProgress, but demuxer may also be/remain
// null due to unknown Fragment type. Probe is synchronous.
if (_demux == null) {
// It is possible we have run onFragmentStreamProgress before
// without having sufficient data to probe
//bytes.position = bytes.length;
//bytes.writeBytes(byteArray);
//byteArray = bytes;
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug2("FragmentDemuxedStream#onStreamProgress: Need a Demuxer for " + fragmentString);
}
_demux = DemuxHelper.probe(
_fragment.data.bytes,
null,
_onDemuxAudioTrackRequested,
_onDemuxProgress,
_onDemuxComplete,
_onDemuxVideoMetadata,
_onDemuxID3TagFound,
false
);
}
if (_demux) {
// Demuxer expects the ByteArray delta
var byteArray : ByteArray = new ByteArray();
_fragment.data.bytes.readBytes(byteArray, 0, _fragment.data.bytes.length - _fragment.data.bytes.position);
byteArray.position = 0;
_demux.append(byteArray);
}
}
/**
* Called when FragmentStream completes.
*
* @method onStreamComplete
* @param {Event} evt
*/
private function onStreamComplete(evt : Event) : void {
// If demuxer is still null, then the Fragment type was invalid
if (_demux == null) {
CONFIG::LOGGING {
Log.error("FragmentDemuxedStream#onStreamComplete: unknown fragment type");
_fragment.data.bytes.position = 0;
var bytes2 : ByteArray = new ByteArray();
_fragment.data.bytes.readBytes(bytes2, 0, 512);
Log.debug2("FragmentDemuxedStream#onStreamComplete: frag dump(512 bytes)");
Log.debug2(Hex.fromArray(bytes2));
}
var err : ErrorEvent = new ErrorEvent(
ErrorEvent.ERROR,
false,
false,
"Unknown Fragment Type"
);
dispatchEvent(err);
} else {
_demux.notifycomplete();
}
}
/**
* Called when FragmentStream has errored.
*
* @method onStreamError
* @param {ProgressEvent} evt
*/
private function onStreamError(evt : ErrorEvent) : void {
CONFIG::LOGGING {
Log.error("FragmentDemuxedStream#onStreamError: " + evt.text);
}
dispatchEvent(evt);
}
//
//
//
// Demuxer Callbacks
//
//
//
/**
* Called when Demuxer needs to know which AudioTrack to parse for.
*
* FIXME: This callback simply returns the first audio track!
* We need to pass this class the appropriate callback propogated from
* UI layer. Yuck.
*
* @method _onDemuxAudioTrackRequested
* @param {Vector<AudioTrack} audioTrackList - List of AudioTracks
* @return {AudioTrack} - AudioTrack to parse
*/
private function _onDemuxAudioTrackRequested(audioTrackList : Vector.<AudioTrack>) : AudioTrack {
if (audioTrackList.length > 0) {
return audioTrackList[0];
} else {
return null;
}
}
/**
* Called when Demuxer parsed portion of Fragment.
*
* @method _onDemuxProgress
* @param {Vector<FLVTag} tags
*/
private function _onDemuxProgress(tags : Vector.<FLVTag>) : void {
CONFIG::LOGGING {
Log.debug2("FragmentDemuxedStream#_onDemuxProgress");
}
_fragment.data.appendTags(tags);
// TODO: Options to parse only portion of Fragment
// FIXME: bytesLoaded and bytesTotal represent stats of the current
// FragmentStream, not Demuxer, which is no longer bytes-relative.
// What should we define here?
var progressEvent : ProgressEvent = new ProgressEvent(
ProgressEvent.PROGRESS,
false,
false,
_fragment.data.bytes.length, // bytesLoaded
_fragment.data.bytesTotal // bytesTotal
);
dispatchEvent(progressEvent);
};
/**
* Called when Demuxer has finished parsing Fragment.
*
* @method _onDemuxComplete
*/
private function _onDemuxComplete() : void {
CONFIG::LOGGING {
Log.debug2("FragmentDemuxedStream#_onDemuxComplete");
}
_metrics.parsing_end_time = getTimer();
var completeEvent : Event = new ProgressEvent(Event.COMPLETE);
dispatchEvent(completeEvent);
};
/**
* Called when Video metadata is parsed.
*
* Specifically, when Sequence Parameter Set (SPS) is found.
*
* @method _onDemuxVideoMetadata
* @param {uint} width
* @param {uint} height
*/
private function _onDemuxVideoMetadata(width : uint, height : uint) : void {
if (_fragment.data.video_width == 0) {
CONFIG::LOGGING {
Log.debug2("FragmentDemuxedStream#_onDemuxVideoMetadata: AVC SPS = " + width + "x" + height);
}
_fragment.data.video_width = width;
_fragment.data.video_height = height;
}
}
/**
* Called when ID3 tags are found.
*
* @method _onDemuxID3TagFound
* @param {Vector.<ID3Tag>} id3_tags - ID3 Tags
*/
private function _onDemuxID3TagFound(id3_tags : Vector.<ID3Tag>) : void {
_fragment.data.id3_tags = id3_tags;
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package com.pivotshare.hls.loader {
import flash.display.DisplayObject;
import flash.events.*;
import flash.net.*;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flash.utils.Timer;
import com.pivotshare.hls.loader.FragmentStream;
import org.mangui.hls.constant.HLSLoaderTypes;
import org.mangui.hls.demux.Demuxer;
import org.mangui.hls.demux.DemuxHelper;
import org.mangui.hls.demux.ID3Tag;
import org.mangui.hls.event.HLSError;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.event.HLSLoadMetrics;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.HLS;
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.model.Fragment;
import org.mangui.hls.model.FragmentData;
import org.mangui.hls.utils.AES;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
import org.mangui.hls.utils.Hex;
}
/**
* HLS Fragment Demuxed Streamer.
* Tries to parallel URLStream design pattern, but is incomplete.
*
* This class encapsulates Demuxing, but in an inefficient way. This is not
* meant to be performant for sequential Fragments in play.
*
* @class FragmentDemuxedStream
* @extends EventDispatcher
* @author HGPA
*/
public class FragmentDemuxedStream extends EventDispatcher {
/*
* DisplayObject needed by AES decrypter.
*/
private var _displayObject : DisplayObject;
/*
* Fragment being loaded.
*/
private var _fragment : Fragment;
/*
* URLStream used to download current Fragment.
*/
private var _fragmentStream : FragmentStream;
/*
* Metrics for this stream.
*/
private var _metrics : HLSLoadMetrics;
/*
* Demuxer needed for this Fragment.
*/
private var _demux : Demuxer;
/*
* Options for streaming and demuxing.
*/
private var _options : Object;
/*
* Whether Fragment has completed processing (loading/demuxing).
*/
private var _complete : Boolean;
//
//
//
// Public Methods
//
//
//
/**
* Create a FragmentStream.
*
* This constructor takes a reference to main DisplayObject, e.g. stage,
* necessary for AES decryption control.
*
* TODO: It would be more appropriate to create a factory that itself
* takes the DisplayObject (or a more flexible version of AES).
*
* @constructor
* @param {DisplayObject} displayObject
*/
public function FragmentDemuxedStream(displayObject : DisplayObject) : void {
_displayObject = displayObject;
_fragment = null;
_fragmentStream = null;
_metrics = null;
_demux = null;
_options = new Object();
_complete = false;
};
/*
* Return FragmentData of Fragment currently being downloaded.
* Of immediate interest is the `bytes` field.
*
* @method getFragment
* @return {Fragment}
*/
public function getFragment() : Fragment {
return _fragment;
}
/**
* Whether Fragment has completed loading and demuxing.
*
* @method complete
* @return {Boolean}
*/
public function get complete():Boolean {
return _complete;
}
/*
* Close the stream.
*
* @method close
*/
public function close() : void {
if (_fragmentStream) {
_fragmentStream.close();
}
if (_demux) {
_demux.cancel();
_demux = null;
}
}
/**
* Load a Fragment.
*
* This class/methods DOES NOT user reference of parameter. Instead it
* clones the Fragment and manipulates this internally.
*
* @method load
* @param {Fragment} fragment - Fragment with details (cloned)
* @param {ByteArray} key - Encryption Key
* @return {HLSLoadMetrics}
*/
public function load(fragment : Fragment, key : ByteArray, options : Object) : HLSLoadMetrics {
_options = options;
// Clone Fragment, with new initilizations of deep fields
// Passing around references is what is causing problems.
// FragmentData is initialized as part of construction
_fragment = new Fragment(
fragment.url,
fragment.duration,
fragment.level,
fragment.seqnum,
fragment.start_time,
fragment.continuity,
fragment.program_date,
fragment.decrypt_url,
fragment.decrypt_iv, // We need this reference
fragment.byterange_start_offset,
fragment.byterange_end_offset,
new Vector.<String>()
)
_fragmentStream = new FragmentStream(_displayObject);
_fragmentStream.addEventListener(IOErrorEvent.IO_ERROR, onStreamError);
_fragmentStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onStreamError);
_fragmentStream.addEventListener(ProgressEvent.PROGRESS, onStreamProgress);
_fragmentStream.addEventListener(Event.COMPLETE, onStreamComplete);
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug("FragmentDemuxedStream#load: " + fragmentString);
}
_metrics = _fragmentStream.load(_fragment, key);
return _metrics;
}
//
//
//
// FragmentStream Event Listeners
//
//
//
/**
*
* @method onFragmentStreamProgress
* @param {ProgressEvent} evt
*/
private function onStreamProgress(evt : ProgressEvent) : void {
_fragment = _fragmentStream.getFragment();
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug2("FragmentDemuxedStream#onStreamProgress: " +
fragmentString + " Progress - " + evt.bytesLoaded + " of " + evt.bytesTotal);
Log.debug2("FragmentDemuxedStream#onStreamProgress: " +
fragmentString + " Fragment status - bytes.position / bytes.length / bytesLoaded " +
_fragment.data.bytes.position + " / " +
_fragment.data.bytes.length + " / " +
_fragment.data.bytesLoaded);
}
// If we are loading a partial Fragment then only parse when it has
// completed loading to desired portion (See onFragmentStreamComplete)
/*
if (fragment.byterange_start_offset != -1) {
return;
}
*/
// START PARSING METRICS
if (_metrics.parsing_begin_time == 0) {
_metrics.parsing_begin_time = getTimer();
}
// Demuxer has not yet been initialized as this is probably first
// call to onFragmentStreamProgress, but demuxer may also be/remain
// null due to unknown Fragment type. Probe is synchronous.
if (_demux == null) {
// It is possible we have run onFragmentStreamProgress before
// without having sufficient data to probe
//bytes.position = bytes.length;
//bytes.writeBytes(byteArray);
//byteArray = bytes;
CONFIG::LOGGING {
var fragmentString : String = "Fragment[" + _fragment.level + "][" + _fragment.seqnum + "]";
Log.debug2("FragmentDemuxedStream#onStreamProgress: Need a Demuxer for " + fragmentString);
}
_demux = DemuxHelper.probe(
_fragment.data.bytes,
null,
_onDemuxAudioTrackRequested,
_onDemuxProgress,
_onDemuxComplete,
_onDemuxVideoMetadata,
_onDemuxID3TagFound,
false
);
}
if (_demux) {
// Demuxer expects the ByteArray delta
var byteArray : ByteArray = new ByteArray();
_fragment.data.bytes.readBytes(byteArray, 0, _fragment.data.bytes.length - _fragment.data.bytes.position);
byteArray.position = 0;
_demux.append(byteArray);
}
}
/**
* Called when FragmentStream completes.
*
* @method onStreamComplete
* @param {Event} evt
*/
private function onStreamComplete(evt : Event) : void {
// If demuxer is still null, then the Fragment type was invalid
if (_demux == null) {
CONFIG::LOGGING {
Log.error("FragmentDemuxedStream#onStreamComplete: unknown fragment type");
_fragment.data.bytes.position = 0;
var bytes2 : ByteArray = new ByteArray();
_fragment.data.bytes.readBytes(bytes2, 0, 512);
Log.debug2("FragmentDemuxedStream#onStreamComplete: frag dump(512 bytes)");
Log.debug2(Hex.fromArray(bytes2));
}
var err : ErrorEvent = new ErrorEvent(
ErrorEvent.ERROR,
false,
false,
"Unknown Fragment Type"
);
dispatchEvent(err);
} else {
_demux.notifycomplete();
}
}
/**
* Called when FragmentStream has errored.
*
* @method onStreamError
* @param {ProgressEvent} evt
*/
private function onStreamError(evt : ErrorEvent) : void {
CONFIG::LOGGING {
Log.error("FragmentDemuxedStream#onStreamError: " + evt.text);
}
dispatchEvent(evt);
}
//
//
//
// Demuxer Callbacks
//
//
//
/**
* Called when Demuxer needs to know which AudioTrack to parse for.
*
* FIXME: This callback simply returns the first audio track!
* We need to pass this class the appropriate callback propogated from
* UI layer. Yuck.
*
* @method _onDemuxAudioTrackRequested
* @param {Vector<AudioTrack} audioTrackList - List of AudioTracks
* @return {AudioTrack} - AudioTrack to parse
*/
private function _onDemuxAudioTrackRequested(audioTrackList : Vector.<AudioTrack>) : AudioTrack {
if (audioTrackList.length > 0) {
return audioTrackList[0];
} else {
return null;
}
}
/**
* Called when Demuxer parsed portion of Fragment.
*
* @method _onDemuxProgress
* @param {Vector<FLVTag} tags
*/
private function _onDemuxProgress(tags : Vector.<FLVTag>) : void {
CONFIG::LOGGING {
Log.debug2("FragmentDemuxedStream#_onDemuxProgress");
}
_fragment.data.appendTags(tags);
// TODO: Options to parse only portion of Fragment
// FIXME: bytesLoaded and bytesTotal represent stats of the current
// FragmentStream, not Demuxer, which is no longer bytes-relative.
// What should we define here?
var progressEvent : ProgressEvent = new ProgressEvent(
ProgressEvent.PROGRESS,
false,
false,
_fragment.data.bytes.length, // bytesLoaded
_fragment.data.bytesTotal // bytesTotal
);
dispatchEvent(progressEvent);
};
/**
* Called when Demuxer has finished parsing Fragment.
*
* @method _onDemuxComplete
*/
private function _onDemuxComplete() : void {
CONFIG::LOGGING {
Log.debug2("FragmentDemuxedStream#_onDemuxComplete");
}
_metrics.parsing_end_time = getTimer();
_complete = true;
var completeEvent : Event = new ProgressEvent(Event.COMPLETE);
dispatchEvent(completeEvent);
};
/**
* Called when Video metadata is parsed.
*
* Specifically, when Sequence Parameter Set (SPS) is found.
*
* @method _onDemuxVideoMetadata
* @param {uint} width
* @param {uint} height
*/
private function _onDemuxVideoMetadata(width : uint, height : uint) : void {
if (_fragment.data.video_width == 0) {
CONFIG::LOGGING {
Log.debug2("FragmentDemuxedStream#_onDemuxVideoMetadata: AVC SPS = " + width + "x" + height);
}
_fragment.data.video_width = width;
_fragment.data.video_height = height;
}
}
/**
* Called when ID3 tags are found.
*
* @method _onDemuxID3TagFound
* @param {Vector.<ID3Tag>} id3_tags - ID3 Tags
*/
private function _onDemuxID3TagFound(id3_tags : Vector.<ID3Tag>) : void {
_fragment.data.id3_tags = id3_tags;
}
}
}
|
Add complete state variable
|
[FragmentDemuxedStream] Add complete state variable
|
ActionScript
|
mpl-2.0
|
codex-corp/flashls,codex-corp/flashls
|
c1dafec9ba841f49859d4661a5dceb35d41d9fe4
|
src/flash/htmlelements/YouTubeElement.as
|
src/flash/htmlelements/YouTubeElement.as
|
package htmlelements
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.utils.Timer;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
import flash.display.MovieClip;
import flash.display.Loader;
import flash.display.DisplayObject;
import FlashMediaElement;
import HtmlMediaEvent;
public class YouTubeElement extends Sprite implements IMediaElement
{
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _preload:String = "";
private var _element:FlashMediaElement;
// event values
private var _currentTime:Number = 0;
private var _duration:Number = 0;
private var _framerate:Number;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _volume:Number = 1;
private var _isMuted:Boolean = false;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _bufferEmpty:Boolean = false;
private var _videoWidth:Number = -1;
private var _videoHeight:Number = -1;
private var _timer:Timer;
// YouTube stuff
private var _playerLoader:Loader;
private var _player:Object = null;
private var _playerIsLoaded:Boolean = false;
private var _youTubeId:String = "";
//http://code.google.com/p/gdata-samples/source/browse/trunk/ytplayer/actionscript3/com/google/youtube/examples/AS3Player.as
private static const WIDESCREEN_ASPECT_RATIO:String = "widescreen";
private static const QUALITY_TO_PLAYER_WIDTH:Object = {
small: 320,
medium: 640,
large: 854,
hd720: 1280
};
private static const STATE_ENDED:Number = 0;
private static const STATE_PLAYING:Number = 1;
private static const STATE_PAUSED:Number = 2;
private static const STATE_CUED:Number = 5;
public function get player():DisplayObject {
return _player;
}
public function setSize(width:Number, height:Number):void {
if (_player != null) {
_player.setSize(width, height);
}
}
public function get videoHeight():Number {
return _videoHeight;
}
public function get videoWidth():Number {
return _videoWidth;
}
public function duration():Number {
return _duration;
}
public function currentProgress():Number {
if(_bytesTotal> 0) {
return Math.round(_bytesLoaded/_bytesTotal*100);
} else {
return 0;
}
}
public function currentTime():Number {
return _currentTime;
}
public var initHeight:Number;
public var initWidth:Number;
// (1) load()
// calls _connection.connect();
// waits for NetConnection.Connect.Success
// _stream gets created
private var _isChromeless:Boolean = false;
public function YouTubeElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number)
{
_element = element;
_autoplay = autoplay;
_volume = startVolume;
_preload = preload;
initHeight = 0;
initWidth = 0;
_playerLoader = new Loader();
_playerLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, playerLoaderInitHandler);
// chromeless
if (_isChromeless) {
_playerLoader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3&controls=1&rel=0&showinfo=0&iv_load_policy=1"));
}
_timer = new Timer(timerRate);
_timer.addEventListener("timer", timerHandler);
_timer.start();
}
private function playerLoaderInitHandler(event:Event):void {
trace("yt player init");
_element.addChild(_playerLoader.content);
_element.setControlDepth();
_playerLoader.content.addEventListener("onReady", onPlayerReady);
_playerLoader.content.addEventListener("onError", onPlayerError);
_playerLoader.content.addEventListener("onStateChange", onPlayerStateChange);
_playerLoader.content.addEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange);
}
private function onPlayerReady(event:Event):void {
_playerIsLoaded = true;
_player = _playerLoader.content;
if (initHeight > 0 && initWidth > 0)
_player.setSize(initWidth, initHeight);
if (_youTubeId != "") { // && _isChromeless) {
if (_autoplay) {
player.loadVideoById(_youTubeId);
} else {
player.cueVideoById(_youTubeId);
}
_timer.start();
}
}
private function onPlayerError(event:Event):void {
// trace("Player error:", Object(event).data);
}
private function onPlayerStateChange(event:Event):void {
trace("State is", Object(event).data);
_duration = _player.getDuration();
switch (Object(event).data) {
case STATE_ENDED:
_isEnded = true;
_isPaused = false;
sendEvent(HtmlMediaEvent.ENDED);
break;
case STATE_PLAYING:
_isEnded = false;
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
break;
case STATE_PAUSED:
_isEnded = false;
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
break;
case STATE_CUED:
sendEvent(HtmlMediaEvent.CANPLAY);
// resize?
break;
}
}
private function onVideoPlaybackQualityChange(event:Event):void {
trace("Current video quality:", Object(event).data);
//resizePlayer(Object(event).data);
}
private function timerHandler(e:TimerEvent) {
if (_playerIsLoaded) {
_bytesLoaded = _player.getVideoBytesLoaded();
_bytesTotal = _player.getVideoBytesTotal();
_currentTime = player.getCurrentTime();
if (!_isPaused)
sendEvent(HtmlMediaEvent.TIMEUPDATE);
if (_bytesLoaded < _bytesTotal)
sendEvent(HtmlMediaEvent.PROGRESS);
}
}
private function getYouTubeId(url:String):String {
// http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
// http://www.youtube.com/v/VIDEO_ID?version=3
// http://youtu.be/Djd6tPrxc08
url = unescape(url);
var youTubeId:String = "";
if (url.indexOf("?") > 0) {
// assuming: http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
youTubeId = getYouTubeIdFromParam(url);
// if it's http://www.youtube.com/v/VIDEO_ID?version=3
if (youTubeId == "") {
youTubeId = getYouTubeIdFromUrl(url);
}
} else {
youTubeId = getYouTubeIdFromUrl(url);
}
return youTubeId;
}
// http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
private function getYouTubeIdFromParam(url:String):String {
var youTubeId:String = "";
var parts:Array = url.split('?');
var parameters:Array = parts[1].split('&');
for (var i:Number=0; i<parameters.length; i++) {
var paramParts = parameters[i].split('=');
if (paramParts[0] == "v") {
youTubeId = paramParts[1];
break;
}
}
return youTubeId;
}
// http://www.youtube.com/v/VIDEO_ID?version=3
// http://youtu.be/Djd6tPrxc08
private function getYouTubeIdFromUrl(url:String):String {
var youTubeId:String = "";
// remove any querystring elements
var parts:Array = url.split('?');
url = parts[0];
youTubeId = url.substring(url.lastIndexOf("/")+1);
return youTubeId;
}
// interface members
public function setSrc(url:String):void {
trace("yt setSrc()" + url );
_currentUrl = url;
_youTubeId = getYouTubeId(url);
if (!_playerIsLoaded && !_isChromeless) {
_playerLoader.load(new URLRequest("http://www.youtube.com/v/" + _youTubeId + "?version=3&controls=0&rel=0&showinfo=0&iv_load_policy=1"));
}
}
public function load():void {
// do nothing
trace("yt load()");
if (_playerIsLoaded) {
player.loadVideoById(_youTubeId);
_timer.start();
} else {
/*
if (!_isChromless && _youTubeId != "") {
_playerLoader.load(new URLRequest("http://www.youtube.com/v/" + _youTubeId + "?version=3&controls=0&rel=0&showinfo=0&iv_load_policy=1"));
}
*/
}
}
public function play():void {
if (_playerIsLoaded) {
_player.playVideo();
}
}
public function pause():void {
if (_playerIsLoaded) {
_player.pauseVideo();
}
}
public function stop():void {
if (_playerIsLoaded) {
_player.pauseVideo();
}
}
public function setCurrentTime(pos:Number):void {
_player.seekTo(pos, false);
}
public function setVolume(volume:Number):void {
_player.setVolume(volume*100);
_volume = volume;
}
public function getVolume():Number {
return _player.getVolume()*100;
}
public function setMuted(muted:Boolean):void {
if (muted) {
_player.mute();
} else {
_player.unMute();
}
_muted = _player.isMuted();
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal * _duration;
// build JSON
var values:String =
"duration:" + _duration +
",framerate:" + _framerate +
",currentTime:" + _currentTime +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
",videoWidth:" + _videoWidth +
",videoHeight:" + _videoHeight +
"";
_element.sendEvent(eventName, values);
}
}
}
|
package htmlelements
{
import flash.display.Sprite;
import flash.events.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.utils.Timer;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLVariables;
import flash.net.URLRequestMethod;
import flash.display.MovieClip;
import flash.display.Loader;
import flash.display.DisplayObject;
import FlashMediaElement;
import HtmlMediaEvent;
public class YouTubeElement extends Sprite implements IMediaElement
{
private var _currentUrl:String = "";
private var _autoplay:Boolean = true;
private var _preload:String = "";
private var _element:FlashMediaElement;
// event values
private var _currentTime:Number = 0;
private var _duration:Number = 0;
private var _framerate:Number;
private var _isPaused:Boolean = true;
private var _isEnded:Boolean = false;
private var _volume:Number = 1;
private var _isMuted:Boolean = false;
private var _bytesLoaded:Number = 0;
private var _bytesTotal:Number = 0;
private var _bufferedTime:Number = 0;
private var _bufferEmpty:Boolean = false;
private var _videoWidth:Number = -1;
private var _videoHeight:Number = -1;
private var _timer:Timer;
// YouTube stuff
private var _playerLoader:Loader;
private var _player:Object = null;
private var _playerIsLoaded:Boolean = false;
private var _youTubeId:String = "";
//http://code.google.com/p/gdata-samples/source/browse/trunk/ytplayer/actionscript3/com/google/youtube/examples/AS3Player.as
private static const WIDESCREEN_ASPECT_RATIO:String = "widescreen";
private static const QUALITY_TO_PLAYER_WIDTH:Object = {
small: 320,
medium: 640,
large: 854,
hd720: 1280
};
private static const STATE_ENDED:Number = 0;
private static const STATE_PLAYING:Number = 1;
private static const STATE_PAUSED:Number = 2;
private static const STATE_CUED:Number = 5;
public function get player():DisplayObject {
return _player;
}
public function setSize(width:Number, height:Number):void {
if (_player != null) {
_player.setSize(width, height);
} else {
initHeight = height;
initWidth = width;
}
}
public function get videoHeight():Number {
return _videoHeight;
}
public function get videoWidth():Number {
return _videoWidth;
}
public function duration():Number {
return _duration;
}
public function currentProgress():Number {
if(_bytesTotal> 0) {
return Math.round(_bytesLoaded/_bytesTotal*100);
} else {
return 0;
}
}
public function currentTime():Number {
return _currentTime;
}
public var initHeight:Number;
public var initWidth:Number;
// (1) load()
// calls _connection.connect();
// waits for NetConnection.Connect.Success
// _stream gets created
private var _isChromeless:Boolean = false;
public function YouTubeElement(element:FlashMediaElement, autoplay:Boolean, preload:String, timerRate:Number, startVolume:Number)
{
_element = element;
_autoplay = autoplay;
_volume = startVolume;
_preload = preload;
initHeight = 0;
initWidth = 0;
_playerLoader = new Loader();
_playerLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, playerLoaderInitHandler);
// chromeless
if (_isChromeless) {
_playerLoader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3&controls=1&rel=0&showinfo=0&iv_load_policy=1"));
}
_timer = new Timer(timerRate);
_timer.addEventListener("timer", timerHandler);
_timer.start();
}
private function playerLoaderInitHandler(event:Event):void {
trace("yt player init");
_element.addChild(_playerLoader.content);
_element.setControlDepth();
_playerLoader.content.addEventListener("onReady", onPlayerReady);
_playerLoader.content.addEventListener("onError", onPlayerError);
_playerLoader.content.addEventListener("onStateChange", onPlayerStateChange);
_playerLoader.content.addEventListener("onPlaybackQualityChange", onVideoPlaybackQualityChange);
}
private function onPlayerReady(event:Event):void {
_playerIsLoaded = true;
_player = _playerLoader.content;
if (initHeight > 0 && initWidth > 0)
_player.setSize(initWidth, initHeight);
if (_youTubeId != "") { // && _isChromeless) {
if (_autoplay) {
player.loadVideoById(_youTubeId);
} else {
player.cueVideoById(_youTubeId);
}
_timer.start();
}
}
private function onPlayerError(event:Event):void {
// trace("Player error:", Object(event).data);
}
private function onPlayerStateChange(event:Event):void {
trace("State is", Object(event).data);
_duration = _player.getDuration();
switch (Object(event).data) {
case STATE_ENDED:
_isEnded = true;
_isPaused = false;
sendEvent(HtmlMediaEvent.ENDED);
break;
case STATE_PLAYING:
_isEnded = false;
_isPaused = false;
sendEvent(HtmlMediaEvent.PLAY);
sendEvent(HtmlMediaEvent.PLAYING);
break;
case STATE_PAUSED:
_isEnded = false;
_isPaused = true;
sendEvent(HtmlMediaEvent.PAUSE);
break;
case STATE_CUED:
sendEvent(HtmlMediaEvent.CANPLAY);
// resize?
break;
}
}
private function onVideoPlaybackQualityChange(event:Event):void {
trace("Current video quality:", Object(event).data);
//resizePlayer(Object(event).data);
}
private function timerHandler(e:TimerEvent) {
if (_playerIsLoaded) {
_bytesLoaded = _player.getVideoBytesLoaded();
_bytesTotal = _player.getVideoBytesTotal();
_currentTime = player.getCurrentTime();
if (!_isPaused)
sendEvent(HtmlMediaEvent.TIMEUPDATE);
if (_bytesLoaded < _bytesTotal)
sendEvent(HtmlMediaEvent.PROGRESS);
}
}
private function getYouTubeId(url:String):String {
// http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
// http://www.youtube.com/v/VIDEO_ID?version=3
// http://youtu.be/Djd6tPrxc08
url = unescape(url);
var youTubeId:String = "";
if (url.indexOf("?") > 0) {
// assuming: http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
youTubeId = getYouTubeIdFromParam(url);
// if it's http://www.youtube.com/v/VIDEO_ID?version=3
if (youTubeId == "") {
youTubeId = getYouTubeIdFromUrl(url);
}
} else {
youTubeId = getYouTubeIdFromUrl(url);
}
return youTubeId;
}
// http://www.youtube.com/watch?feature=player_embedded&v=yyWWXSwtPP0
private function getYouTubeIdFromParam(url:String):String {
var youTubeId:String = "";
var parts:Array = url.split('?');
var parameters:Array = parts[1].split('&');
for (var i:Number=0; i<parameters.length; i++) {
var paramParts = parameters[i].split('=');
if (paramParts[0] == "v") {
youTubeId = paramParts[1];
break;
}
}
return youTubeId;
}
// http://www.youtube.com/v/VIDEO_ID?version=3
// http://youtu.be/Djd6tPrxc08
private function getYouTubeIdFromUrl(url:String):String {
var youTubeId:String = "";
// remove any querystring elements
var parts:Array = url.split('?');
url = parts[0];
youTubeId = url.substring(url.lastIndexOf("/")+1);
return youTubeId;
}
// interface members
public function setSrc(url:String):void {
trace("yt setSrc()" + url );
_currentUrl = url;
_youTubeId = getYouTubeId(url);
if (!_playerIsLoaded && !_isChromeless) {
_playerLoader.load(new URLRequest("http://www.youtube.com/v/" + _youTubeId + "?version=3&controls=0&rel=0&showinfo=0&iv_load_policy=1"));
}
}
public function load():void {
// do nothing
trace("yt load()");
if (_playerIsLoaded) {
player.loadVideoById(_youTubeId);
_timer.start();
} else {
/*
if (!_isChromless && _youTubeId != "") {
_playerLoader.load(new URLRequest("http://www.youtube.com/v/" + _youTubeId + "?version=3&controls=0&rel=0&showinfo=0&iv_load_policy=1"));
}
*/
}
}
public function play():void {
if (_playerIsLoaded) {
_player.playVideo();
}
}
public function pause():void {
if (_playerIsLoaded) {
_player.pauseVideo();
}
}
public function stop():void {
if (_playerIsLoaded) {
_player.pauseVideo();
}
}
public function setCurrentTime(pos:Number):void {
//_player.seekTo(pos, false);
_player.seekTo(pos, true); // works in all places now
}
public function setVolume(volume:Number):void {
_player.setVolume(volume*100);
_volume = volume;
}
public function getVolume():Number {
return _player.getVolume()*100;
}
public function setMuted(muted:Boolean):void {
if (muted) {
_player.mute();
} else {
_player.unMute();
}
_muted = _player.isMuted();
sendEvent(HtmlMediaEvent.VOLUMECHANGE);
}
private function sendEvent(eventName:String) {
// calculate this to mimic HTML5
_bufferedTime = _bytesLoaded / _bytesTotal * _duration;
// build JSON
var values:String =
"duration:" + _duration +
",framerate:" + _framerate +
",currentTime:" + _currentTime +
",muted:" + _isMuted +
",paused:" + _isPaused +
",ended:" + _isEnded +
",volume:" + _volume +
",src:\"" + _currentUrl + "\"" +
",bytesTotal:" + _bytesTotal +
",bufferedBytes:" + _bytesLoaded +
",bufferedTime:" + _bufferedTime +
",videoWidth:" + _videoWidth +
",videoHeight:" + _videoHeight +
"";
_element.sendEvent(eventName, values);
}
}
}
|
fix for seeking
|
fix for seeking
|
ActionScript
|
agpl-3.0
|
libeo/Vibeo,libeo/Vibeo,libeo/Vibeo,libeo/Vibeo
|
1de3f13490b102b94a3d44fc2f26c75bf5f84fad
|
WeaveData/src/weave/data/Transforms/PartitionDataTransform.as
|
WeaveData/src/weave/data/Transforms/PartitionDataTransform.as
|
package weave.data.Transforms
{
import weave.api.core.ILinkableHashMap;
import weave.api.data.ColumnMetadata;
import weave.api.data.IAttributeColumn;
import weave.api.data.IColumnReference;
import weave.api.data.IDataSource;
import weave.api.data.IWeaveTreeNode;
import weave.api.newLinkableChild;
import weave.api.registerLinkableChild;
import weave.core.LinkableHashMap;
import weave.data.AttributeColumns.DynamicColumn;
import weave.data.AttributeColumns.FilteredColumn;
import weave.data.AttributeColumns.ProxyColumn;
import weave.data.DataSources.AbstractDataSource;
import weave.data.KeySets.StringDataFilter;
import weave.utils.VectorUtils;
public class PartitionDataTransform extends AbstractDataSource
{
public static const PARTITION_VALUE_META:String = "__PartitionValue__";
public static const PARTITION_COLUMNNAME_META:String = "__PartitionColumnName__";
WeaveAPI.registerImplementation(IDataSource, PartitionDataTransform, "Partitioned Table");
public const inputColumns:ILinkableHashMap = registerLinkableChild(this, new LinkableHashMap(IAttributeColumn), inputColumnsChanged);
public const partitionColumn:DynamicColumn = newLinkableChild(this, DynamicColumn, partitionColumnChanged);
public var layer_names:Array = [];
public function PartitionDataTransform()
{
}
public function inputColumnsChanged():void
{
refreshHierarchy();
refreshAllProxyColumns();
}
private function partitionColumnChanged():void
{
var keys:Array = partitionColumn.keys;
var layers:Object = {};
for (var idx:int = keys.length - 1; idx >= 0; idx--)
{
var value:String = partitionColumn.getValueFromKey(keys[idx], String);
layers[value] = true;
}
layer_names = VectorUtils.getKeys(layers);
refreshHierarchy();
refreshAllProxyColumns();
}
public function getInputColumnTitle(name:String):String
{
var column:IAttributeColumn = inputColumns.getObject(name) as IAttributeColumn;
return column.getMetadata(ColumnMetadata.TITLE);
}
override protected function generateHierarchyNode(metadata:Object):IWeaveTreeNode
{
var transformNode:PartitionTransformNode;
var valueNode:PartitionValueNode;
var columnNode:PartitionColumnNode;
transformNode = new PartitionTransformNode(this);
if (metadata[PARTITION_VALUE_META] === undefined)
return transformNode;
valueNode = new PartitionValueNode(transformNode, metadata[PARTITION_VALUE_META])
if (metadata[PARTITION_COLUMNNAME_META] === undefined)
return valueNode;
return new PartitionColumnNode(valueNode, metadata[PARTITION_COLUMNNAME_META]);
}
override public function getHierarchyRoot():IWeaveTreeNode
{
if (!_rootNode)
_rootNode = new PartitionTransformNode(this);
return _rootNode;
}
override protected function requestHierarchyFromSource(subtreeNode:XML = null):void
{
// do nothing, as the hierarchy is known ahead of time.
return;
}
override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void
{
var metadata:Object = proxyColumn.getProxyMetadata();
var columnName:String = metadata[PARTITION_COLUMNNAME_META];
var value:String = metadata[PARTITION_VALUE_META];
var column:IAttributeColumn = inputColumns.getObject(columnName) as IAttributeColumn;
var newFilteredColumn:FilteredColumn = new FilteredColumn();
var filter:StringDataFilter = newFilteredColumn.filter.requestLocalObject(StringDataFilter, false);
filter.column.requestLocalObjectCopy(partitionColumn);
filter.stringValue.value = value;
newFilteredColumn.internalDynamicColumn.requestLocalObjectCopy(column);
proxyColumn.setInternalColumn(newFilteredColumn);
}
}
}
import weave.api.data.ColumnMetadata;
import weave.api.data.IColumnReference;
import weave.api.data.IDataSource;
import weave.api.data.IWeaveTreeNode;
import weave.data.Transforms.PartitionDataTransform;
internal class PartitionTransformNode implements IWeaveTreeNode
{
private var _source:PartitionDataTransform;
private var children:Array;
public function get source():PartitionDataTransform { return _source; }
public function PartitionTransformNode(source:PartitionDataTransform)
{
_source = source;
}
public function equals(other:IWeaveTreeNode):Boolean
{
var that:PartitionTransformNode = other as PartitionTransformNode;
return !!that &&
that.source === this.source;
}
public function isBranch():Boolean { return true; }
public function hasChildBranches():Boolean {return true; }
public function getChildren():Array
{
if (children == null)
{
children = [];
var layer_names:Array = source.layer_names;
for (var idx:int = layer_names.length - 1; idx >= 0; idx--)
{
var layer:String = layer_names[idx];
children.push(new PartitionValueNode(this, layer));
}
}
return children;
}
public function getLabel():String
{
return WeaveAPI.globalHashMap.getName(source);
}
}
internal class PartitionValueNode implements IWeaveTreeNode
{
private var _parent:PartitionTransformNode;
private var _partitionValue:String;
private var children:Array;
public function get parent():PartitionTransformNode { return _parent; }
public function get partitionValue():String { return _partitionValue; }
public function PartitionValueNode(parent:PartitionTransformNode, value:String)
{
_parent = parent;
_partitionValue = value;
}
public function equals(other:IWeaveTreeNode):Boolean
{
var that:PartitionValueNode = other as PartitionValueNode;
return !!that &&
this.partitionValue == that.partitionValue &&
that.parent.equals(this.parent);
}
public function isBranch():Boolean { return true; }
public function hasChildBranches():Boolean { return false; }
public function getChildren():Array
{
if (children == null)
{
children = [];
var column_names:Array = parent.source.inputColumns.getNames();
for (var idx:int = column_names.length - 1; idx >= 0; idx--)
{
children.push(new PartitionColumnNode(this, column_names[idx]));
}
}
return children;
}
public function getLabel():String
{
return _partitionValue;
}
}
internal class PartitionColumnNode implements IWeaveTreeNode, IColumnReference
{
private var _parent:PartitionValueNode;
private var _columnName:String;
public function get parent():PartitionValueNode { return _parent; }
public function get columnName():String { return _columnName; }
public function PartitionColumnNode(parent:PartitionValueNode, columnName:String)
{
_parent = parent;
_columnName = columnName;
}
public function equals(other:IWeaveTreeNode):Boolean
{
var that:PartitionColumnNode = other as PartitionColumnNode;
return !!that &&
this.columnName == that.columnName &&
that.parent.equals(this.parent);
}
public function isBranch():Boolean {return false;}
public function hasChildBranches():Boolean {return false;}
public function getChildren():Array {return null; }
public function getLabel():String
{
return parent.parent.source.getInputColumnTitle(_columnName) +
" (" + parent.partitionValue + ")";
}
public function getDataSource():IDataSource
{
return parent.parent.source;
}
public function getColumnMetadata():Object
{
var metadata:Object = {};
metadata[PartitionDataTransform.PARTITION_COLUMNNAME_META] = columnName;
metadata[PartitionDataTransform.PARTITION_VALUE_META] = parent.partitionValue;
return metadata;
}
}
|
package weave.data.Transforms
{
import weave.api.core.ILinkableHashMap;
import weave.api.data.ColumnMetadata;
import weave.api.data.IAttributeColumn;
import weave.api.data.IColumnReference;
import weave.api.data.IDataSource;
import weave.api.data.IWeaveTreeNode;
import weave.api.newLinkableChild;
import weave.api.registerLinkableChild;
import weave.core.LinkableHashMap;
import weave.data.AttributeColumns.DynamicColumn;
import weave.data.AttributeColumns.FilteredColumn;
import weave.data.AttributeColumns.ProxyColumn;
import weave.data.DataSources.AbstractDataSource;
import weave.data.KeySets.StringDataFilter;
import weave.utils.VectorUtils;
public class PartitionDataTransform extends AbstractDataSource
{
public static const PARTITION_VALUE_META:String = "__PartitionValue__";
public static const PARTITION_COLUMNNAME_META:String = "__PartitionColumnName__";
WeaveAPI.registerImplementation(IDataSource, PartitionDataTransform, "Partitioned Table");
public const inputColumns:ILinkableHashMap = registerLinkableChild(this, new LinkableHashMap(IAttributeColumn), inputColumnsChanged);
public const partitionColumn:DynamicColumn = newLinkableChild(this, DynamicColumn, partitionColumnChanged);
public var layer_names:Array = [];
public function PartitionDataTransform()
{
}
public function inputColumnsChanged():void
{
refreshHierarchy();
refreshAllProxyColumns();
}
private function partitionColumnChanged():void
{
var keys:Array = partitionColumn.keys;
var layers:Object = {};
for (var idx:int = keys.length - 1; idx >= 0; idx--)
{
var value:String = partitionColumn.getValueFromKey(keys[idx], String);
layers[value] = true;
}
layer_names = VectorUtils.getKeys(layers);
refreshHierarchy();
refreshAllProxyColumns();
}
public function getInputColumnTitle(name:String):String
{
var column:IAttributeColumn = inputColumns.getObject(name) as IAttributeColumn;
return column ? column.getMetadata(ColumnMetadata.TITLE) : '';
}
override protected function generateHierarchyNode(metadata:Object):IWeaveTreeNode
{
var transformNode:PartitionTransformNode;
var valueNode:PartitionValueNode;
var columnNode:PartitionColumnNode;
transformNode = new PartitionTransformNode(this);
if (metadata[PARTITION_VALUE_META] === undefined)
return transformNode;
valueNode = new PartitionValueNode(transformNode, metadata[PARTITION_VALUE_META])
if (metadata[PARTITION_COLUMNNAME_META] === undefined)
return valueNode;
return new PartitionColumnNode(valueNode, metadata[PARTITION_COLUMNNAME_META]);
}
override public function getHierarchyRoot():IWeaveTreeNode
{
if (!_rootNode)
_rootNode = new PartitionTransformNode(this);
return _rootNode;
}
override protected function requestColumnFromSource(proxyColumn:ProxyColumn):void
{
var metadata:Object = proxyColumn.getProxyMetadata();
var columnName:String = metadata[PARTITION_COLUMNNAME_META];
var value:String = metadata[PARTITION_VALUE_META];
var column:IAttributeColumn = inputColumns.getObject(columnName) as IAttributeColumn;
var newFilteredColumn:FilteredColumn = new FilteredColumn();
var filter:StringDataFilter = newFilteredColumn.filter.requestLocalObject(StringDataFilter, false);
filter.column.requestLocalObjectCopy(partitionColumn);
filter.stringValue.value = value;
newFilteredColumn.internalDynamicColumn.requestLocalObjectCopy(column);
proxyColumn.setInternalColumn(newFilteredColumn);
}
}
}
import weave.api.data.ColumnMetadata;
import weave.api.data.IColumnReference;
import weave.api.data.IDataSource;
import weave.api.data.IWeaveTreeNode;
import weave.data.Transforms.PartitionDataTransform;
internal class PartitionTransformNode implements IWeaveTreeNode
{
private var _source:PartitionDataTransform;
private var children:Array;
public function get source():PartitionDataTransform { return _source; }
public function PartitionTransformNode(source:PartitionDataTransform)
{
_source = source;
}
public function equals(other:IWeaveTreeNode):Boolean
{
var that:PartitionTransformNode = other as PartitionTransformNode;
return !!that &&
that.source === this.source;
}
public function isBranch():Boolean { return true; }
public function hasChildBranches():Boolean {return true; }
public function getChildren():Array
{
if (children == null)
{
children = [];
var layer_names:Array = source.layer_names;
for (var idx:int = layer_names.length - 1; idx >= 0; idx--)
{
var layer:String = layer_names[idx];
children.push(new PartitionValueNode(this, layer));
}
}
return children;
}
public function getLabel():String
{
return WeaveAPI.globalHashMap.getName(source);
}
}
internal class PartitionValueNode implements IWeaveTreeNode
{
private var _parent:PartitionTransformNode;
private var _partitionValue:String;
private var children:Array;
public function get parent():PartitionTransformNode { return _parent; }
public function get partitionValue():String { return _partitionValue; }
public function PartitionValueNode(parent:PartitionTransformNode, value:String)
{
_parent = parent;
_partitionValue = value;
}
public function equals(other:IWeaveTreeNode):Boolean
{
var that:PartitionValueNode = other as PartitionValueNode;
return !!that &&
this.partitionValue == that.partitionValue &&
that.parent.equals(this.parent);
}
public function isBranch():Boolean { return true; }
public function hasChildBranches():Boolean { return false; }
public function getChildren():Array
{
if (children == null)
{
children = [];
var column_names:Array = parent.source.inputColumns.getNames();
for (var idx:int = column_names.length - 1; idx >= 0; idx--)
{
children.push(new PartitionColumnNode(this, column_names[idx]));
}
}
return children;
}
public function getLabel():String
{
return _partitionValue;
}
}
internal class PartitionColumnNode implements IWeaveTreeNode, IColumnReference
{
private var _parent:PartitionValueNode;
private var _columnName:String;
public function get parent():PartitionValueNode { return _parent; }
public function get columnName():String { return _columnName; }
public function PartitionColumnNode(parent:PartitionValueNode, columnName:String)
{
_parent = parent;
_columnName = columnName;
}
public function equals(other:IWeaveTreeNode):Boolean
{
var that:PartitionColumnNode = other as PartitionColumnNode;
return !!that &&
this.columnName == that.columnName &&
that.parent.equals(this.parent);
}
public function isBranch():Boolean {return false;}
public function hasChildBranches():Boolean {return false;}
public function getChildren():Array {return null; }
public function getLabel():String
{
return parent.parent.source.getInputColumnTitle(_columnName) +
" (" + parent.partitionValue + ")";
}
public function getDataSource():IDataSource
{
return parent.parent.source;
}
public function getColumnMetadata():Object
{
var metadata:Object = {};
metadata[PartitionDataTransform.PARTITION_COLUMNNAME_META] = columnName;
metadata[PartitionDataTransform.PARTITION_VALUE_META] = parent.partitionValue;
return metadata;
}
}
|
fix null pointer error
|
fix null pointer error
Change-Id: I0e44faee096bf245825f75d76dc3b127ed8dfc64
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
b70a372cf0cb9e54e38c5ec0d059e9a1aeed9710
|
Exporter/src/harayoki/app/bitmapfont/export/FntExporter.as
|
Exporter/src/harayoki/app/bitmapfont/export/FntExporter.as
|
package harayoki.app.bitmapfont.export
{
import flash.display.BitmapData;
import flash.display.PNGEncoderOptions;
import flash.events.Event;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
import harayoki.app.data.FontData;
import org.osflash.signals.Signal;
public class FntExporter
{
private var _onResult:Signal = new Signal();
private var _errorMessage:String;
private var _isSuccess:Boolean = false;
private var _canceled:Boolean = false;
public function FntExporter()
{
fntFileMaker = XmlFntFileMaker.getInstance();
}
private var _fntFileMaker:IFntFileMaker;
public function get fntFileMaker():IFntFileMaker
{
return _fntFileMaker;
}
public function set fntFileMaker(value:IFntFileMaker):void
{
_fntFileMaker = value;
}
public function export(fntFileName:String,fontData:FontData,bitmapData:BitmapData):void
{
var bytes:ByteArray;
var data:String = _fntFileMaker.makeFntFile(fontData,bitmapData);
trace(data);
_errorMessage = "";
_isSuccess = false;
var file:File = File.desktopDirectory;
file.browseForDirectory("select save dirctory");
file.addEventListener(Event.SELECT,onSelectDir);
file.addEventListener(Event.CANCEL,onCancelSelectDir);
function clearListener():void
{
file.removeEventListener(Event.SELECT,onSelectDir);
file.removeEventListener(Event.CANCEL,onCancelSelectDir);
}
function onSelectDir(ev:Event):void
{
clearListener();
writeFntData();
}
function onCancelSelectDir(ev:Event):void
{
clearListener();
_isSuccess = false;
_canceled = true;
_onResult.dispatch();
}
function writeFntData():void
{
try
{
var fntFile:File = file.resolvePath(fntFileName)
var fileStream:FileStream = new FileStream();
fileStream.open(fntFile,FileMode.WRITE);
fileStream.writeUTFBytes(data);
fileStream.close();
flash.utils.setTimeout(makePngData,1);
}
catch(err:Error)
{
_errorMessage = err.message;
_isSuccess = false;
_onResult.dispatch();
}
}
function makePngData():void
{
try
{
bytes = new ByteArray();
var option:PNGEncoderOptions = new PNGEncoderOptions();
bitmapData.encode(bitmapData.rect,option,bytes);
flash.utils.setTimeout(writePngData,1);
}
catch(err:Error)
{
_errorMessage = err.message;
_isSuccess = false;
_onResult.dispatch();
}
}
function writePngData():void
{
try
{
var pngFile:File = file.resolvePath(fontData.file)
var fileStream:FileStream = new FileStream();
fileStream.open(pngFile,FileMode.WRITE);
fileStream.writeBytes(bytes);
fileStream.close();
flash.utils.setTimeout(finish,1);
}
catch(err:Error)
{
_errorMessage = err.message;
_isSuccess = false;
_onResult.dispatch();
}
}
function finish():void
{
_isSuccess = true;
_onResult.dispatch();
}
}
public function get onResult():Signal
{
return _onResult;
}
public function get successed():Boolean
{
return _isSuccess;
}
public function get canceled():Boolean
{
return _canceled;
}
public function get errorMessage():String
{
return _errorMessage;
}
}
}
|
package harayoki.app.bitmapfont.export
{
import flash.display.BitmapData;
import flash.display.PNGEncoderOptions;
import flash.events.Event;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.SharedObject;
import flash.utils.ByteArray;
import flash.utils.setTimeout;
import harayoki.app.data.FontData;
import org.osflash.signals.Signal;
public class FntExporter
{
private static const SO_KEY:String = "BitmapFOntExporter";
private static const LAST_SAVED:String = "lastsaved";
private var _onResult:Signal = new Signal();
private var _errorMessage:String;
private var _isSuccess:Boolean = false;
private var _canceled:Boolean = false;
public function FntExporter()
{
fntFileMaker = XmlFntFileMaker.getInstance();
}
private var _fntFileMaker:IFntFileMaker;
public function get fntFileMaker():IFntFileMaker
{
return _fntFileMaker;
}
public function set fntFileMaker(value:IFntFileMaker):void
{
_fntFileMaker = value;
}
public function export(fntFileName:String,fontData:FontData,bitmapData:BitmapData):void
{
var bytes:ByteArray;
var data:String = _fntFileMaker.makeFntFile(fontData,bitmapData);
trace(data);
_errorMessage = "";
_isSuccess = false;
var file:File;
var so:SharedObject = SharedObject.getLocal(SO_KEY);
var path:String = so.data[LAST_SAVED];
if(path)
{
file = new File(path);
if(!file.exists)
{
file = File.userDirectory;
}
}
else
{
file = File.userDirectory;
}
file.browseForDirectory("select save dirctory");
file.addEventListener(Event.SELECT,onSelectDir);
file.addEventListener(Event.CANCEL,onCancelSelectDir);
function clearListener():void
{
file.removeEventListener(Event.SELECT,onSelectDir);
file.removeEventListener(Event.CANCEL,onCancelSelectDir);
}
function onSelectDir(ev:Event):void
{
clearListener();
writeFntData();
}
function onCancelSelectDir(ev:Event):void
{
clearListener();
_isSuccess = false;
_canceled = true;
_onResult.dispatch();
}
function writeFntData():void
{
try
{
var fntFile:File = file.resolvePath(fntFileName)
var fileStream:FileStream = new FileStream();
fileStream.open(fntFile,FileMode.WRITE);
fileStream.writeUTFBytes(data);
fileStream.close();
flash.utils.setTimeout(makePngData,1);
}
catch(err:Error)
{
_errorMessage = err.message;
_isSuccess = false;
_onResult.dispatch();
}
}
function makePngData():void
{
try
{
bytes = new ByteArray();
var option:PNGEncoderOptions = new PNGEncoderOptions();
bitmapData.encode(bitmapData.rect,option,bytes);
flash.utils.setTimeout(writePngData,1);
}
catch(err:Error)
{
_errorMessage = err.message;
_isSuccess = false;
_onResult.dispatch();
}
}
function writePngData():void
{
try
{
var pngFile:File = file.resolvePath(fontData.file)
var fileStream:FileStream = new FileStream();
fileStream.open(pngFile,FileMode.WRITE);
fileStream.writeBytes(bytes);
fileStream.close();
flash.utils.setTimeout(finish,1);
}
catch(err:Error)
{
_errorMessage = err.message;
_isSuccess = false;
_onResult.dispatch();
}
}
function finish():void
{
so.data[LAST_SAVED] = file.nativePath;
trace(file.nativePath);
_isSuccess = true;
_onResult.dispatch();
}
}
public function get onResult():Signal
{
return _onResult;
}
public function get successed():Boolean
{
return _isSuccess;
}
public function get canceled():Boolean
{
return _canceled;
}
public function get errorMessage():String
{
return _errorMessage;
}
}
}
|
save file path
|
save file path
|
ActionScript
|
apache-2.0
|
harayoki/BitmapFontExporter,harayoki/BitmapFontExporter
|
d298cd01edcbd159050bd1b8faabcc475992826e
|
src/aerys/minko/type/binding/ShaderDataBindingsProxy.as
|
src/aerys/minko/type/binding/ShaderDataBindingsProxy.as
|
package aerys.minko.type.binding
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.compiler.Serializer;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.BindableConstant;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.BindableSampler;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Constant;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Sampler;
/**
* The wrapper used to expose scene/mesh data bindings in ActionScript shaders.
*
* @author Jean-Marc Le Roux
*
*/
public final class ShaderDataBindingsProxy extends DataBindingsProxy
{
private var _serializer : Serializer;
public function ShaderDataBindingsProxy(bindings : DataBindings,
signature : Signature,
signatureFlags : uint)
{
super(bindings, signature, signatureFlags);
_serializer = new Serializer();
}
public function getParameter(name : String,
size : uint,
defaultValue : Object = null) : SFloat
{
if (defaultValue != null && !propertyExists(name))
{
var constantValue : Vector.<Number> = new Vector.<Number>();
_serializer.serializeKnownLength(defaultValue, constantValue, 0, size);
return new SFloat(new Constant(constantValue));
}
return new SFloat(new BindableConstant(name, size));
}
public function getTextureParameter(bindingName : String,
filter : uint = 1,
mipmap : uint = 0,
wrapping : uint = 1,
dimension : uint = 0,
format : uint = 0,
defaultValue : TextureResource = null) : SFloat
{
if (defaultValue != null && !propertyExists(bindingName))
return new SFloat(new Sampler(defaultValue, filter, mipmap, wrapping, dimension, format));
return new SFloat(
new BindableSampler(bindingName, filter, mipmap, wrapping, dimension, format)
);
}
}
}
|
package aerys.minko.type.binding
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.compiler.Serializer;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.BindableConstant;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.BindableSampler;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Constant;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Sampler;
/**
* The wrapper used to expose scene/mesh data bindings in ActionScript shaders.
*
* @author Jean-Marc Le Roux
*
*/
public final class ShaderDataBindingsProxy extends DataBindingsProxy
{
public function ShaderDataBindingsProxy(bindings : DataBindings,
signature : Signature,
signatureFlags : uint)
{
super(bindings, signature, signatureFlags);
}
public function getParameter(name : String,
size : uint,
defaultValue : Object = null) : SFloat
{
if (defaultValue != null && !propertyExists(name))
{
var constantValue : Vector.<Number> = new Vector.<Number>();
var serializer : Serializer = new Serializer();
serializer.serializeKnownLength(defaultValue, constantValue, 0, size);
return new SFloat(new Constant(constantValue));
}
return new SFloat(new BindableConstant(name, size));
}
public function getTextureParameter(bindingName : String,
filter : uint = 1,
mipmap : uint = 0,
wrapping : uint = 1,
dimension : uint = 0,
format : uint = 0,
defaultValue : TextureResource = null) : SFloat
{
if (defaultValue != null && !propertyExists(bindingName))
return new SFloat(new Sampler(defaultValue, filter, mipmap, wrapping, dimension, format));
return new SFloat(
new BindableSampler(bindingName, filter, mipmap, wrapping, dimension, format)
);
}
}
}
|
use a local variable for Serializer to avoid useless memory consumption
|
use a local variable for Serializer to avoid useless memory consumption
|
ActionScript
|
mit
|
aerys/minko-as3
|
a8108fdaa02eb4d7229150f1f294bdabfcc646f9
|
src/as/com/threerings/ezgame/client/EZGamePanel.as
|
src/as/com/threerings/ezgame/client/EZGamePanel.as
|
package com.threerings.ezgame.client {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.events.Event;
import flash.utils.Dictionary;
import mx.containers.Canvas;
import mx.containers.VBox;
import mx.core.Container;
import mx.core.IChildList;
import mx.utils.DisplayUtil;
import com.threerings.util.MediaContainer;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import com.threerings.ezgame.data.EZGameConfig;
import com.threerings.ezgame.data.EZGameObject;
public class EZGamePanel extends VBox
implements PlaceView
{
/** The game object backend. */
public var backend :GameControlBackend;
public function EZGamePanel (ctx :CrowdContext, ctrl :EZGameController)
{
_ctx = ctx;
_ctrl = ctrl;
}
// from PlaceView
public function willEnterPlace (plobj :PlaceObject) :void
{
var cfg :EZGameConfig = (_ctrl.getPlaceConfig() as EZGameConfig);
_ezObj = (plobj as EZGameObject);
backend = createBackend();
_gameView = new GameContainer(cfg.configData); // TODO?
backend.setSharedEvents(
Loader(_gameView.getMediaContainer().getMedia()).
contentLoaderInfo.sharedEvents);
backend.setContainer(_gameView);
addChild(_gameView);
}
// from PlaceView
public function didLeavePlace (plobj :PlaceObject) :void
{
_gameView.getMediaContainer().shutdown(true);
removeChild(_gameView);
backend.shutdown();
}
/**
* Creates the backend object that will handle requests from user code.
*/
protected function createBackend () :GameControlBackend
{
return new GameControlBackend(_ctx, _ezObj);
}
protected var _ctx :CrowdContext;
protected var _ctrl :EZGameController;
protected var _gameView :GameContainer;
protected var _ezObj :EZGameObject;
}
}
|
package com.threerings.ezgame.client {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.events.Event;
import flash.utils.Dictionary;
import mx.containers.Canvas;
import mx.core.Container;
import mx.core.IChildList;
import mx.utils.DisplayUtil;
import com.threerings.util.MediaContainer;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import com.threerings.ezgame.data.EZGameConfig;
import com.threerings.ezgame.data.EZGameObject;
public class EZGamePanel extends Canvas
implements PlaceView
{
/** The game object backend. */
public var backend :GameControlBackend;
public function EZGamePanel (ctx :CrowdContext, ctrl :EZGameController)
{
_ctx = ctx;
_ctrl = ctrl;
}
// from PlaceView
public function willEnterPlace (plobj :PlaceObject) :void
{
var cfg :EZGameConfig = (_ctrl.getPlaceConfig() as EZGameConfig);
_ezObj = (plobj as EZGameObject);
backend = createBackend();
_gameView = new GameContainer(cfg.configData); // TODO?
_gameView.percentWidth = 100;
_gameView.percentHeight = 100;
backend.setSharedEvents(
Loader(_gameView.getMediaContainer().getMedia()).
contentLoaderInfo.sharedEvents);
backend.setContainer(_gameView);
addChild(_gameView);
}
// from PlaceView
public function didLeavePlace (plobj :PlaceObject) :void
{
_gameView.getMediaContainer().shutdown(true);
removeChild(_gameView);
backend.shutdown();
}
/**
* Creates the backend object that will handle requests from user code.
*/
protected function createBackend () :GameControlBackend
{
return new GameControlBackend(_ctx, _ezObj);
}
protected var _ctx :CrowdContext;
protected var _ctrl :EZGameController;
protected var _gameView :GameContainer;
protected var _ezObj :EZGameObject;
}
}
|
Extend from Canvas so that the chat overlay scrollbar works.
|
Extend from Canvas so that the chat overlay scrollbar works.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@160 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
1310ff035e82b5ea890da54bdca5da4c771b6378
|
vendors/VASTNew/org/osmf/vast/loader/VASTDocumentProcessor.as
|
vendors/VASTNew/org/osmf/vast/loader/VASTDocumentProcessor.as
|
/*****************************************************
*
* Copyright 2009 Adobe Systems Incorporated. All Rights Reserved.
*
*****************************************************
* 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 Initial Developer of the Original Code is Adobe Systems Incorporated.
* Portions created by Adobe Systems Incorporated are Copyright (C) 2009 Adobe Systems
* Incorporated. All Rights Reserved.
*
* Contributor(s): Eyewonder, LLC
*
*****************************************************/
package org.osmf.vast.loader
{
import flash.events.EventDispatcher;
import org.osmf.utils.HTTPLoader;
import org.osmf.vast.model.VASTDataObject;
import org.osmf.vast.model.VASTDocument;
import org.osmf.vast.parser.base.VAST2TrackingData;
CONFIG::LOGGING
{
import org.osmf.logging.Logger;
import org.osmf.logging.Log;
}
[Event("processed")]
[Event("processingFailed")]
internal class VASTDocumentProcessor extends EventDispatcher
{
/**
* @private Exposes the same interface as VAST1DocumentProcessor and VAST2DocumentProcessor.
* Determines which processor to use based on the VAST version stored in the VASTDataObject.
*/
public function VASTDocumentProcessor(maxNumWrapperRedirects:Number, httpLoader:HTTPLoader)
{
super();
this.maxNumWrapperRedirects = maxNumWrapperRedirects;
this.httpLoader = httpLoader;
}
/**
* @private
*/
public function processVASTDocument(documentContents:String, trackingData:VAST2TrackingData = null):void
{
var processingFailed:Boolean = false;
var vastDocument:VASTDocument = null;
var documentXML:XML = null;
try
{
documentXML = new XML(documentContents);
}
catch (error:TypeError)
{
processingFailed = true;
}
if (documentXML != null)
{
var vastVersion:Number;
if(documentXML.localName() == VAST_1_ROOT){
vastVersion = VASTDataObject.VERSION_1_0;
}else if(documentXML.localName() == VAST_2_ROOT){
vastVersion = documentXML.@version;
}
switch(vastVersion)
{
case VASTDataObject.VERSION_1_0:
var vast1DocumentProcessor:VAST1DocumentProcessor = new VAST1DocumentProcessor(maxNumWrapperRedirects, httpLoader);
vast1DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSED, cloneDocumentProcessorEvent);
vast1DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSING_FAILED, cloneDocumentProcessorEvent);
vast1DocumentProcessor.processVASTDocument(documentContents);
break;
case VASTDataObject.VERSION_2_0:
var vast2DocumentProcessor:VAST2DocumentProcessor = new VAST2DocumentProcessor(maxNumWrapperRedirects, httpLoader);
vast2DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSED, cloneDocumentProcessorEvent);
vast2DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSING_FAILED, cloneDocumentProcessorEvent);
vast2DocumentProcessor.processVASTDocument(documentContents, trackingData);
break;
case VASTDataObject.VERSION_3_0:
var vast3DocumentProcessor:VAST3DocumentProcessor = new VAST3DocumentProcessor(maxNumWrapperRedirects, httpLoader);
vast3DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSED, cloneVast3DocumentProcessorEvent);
vast3DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSING_FAILED, cloneVast3DocumentProcessorEvent);
vast3DocumentProcessor.processVASTDocument(documentContents, trackingData);
break;
default:
processingFailed = true;
break;
}
}
if (processingFailed)
{
CONFIG::LOGGING
{
logger.debug("[VAST] Processing failed for document with contents: " + documentContents);
}
dispatchEvent(new VASTDocumentProcessedEvent(VASTDocumentProcessedEvent.PROCESSING_FAILED));
}
}
private function cloneDocumentProcessorEvent(event:VASTDocumentProcessedEvent):void
{
var parser:EventDispatcher = event.target as EventDispatcher;
parser.removeEventListener(VASTDocumentProcessedEvent.PROCESSED, cloneDocumentProcessorEvent);
parser.removeEventListener(VASTDocumentProcessedEvent.PROCESSING_FAILED, cloneDocumentProcessorEvent);
dispatchEvent(event.clone());
}
private function cloneVast3DocumentProcessorEvent(event:VASTDocumentProcessedEvent):void
{
if (event.target is VAST3DocumentProcessor)
{
var parser:EventDispatcher = event.target as EventDispatcher;
parser.removeEventListener(VASTDocumentProcessedEvent.PROCESSED, cloneDocumentProcessorEvent);
parser.removeEventListener(VASTDocumentProcessedEvent.PROCESSING_FAILED, cloneDocumentProcessorEvent);
dispatchEvent(event.clone());
}
}
private var maxNumWrapperRedirects:Number;
private var httpLoader:HTTPLoader;
private static const VAST_1_ROOT:String = "VideoAdServingTemplate";
private static const VAST_2_ROOT:String = "VAST";
CONFIG::LOGGING
private static const logger:Logger = Log.getLogger("org.osmf.vast.loader.VASTDocumentProcessor");
}
}
|
/*****************************************************
*
* Copyright 2009 Adobe Systems Incorporated. All Rights Reserved.
*
*****************************************************
* 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 Initial Developer of the Original Code is Adobe Systems Incorporated.
* Portions created by Adobe Systems Incorporated are Copyright (C) 2009 Adobe Systems
* Incorporated. All Rights Reserved.
*
* Contributor(s): Eyewonder, LLC
*
*****************************************************/
package org.osmf.vast.loader
{
import flash.events.EventDispatcher;
import org.osmf.utils.HTTPLoader;
import org.osmf.vast.model.VASTDataObject;
import org.osmf.vast.model.VASTDocument;
import org.osmf.vast.parser.base.VAST2TrackingData;
CONFIG::LOGGING
{
import org.osmf.logging.Logger;
import org.osmf.logging.Log;
}
[Event("processed")]
[Event("processingFailed")]
internal class VASTDocumentProcessor extends EventDispatcher
{
/**
* @private Exposes the same interface as VAST1DocumentProcessor and VAST2DocumentProcessor.
* Determines which processor to use based on the VAST version stored in the VASTDataObject.
*/
public function VASTDocumentProcessor(maxNumWrapperRedirects:Number, httpLoader:HTTPLoader)
{
super();
this.maxNumWrapperRedirects = maxNumWrapperRedirects;
this.httpLoader = httpLoader;
}
/**
* @private
*/
public function processVASTDocument(documentContents:String, trackingData:VAST2TrackingData = null):void
{
var processingFailed:Boolean = false;
var vastDocument:VASTDocument = null;
var documentXML:XML = null;
try
{
documentXML = new XML(documentContents);
}
catch (error:TypeError)
{
processingFailed = true;
}
if (documentXML != null)
{
var vastVersion:Number;
if(documentXML.localName() == VAST_1_ROOT){
vastVersion = VASTDataObject.VERSION_1_0;
}else if(documentXML.localName() == VAST_2_ROOT){
vastVersion = documentXML.@version;
if ( documentXML.@version == "2.0.1" ) {
vastVersion = VASTDataObject.VERSION_2_0;
}
}
switch(vastVersion)
{
case VASTDataObject.VERSION_1_0:
var vast1DocumentProcessor:VAST1DocumentProcessor = new VAST1DocumentProcessor(maxNumWrapperRedirects, httpLoader);
vast1DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSED, cloneDocumentProcessorEvent);
vast1DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSING_FAILED, cloneDocumentProcessorEvent);
vast1DocumentProcessor.processVASTDocument(documentContents);
break;
case VASTDataObject.VERSION_2_0:
var vast2DocumentProcessor:VAST2DocumentProcessor = new VAST2DocumentProcessor(maxNumWrapperRedirects, httpLoader);
vast2DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSED, cloneDocumentProcessorEvent);
vast2DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSING_FAILED, cloneDocumentProcessorEvent);
vast2DocumentProcessor.processVASTDocument(documentContents, trackingData);
break;
case VASTDataObject.VERSION_3_0:
var vast3DocumentProcessor:VAST3DocumentProcessor = new VAST3DocumentProcessor(maxNumWrapperRedirects, httpLoader);
vast3DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSED, cloneVast3DocumentProcessorEvent);
vast3DocumentProcessor.addEventListener(VASTDocumentProcessedEvent.PROCESSING_FAILED, cloneVast3DocumentProcessorEvent);
vast3DocumentProcessor.processVASTDocument(documentContents, trackingData);
break;
default:
processingFailed = true;
break;
}
}
if (processingFailed)
{
CONFIG::LOGGING
{
logger.debug("[VAST] Processing failed for document with contents: " + documentContents);
}
dispatchEvent(new VASTDocumentProcessedEvent(VASTDocumentProcessedEvent.PROCESSING_FAILED));
}
}
private function cloneDocumentProcessorEvent(event:VASTDocumentProcessedEvent):void
{
var parser:EventDispatcher = event.target as EventDispatcher;
parser.removeEventListener(VASTDocumentProcessedEvent.PROCESSED, cloneDocumentProcessorEvent);
parser.removeEventListener(VASTDocumentProcessedEvent.PROCESSING_FAILED, cloneDocumentProcessorEvent);
dispatchEvent(event.clone());
}
private function cloneVast3DocumentProcessorEvent(event:VASTDocumentProcessedEvent):void
{
if (event.target is VAST3DocumentProcessor)
{
var parser:EventDispatcher = event.target as EventDispatcher;
parser.removeEventListener(VASTDocumentProcessedEvent.PROCESSED, cloneDocumentProcessorEvent);
parser.removeEventListener(VASTDocumentProcessedEvent.PROCESSING_FAILED, cloneDocumentProcessorEvent);
dispatchEvent(event.clone());
}
}
private var maxNumWrapperRedirects:Number;
private var httpLoader:HTTPLoader;
private static const VAST_1_ROOT:String = "VideoAdServingTemplate";
private static const VAST_2_ROOT:String = "VAST";
CONFIG::LOGGING
private static const logger:Logger = Log.getLogger("org.osmf.vast.loader.VASTDocumentProcessor");
}
}
|
Support VAST 2.0.1
|
Support VAST 2.0.1
|
ActionScript
|
agpl-3.0
|
kaltura/kdp,shvyrev/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp
|
50d9ab969a4bd2b2bdcea163074e51c73a5d5166
|
src/swf2png.as
|
src/swf2png.as
|
package
{
import com.adobe.images.PNGEncoder;
import flash.desktop.NativeApplication;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
import flash.utils.Timer;
public class swf2png extends Sprite
{
public var outputWidth:int;
public var outputHeight:int;
public var loadedSwf:MovieClip;
public var loader:Loader;
private var counter:int = 0;
private var timer:Timer;
private var totalFrames:int;
private var inputFileName:String;
private var inputFilePath:String;
private var prefix:String;
private var separator:String = "_";
private var outfield:TextField;
private var outputDirPath:String;
private var offsetMatrix:Matrix;
private var bBox:Rectangle;
public function swf2png() {
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
stage.align = 'TL';
stage.scaleMode = 'noScale';
outfield = new TextField();
outfield.autoSize = TextFieldAutoSize.LEFT;
stage.addChild(outfield);
stage.frameRate = 12;
}
//Loads in file
private function loadSwf():void {
loader = new Loader();
log("Loading " + inputFilePath);
loader.load(new URLRequest("file://" + inputFilePath));
loader.contentLoaderInfo.addEventListener(Event.INIT, startLoop);
}
//Event handler called when the swf is loaded. Sets it up and starts the export loop
private function startLoop(ev:Event):void {
try {
loadedSwf = MovieClip(ev.target.content);
}
catch(err:Error) {
//AVM1 Movie not supported
exit(5);
return;
}
outputWidth = Math.ceil(ev.target.width);
outputHeight = Math.ceil(ev.target.height);
log("Loaded!");
totalFrames = loadedSwf.totalFrames;
log("Frame count: " + totalFrames);
calculateBBox();
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
timer = new Timer(1);
timer.addEventListener(TimerEvent.TIMER, step);
timer.start();
}
private function padNumber(input:int, target:int):String {
var out:String = input.toString();
var targetCount:int = target.toString().length;
while(out.length < targetCount) {
out = '0' + out;
}
return out;
}
private function calculateBBox():void {
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
var boundsArray:Object = {
"x" : new Array(),
"y" : new Array(),
"w" : new Array(),
"h" : new Array()
}
var r:Rectangle;
for(var currentFrame:int = 0; currentFrame < totalFrames; currentFrame++) {
goToFrame(loadedSwf, currentFrame);
r = loader.content.getRect(stage);
boundsArray.x.push(r.x);
boundsArray.y.push(r.y);
boundsArray.w.push(r.width);
boundsArray.h.push(r.height);
}
boundsArray.x.sort(Array.NUMERIC);
boundsArray.y.sort(Array.NUMERIC);
boundsArray.w.sort(Array.NUMERIC | Array.DESCENDING);
boundsArray.h.sort(Array.NUMERIC | Array.DESCENDING);
bBox = new Rectangle(
Math.floor(boundsArray.x[0]),
Math.floor(boundsArray.y[0]),
Math.ceil(boundsArray.w[0]),
Math.ceil(boundsArray.h[0])
);
log("Bounding box: " + bBox)
outputWidth = bBox.width;
outputHeight = bBox.height;
offsetMatrix = new Matrix();
offsetMatrix.translate(bBox.x * -1, bBox.y * -1);
return;
}
//Called for every frame
private function step(ev:TimerEvent):void {
counter++;
if(counter <= totalFrames) {
goToFrame(loadedSwf, counter);
saveFrame();
}
else {
timer.stop();
log("Done!");
exit(0);
return;
}
}
//Saves the current frame of the loader object to a png
private function saveFrame():void {
var bitmapData:BitmapData = new BitmapData(outputWidth, outputHeight, true, 0x0);
bitmapData.draw(loader.content, offsetMatrix);
var bytearr:ByteArray = PNGEncoder.encode(bitmapData);
var increment:String = '';
if(totalFrames > 1) {
increment = separator + padNumber(counter, totalFrames);
}
var outfileName:String = outputDirPath + File.separator + prefix + increment + ".png"
var file:File = new File(outfileName);
log("Writing: " + outfileName);
var stream:FileStream = new FileStream();
stream.open(file, "write");
stream.writeBytes(bytearr);
stream.close();
}
//Stops the movie clip and all its subclips.
private function stopClip(inMc:MovieClip):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.stop();
if(mc.numChildren > 0) {
stopClip(mc);
}
}
}
inMc.stop();
}
//Traverses the movie clip and sets the current frame for all subclips too, looping them where needed.
private function goToFrame(inMc:MovieClip, frameNo:int):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.gotoAndStop(frameNo % inMc.totalFrames);
if(mc.numChildren > 0) {
goToFrame(mc, frameNo);
}
}
}
inMc.gotoAndStop(frameNo % inMc.totalFrames);
}
//Finds and checks for existance of input file
private function getInputFile(ev:InvokeEvent):String {
if(ev.arguments && ev.arguments.length) {
inputFileName = ev.arguments[0];
var matchNameRegExStr:String = '([^\\' + File.separator + ']+)$';
var matchNameRegEx:RegExp = new RegExp(matchNameRegExStr);
var matches:Array = inputFileName.match(matchNameRegEx);
if(!matches) {
// File inputFileName not valid
exit(2);
return "";
}
prefix = matches[1].split('.')[0];
log("Prefix: " + prefix);
var f:File = new File(ev.currentDirectory.nativePath);
f = f.resolvePath(inputFileName);
if(!f.exists) {
log("Input file not found!");
//Input file not found
exit(3);
return "";
}
return f.nativePath;
}
else {
//App opened without input data
exit(1);
return "";
}
}
//Finds and checks for existance of output directory
private function getOutputDir(ev:InvokeEvent):String {
var d:File;
if(ev.arguments.length > 1) {
outputDirPath = ev.arguments[1];
d = new File(ev.currentDirectory.nativePath);
d = d.resolvePath(outputDirPath);
if(!d.isDirectory) {
//outdir not a directory
exit(4);
return "";
}
log("inpt: " + d.nativePath);
return d.nativePath;
}
else {
if(ev.currentDirectory.nativePath === '/') {
if(ev.arguments.length) {
d = new File(ev.arguments[0]);
d = d.resolvePath('..');
return d.nativePath;
}
else {
return File.desktopDirectory.nativePath;
}
}
else {
log("cwd: " + ev.currentDirectory.nativePath);
return ev.currentDirectory.nativePath;
}
return "";
}
}
private function log(message:String="", add_new_line:Boolean=true):void {
outfield.appendText((add_new_line ? "\n" : "") + message);
}
//Invoke handler called when started
private function onInvoke(ev:InvokeEvent):void {
inputFilePath = getInputFile(ev);
outputDirPath = getOutputDir(ev);
log("Input file: " + inputFilePath);
log("Output directory: " + outputDirPath);
loadSwf();
}
private function exit(code:int=0):void {
log("Exit: " + code);
NativeApplication.nativeApplication.exit(code);
}
}
}
|
package
{
import com.adobe.images.PNGEncoder;
import flash.desktop.NativeApplication;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
import flash.utils.Timer;
public class swf2png extends Sprite
{
public var outputWidth:int;
public var outputHeight:int;
public var loadedSwf:MovieClip;
public var loader:Loader;
private var counter:int = 0;
private var timer:Timer;
private var totalFrames:int;
private var inputFileName:String;
private var inputFilePath:String;
private var prefix:String;
private var separator:String = "_";
private var outfield:TextField;
private var outputDirPath:String;
private var offsetMatrix:Matrix;
private var bBox:Rectangle;
private var scaleFactor:Number;
public function swf2png() {
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
stage.align = 'TL';
stage.scaleMode = 'noScale';
outfield = new TextField();
outfield.autoSize = TextFieldAutoSize.LEFT;
stage.addChild(outfield);
stage.frameRate = 12;
}
//Loads in file
private function loadSwf():void {
loader = new Loader();
log("Loading " + inputFilePath);
loader.load(new URLRequest("file://" + inputFilePath));
loader.contentLoaderInfo.addEventListener(Event.INIT, startLoop);
}
//Event handler called when the swf is loaded. Sets it up and starts the export loop
private function startLoop(ev:Event):void {
try {
loadedSwf = MovieClip(ev.target.content);
}
catch(err:Error) {
//AVM1 Movie not supported
exit(5);
return;
}
outputWidth = Math.ceil(ev.target.width);
outputHeight = Math.ceil(ev.target.height);
log("Loaded!");
totalFrames = loadedSwf.totalFrames;
log("Frame count: " + totalFrames);
calculateBBox();
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
timer = new Timer(1);
timer.addEventListener(TimerEvent.TIMER, step);
timer.start();
}
private function padNumber(input:int, target:int):String {
var out:String = input.toString();
var targetCount:int = target.toString().length;
while(out.length < targetCount) {
out = '0' + out;
}
return out;
}
private function calculateBBox():void {
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
var boundsArray:Object = {
"x" : new Array(),
"y" : new Array(),
"w" : new Array(),
"h" : new Array()
}
var r:Rectangle;
for(var currentFrame:int = 0; currentFrame < totalFrames; currentFrame++) {
goToFrame(loadedSwf, currentFrame);
r = loader.content.getRect(stage);
boundsArray.x.push(r.x);
boundsArray.y.push(r.y);
boundsArray.w.push(r.width);
boundsArray.h.push(r.height);
}
boundsArray.x.sort(Array.NUMERIC);
boundsArray.y.sort(Array.NUMERIC);
boundsArray.w.sort(Array.NUMERIC | Array.DESCENDING);
boundsArray.h.sort(Array.NUMERIC | Array.DESCENDING);
bBox = new Rectangle(
Math.floor(boundsArray.x[0]),
Math.floor(boundsArray.y[0]),
Math.ceil(boundsArray.w[0]),
Math.ceil(boundsArray.h[0])
);
log("Bounding box: " + bBox)
outputWidth = bBox.width * scaleFactor;
outputHeight = bBox.height * scaleFactor;
offsetMatrix = new Matrix();
offsetMatrix.translate(bBox.x * -1, bBox.y * -1);
offsetMatrix.scale(scaleFactor, scaleFactor);
return;
}
//Called for every frame
private function step(ev:TimerEvent):void {
counter++;
if(counter <= totalFrames) {
goToFrame(loadedSwf, counter);
saveFrame();
}
else {
timer.stop();
log("Done!");
exit(0);
return;
}
}
//Saves the current frame of the loader object to a png
private function saveFrame():void {
var bitmapData:BitmapData = new BitmapData(outputWidth, outputHeight, true, 0x0);
bitmapData.draw(loader.content, offsetMatrix);
var bytearr:ByteArray = PNGEncoder.encode(bitmapData);
var increment:String = '';
if(totalFrames > 1) {
increment = separator + padNumber(counter, totalFrames);
}
var outfileName:String = outputDirPath + File.separator + prefix + increment + ".png"
var file:File = new File(outfileName);
log("Writing: " + outfileName);
var stream:FileStream = new FileStream();
stream.open(file, "write");
stream.writeBytes(bytearr);
stream.close();
}
//Stops the movie clip and all its subclips.
private function stopClip(inMc:MovieClip):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.stop();
if(mc.numChildren > 0) {
stopClip(mc);
}
}
}
inMc.stop();
}
//Traverses the movie clip and sets the current frame for all subclips too, looping them where needed.
private function goToFrame(inMc:MovieClip, frameNo:int):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.gotoAndStop(frameNo % inMc.totalFrames);
if(mc.numChildren > 0) {
goToFrame(mc, frameNo);
}
}
}
inMc.gotoAndStop(frameNo % inMc.totalFrames);
}
//Finds and checks for existance of input file
private function getInputFile(ev:InvokeEvent):String {
if(ev.arguments && ev.arguments.length) {
inputFileName = ev.arguments[0];
var matchNameRegExStr:String = '([^\\' + File.separator + ']+)$';
var matchNameRegEx:RegExp = new RegExp(matchNameRegExStr);
var matches:Array = inputFileName.match(matchNameRegEx);
if(!matches) {
// File inputFileName not valid
exit(2);
return "";
}
prefix = matches[1].split('.')[0];
log("Prefix: " + prefix);
var f:File = new File(ev.currentDirectory.nativePath);
f = f.resolvePath(inputFileName);
if(!f.exists) {
log("Input file not found!");
//Input file not found
exit(3);
return "";
}
return f.nativePath;
}
else {
//App opened without input data
exit(1);
return "";
}
}
//Finds and checks for existance of output directory
private function getOutputDir(ev:InvokeEvent):String {
var d:File;
if(ev.arguments.length > 1) {
outputDirPath = ev.arguments[1];
d = new File(ev.currentDirectory.nativePath);
d = d.resolvePath(outputDirPath);
if(!d.isDirectory) {
//outdir not a directory
exit(4);
return "";
}
log("inpt: " + d.nativePath);
return d.nativePath;
}
else {
if(ev.currentDirectory.nativePath === '/') {
if(ev.arguments.length) {
d = new File(ev.arguments[0]);
d = d.resolvePath('..');
return d.nativePath;
}
else {
return File.desktopDirectory.nativePath;
}
}
else {
log("cwd: " + ev.currentDirectory.nativePath);
return ev.currentDirectory.nativePath;
}
return "";
}
}
private function getScaleFactor(ev:InvokeEvent):Number {
if(ev.arguments.length > 2) {
log("scale factor set to " + parseFloat(ev.arguments[2]));
return parseFloat(ev.arguments[2]);
}
return 1;
}
private function log(message:String="", add_new_line:Boolean=true):void {
outfield.appendText((add_new_line ? "\n" : "") + message);
}
//Invoke handler called when started
private function onInvoke(ev:InvokeEvent):void {
inputFilePath = getInputFile(ev);
outputDirPath = getOutputDir(ev);
scaleFactor = getScaleFactor(ev);
log("Input file: " + inputFilePath);
log("Output directory: " + outputDirPath);
loadSwf();
}
private function exit(code:int=0):void {
log("Exit: " + code);
NativeApplication.nativeApplication.exit(code);
}
}
}
|
Enable scaling of output assets.
|
Enable scaling of output assets.
|
ActionScript
|
mit
|
mdahlstrand/swf2png
|
9cbb25b5e4b0d846a37d50408d22a3c1009bb466
|
src/flash/events/ShaderEvent.as
|
src/flash/events/ShaderEvent.as
|
package flash.events {
import flash.display.BitmapData;
import flash.utils.ByteArray;
public class ShaderEvent extends Event {
public static const COMPLETE:String = "complete";
private var _bitmap:BitmapData;
private var _array:ByteArray;
private var _vector:Vector;
public function ShaderEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false,
bitmap:BitmapData = null, array:ByteArray = null,
vector:Vector = null)
{
super(type, bubbles, cancelable);
_bitmap = bitmap;
_array = array;
_vector = vector;
}
public function get bitmap():BitmapData {
return _bitmap;
}
public function set bitmap(value:BitmapData):void {
_bitmap = value;
}
public function get array():ByteArray {
return _array;
}
public function set array(value:ByteArray):void {
_array = value;
}
public function get vector():Vector {
return _vector;
}
public function set vector(value:Vector):void {
_vector = value;
}
public override function clone():Event {
return new ShaderEvent(type, bubbles, cancelable, bitmap, array, vector);
}
public override function toString():String {
return formatToString('ShaderEvent', 'type', 'bubbles', 'cancelable', 'eventPhase',
'bitmap', 'array', 'vector');
}
}
}
|
/*
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flash.events {
import flash.display.BitmapData;
import flash.utils.ByteArray;
public class ShaderEvent extends Event {
public static const COMPLETE:String = "complete";
private var _bitmap:BitmapData;
private var _array:ByteArray;
private var _vector:Vector;
public function ShaderEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false,
bitmap:BitmapData = null, array:ByteArray = null,
vector:Vector = null)
{
super(type, bubbles, cancelable);
_bitmap = bitmap;
_array = array;
_vector = vector;
}
public function get bitmap():BitmapData {
return _bitmap;
}
public function set bitmap(value:BitmapData):void {
_bitmap = value;
}
public function get array():ByteArray {
return _array;
}
public function set array(value:ByteArray):void {
_array = value;
}
public function get vector():Vector {
return _vector;
}
public function set vector(value:Vector):void {
_vector = value;
}
public override function clone():Event {
return new ShaderEvent(type, bubbles, cancelable, bitmap, array, vector);
}
public override function toString():String {
return formatToString('ShaderEvent', 'type', 'bubbles', 'cancelable', 'eventPhase',
'bitmap', 'array', 'vector');
}
}
}
|
Add license header to flash/events/ShaderEvent.as
|
Add license header to flash/events/ShaderEvent.as
|
ActionScript
|
apache-2.0
|
mbebenita/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway
|
31c582e480557a4370eea1ad441814262d045204
|
flexclient/dag/Components/DAGConstants.as
|
flexclient/dag/Components/DAGConstants.as
|
package Components
{
public class DAGConstants
{
public static var VIEW_ONLY_NODE:String ="ViewOnlyNode";
public static var CONSTRAINT_VIEW_NODE:String="ConstraintViewNode";
public static var CONSTRAINT_ONLY_NODE:String="ConstraintOnlyNode";
public static var EDIT:String="Edit";
public static var DELETE:String="Delete";
public static var ADD_TO_VIEW:String="AddToView";
public static var DELETE_FROM_VIEW:String="DeleteFromView";
public static var ADD_LIMIT_VIEW:String="AddLimit";
public static var RESULT_VIEW:String="Result";
//Error Codes
public static var SUCCESS:int=0;
public static var EMPTY_DAG:int=1;
public static var MULTIPLE_ROOT:int=2;
public static var CYCLIC_GRAPH:int=3;
public static var SQL_EXCEPTION:int=4;
public static var DAO_EXCEPTION:int=5;
public static var DYNAMIC_EXTENSION_EXCEPTION:int=6;
public static var NO_PATHS_PRESENT:int=7;
public static var NO_RESULT_PRESENT:int=8;
public static var CLASS_NOT_FOUND:int=9;
//messages
public static var EMPTY_LIMIT_ERROR_MESSAGE:String = "<li><font color='red'>Please enter at least one condition to add a limit to limit set.</font></li>";
public static var GENERIC_MESSAGE:String="<li><font color='red'>Error occured while executing query.Please report this problem to the Adminstrator.</font></li>";
public static var MULTIPLE_ROOT_MESSAGE:String="<li><font color='red'>Expression graph should be a connected graph and without multiple roots.</font></li>"
public static var NO_RESULT_PRESENT_MESSAGE:String="<li><font color='blue' family='arial,helvetica,verdana,sans-serif'>Zero records found for this query.</font></li>"
public static var EDIT_LIMITS_MESSAGE:String = "<li><font color='blue'>Limit succesfully edited.</font></li>";
public static var DELETE_LIMITS_MESSAGE:String = "<li><font color='blue'>Limit succesfully deleted.</font></li>";
}
}
|
package Components
{
public class DAGConstants
{
public static var VIEW_ONLY_NODE:String ="ViewOnlyNode";
public static var CONSTRAINT_VIEW_NODE:String="ConstraintViewNode";
public static var CONSTRAINT_ONLY_NODE:String="ConstraintOnlyNode";
public static var EDIT:String="Edit";
public static var DELETE:String="Delete";
public static var ADD_TO_VIEW:String="AddToView";
public static var DELETE_FROM_VIEW:String="DeleteFromView";
public static var ADD_LIMIT_VIEW:String="AddLimit";
public static var RESULT_VIEW:String="Result";
//Error Codes
public static var SUCCESS:int=0;
public static var EMPTY_DAG:int=1;
public static var MULTIPLE_ROOT:int=2;
public static var NO_RESULT_PRESENT:int=3;
public static var SQL_EXCEPTION:int=4;
public static var DAO_EXCEPTION:int=5;
public static var CLASS_NOT_FOUND:int=6;
public static var NO_PATHS_PRESENT:int=7;
public static var DYNAMIC_EXTENSION_EXCEPTION:int=8;
public static var CYCLIC_GRAPH:int=9;
//messages
public static var EMPTY_LIMIT_ERROR_MESSAGE:String = "<li><font color='red'>Please enter at least one condition to add a limit to limit set.</font></li>";
public static var GENERIC_MESSAGE:String="<li><font color='red'>Error occured while executing query.Please report this problem to the Adminstrator.</font></li>";
public static var MULTIPLE_ROOT_MESSAGE:String="<li><font color='red'>Expression graph should be a connected graph and without multiple roots.</font></li>"
public static var NO_RESULT_PRESENT_MESSAGE:String="<li><font color='blue' family='arial,helvetica,verdana,sans-serif'>Zero records found for this query.</font></li>"
public static var EDIT_LIMITS_MESSAGE:String = "<li><font color='blue'>Limit succesfully edited.</font></li>";
public static var DELETE_LIMITS_MESSAGE:String = "<li><font color='blue'>Limit succesfully deleted.</font></li>";
}
}
|
Change in constants value
|
Change in constants value
SVN-Revision: 8838
|
ActionScript
|
bsd-3-clause
|
asamgir/openspecimen,krishagni/openspecimen,krishagni/openspecimen,asamgir/openspecimen,asamgir/openspecimen,krishagni/openspecimen
|
644d8f32f54d4c14e0d48e5c29c9e43778461178
|
src/org/flintparticles/threeD/zones/BitmapDataZone.as
|
src/org/flintparticles/threeD/zones/BitmapDataZone.as
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2011
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.threeD.zones
{
import org.flintparticles.common.utils.FastWeightedArray;
import org.flintparticles.threeD.geom.Matrix3DUtils;
import org.flintparticles.threeD.geom.Vector3DUtils;
import flash.display.BitmapData;
import flash.geom.Matrix3D;
import flash.geom.Point;
import flash.geom.Vector3D;
/**
* The BitmapData zone defines a shaped zone based on a BitmapData object.
* The zone contains all pixels in the bitmap that are not transparent -
* i.e. they have an alpha value greater than zero.
*/
public class BitmapDataZone implements Zone3D
{
private var _bitmapData : BitmapData;
private var _corner : Vector3D;
private var _top : Vector3D;
private var _scaledWidth : Vector3D;
private var _left : Vector3D;
private var _scaledHeight : Vector3D;
private var _normal : Vector3D;
private var _basis : Matrix3D;
private var _distToOrigin:Number;
private var _dirty:Boolean;
private var _volume : Number;
private var _validPoints : FastWeightedArray;
/**
* The constructor creates a BitmapDataZone zone. To avoid distorting the zone, the top
* and left vectors should be perpendicular and the same lengths as the width and
* height of the bitmap data object. Vectors that are not the same width and height
* as the bitmap data object will scale the zone and vectors that are not perpendicular
* will skew the zone.
*
* @param bitmapData The bitmapData object that defines the zone.
* @param corner The position for the top left corner of the bitmap data for the zone.
* @param top The top side of the zone from the corner. The length of the vector
* indicates how long the side is.
* @param left The left side of the zone from the corner. The length of the
* vector indicates how long the side is.
*/
public function BitmapDataZone( bitmapData : BitmapData = null, corner:Vector3D = null, top:Vector3D = null, left:Vector3D = null )
{
_bitmapData = bitmapData;
this.corner = corner ? corner : new Vector3D();
this.top = top ? top : Vector3D.X_AXIS;
this.left = left ? left : new Vector3D( 0, 1, 0 );
if( _bitmapData )
{
_dirty = true;
invalidate();
}
}
/**
* The bitmapData object that defines the zone.
*/
public function get bitmapData() : BitmapData
{
return _bitmapData;
}
public function set bitmapData( value : BitmapData ) : void
{
_bitmapData = value;
invalidate();
}
/**
* The position for the top left corner of the bitmap data for the zone.
*/
public function get corner() : Vector3D
{
return _corner.clone();
}
public function set corner( value : Vector3D ) : void
{
_corner = Vector3DUtils.clonePoint( value );
}
/**
* The top side of the zone from the corner. The length of the vector
* indicates how long the side is.
*/
public function get top() : Vector3D
{
return _top.clone();
}
public function set top( value : Vector3D ) : void
{
_top = Vector3DUtils.cloneVector( value );
_dirty = true;
}
/**
* The left side of the zone from the corner. The length of the
* vector indicates how long the side is.
*/
public function get left() : Vector3D
{
return _left.clone();
}
public function set left( value : Vector3D ) : void
{
_left = Vector3DUtils.cloneVector( value );
_dirty = true;
}
/**
* This method forces the zone to revaluate itself. It should be called whenever the
* contents of the BitmapData object change. However, it is an intensive method and
* calling it frequently will likely slow your code down.
*/
public function invalidate():void
{
_validPoints = new FastWeightedArray();
for( var x : int = 0; x < _bitmapData.width ; ++x )
{
for( var y : int = 0; y < _bitmapData.height ; ++y )
{
var pixel : uint = _bitmapData.getPixel32( x, y );
var ratio : Number = ( pixel >> 24 & 0xFF ) / 0xFF;
if ( ratio != 0 )
{
_validPoints.add( new Point( x, _bitmapData.height-y ), ratio );
}
}
}
_volume = _top.crossProduct( _left ).length * _validPoints.totalRatios / ( _bitmapData.width * _bitmapData.height );
_dirty = true;
}
private function init():void
{
_normal = _top.crossProduct( _left );
_distToOrigin = _normal.dotProduct( _corner );
_scaledWidth = _top.clone();
_scaledWidth.scaleBy( 1 / _bitmapData.width );
_scaledHeight = _left.clone();
_scaledHeight.scaleBy( 1 / _bitmapData.height );
var perp:Vector3D = _top.crossProduct( _left );
perp.normalize();
_basis = Matrix3DUtils.newBasisTransform( _scaledWidth, _scaledHeight, perp );
_basis.prependTranslation( -_corner.x, -_corner.y, -_corner.z );
_dirty = false;
}
/**
* The contains method determines whether a point is inside the zone.
* This method is used by the initializers and actions that
* use the zone. Usually, it need not be called directly by the user.
*
* @param x The x coordinate of the location to test for.
* @param y The y coordinate of the location to test for.
* @return true if point is inside the zone, false if it is outside.
*/
public function contains( p:Vector3D ):Boolean
{
if( _dirty )
{
init();
}
var dist:Number = _normal.dotProduct( p );
if( Math.abs( dist - _distToOrigin ) > 0.1 ) // test for close, not exact
{
return false;
}
var q:Vector3D = _basis.transformVector( p );
var pixel : uint = _bitmapData.getPixel32( Math.round( q.x ), Math.round( _bitmapData.height-q.y ) );
return ( pixel >> 24 & 0xFF ) != 0;
}
/**
* The getLocation method returns a random point inside the zone.
* This method is used by the initializers and actions that
* use the zone. Usually, it need not be called directly by the user.
*
* @return a random point inside the zone.
*/
public function getLocation():Vector3D
{
if( _dirty )
{
init();
}
var point:Point = Point( _validPoints.getRandomValue() ).clone();
var d1:Vector3D = _scaledWidth;
d1.scaleBy( point.x );
var d2:Vector3D = _scaledHeight;
d2.scaleBy( point.y );
d1.incrementBy( d2 );
return _corner.add( d1 );
}
/**
* The getVolume method returns the size of the zone.
* This method is used by the MultiZone class. Usually,
* it need not be called directly by the user.
*
* @return a random point inside the zone.
*/
public function getVolume():Number
{
return _volume;
}
}
}
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2011
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.threeD.zones
{
import org.flintparticles.common.utils.FastWeightedArray;
import org.flintparticles.threeD.geom.Matrix3DUtils;
import org.flintparticles.threeD.geom.Vector3DUtils;
import flash.display.BitmapData;
import flash.geom.Matrix3D;
import flash.geom.Point;
import flash.geom.Vector3D;
/**
* The BitmapData zone defines a shaped zone based on a BitmapData object.
* The zone contains all pixels in the bitmap that are not transparent -
* i.e. they have an alpha value greater than zero.
*/
public class BitmapDataZone implements Zone3D
{
private var _bitmapData : BitmapData;
private var _corner : Vector3D;
private var _top : Vector3D;
private var _scaledWidth : Vector3D;
private var _left : Vector3D;
private var _scaledHeight : Vector3D;
private var _normal : Vector3D;
private var _basis : Matrix3D;
private var _distToOrigin:Number;
private var _dirty:Boolean;
private var _volume : Number;
private var _validPoints : FastWeightedArray;
/**
* The constructor creates a BitmapDataZone zone. To avoid distorting the zone, the top
* and left vectors should be perpendicular and the same lengths as the width and
* height of the bitmap data object. Vectors that are not the same width and height
* as the bitmap data object will scale the zone and vectors that are not perpendicular
* will skew the zone.
*
* @param bitmapData The bitmapData object that defines the zone.
* @param corner The position for the top left corner of the bitmap data for the zone.
* @param top The top side of the zone from the corner. The length of the vector
* indicates how long the side is.
* @param left The left side of the zone from the corner. The length of the
* vector indicates how long the side is.
*/
public function BitmapDataZone( bitmapData : BitmapData = null, corner:Vector3D = null, top:Vector3D = null, left:Vector3D = null )
{
_bitmapData = bitmapData;
this.corner = corner ? corner : new Vector3D();
this.top = top ? top : Vector3D.X_AXIS;
this.left = left ? left : new Vector3D( 0, 1, 0 );
if( _bitmapData )
{
_dirty = true;
invalidate();
}
}
/**
* The bitmapData object that defines the zone.
*/
public function get bitmapData() : BitmapData
{
return _bitmapData;
}
public function set bitmapData( value : BitmapData ) : void
{
_bitmapData = value;
invalidate();
}
/**
* The position for the top left corner of the bitmap data for the zone.
*/
public function get corner() : Vector3D
{
return _corner.clone();
}
public function set corner( value : Vector3D ) : void
{
_corner = Vector3DUtils.clonePoint( value );
}
/**
* The top side of the zone from the corner. The length of the vector
* indicates how long the side is.
*/
public function get top() : Vector3D
{
return _top.clone();
}
public function set top( value : Vector3D ) : void
{
_top = Vector3DUtils.cloneVector( value );
_dirty = true;
}
/**
* The left side of the zone from the corner. The length of the
* vector indicates how long the side is.
*/
public function get left() : Vector3D
{
return _left.clone();
}
public function set left( value : Vector3D ) : void
{
_left = Vector3DUtils.cloneVector( value );
_dirty = true;
}
/**
* This method forces the zone to revaluate itself. It should be called whenever the
* contents of the BitmapData object change. However, it is an intensive method and
* calling it frequently will likely slow your code down.
*/
public function invalidate():void
{
_validPoints = new FastWeightedArray();
for( var x : int = 0; x < _bitmapData.width ; ++x )
{
for( var y : int = 0; y < _bitmapData.height ; ++y )
{
var pixel : uint = _bitmapData.getPixel32( x, y );
var ratio : Number = ( pixel >> 24 & 0xFF ) / 0xFF;
if ( ratio != 0 )
{
_validPoints.add( new Point( x, _bitmapData.height-y ), ratio );
}
}
}
_volume = _top.crossProduct( _left ).length * _validPoints.totalRatios / ( _bitmapData.width * _bitmapData.height );
_dirty = true;
}
private function init():void
{
_normal = _top.crossProduct( _left );
_distToOrigin = _normal.dotProduct( _corner );
_scaledWidth = _top.clone();
_scaledWidth.scaleBy( 1 / _bitmapData.width );
_scaledHeight = _left.clone();
_scaledHeight.scaleBy( 1 / _bitmapData.height );
var perp:Vector3D = _top.crossProduct( _left );
perp.normalize();
_basis = Matrix3DUtils.newBasisTransform( _scaledWidth, _scaledHeight, perp );
_basis.prependTranslation( -_corner.x, -_corner.y, -_corner.z );
_dirty = false;
}
/**
* The contains method determines whether a point is inside the zone.
* This method is used by the initializers and actions that
* use the zone. Usually, it need not be called directly by the user.
*
* @param x The x coordinate of the location to test for.
* @param y The y coordinate of the location to test for.
* @return true if point is inside the zone, false if it is outside.
*/
public function contains( p:Vector3D ):Boolean
{
if( _dirty )
{
init();
}
var dist:Number = _normal.dotProduct( p );
if( Math.abs( dist - _distToOrigin ) > 0.1 ) // test for close, not exact
{
return false;
}
var q:Vector3D = _basis.transformVector( p );
var pixel : uint = _bitmapData.getPixel32( Math.round( q.x ), Math.round( _bitmapData.height-q.y ) );
return ( pixel >> 24 & 0xFF ) != 0;
}
/**
* The getLocation method returns a random point inside the zone.
* This method is used by the initializers and actions that
* use the zone. Usually, it need not be called directly by the user.
*
* @return a random point inside the zone.
*/
public function getLocation():Vector3D
{
if( _dirty )
{
init();
}
var point:Point = Point( _validPoints.getRandomValue() ).clone();
var d1:Vector3D = _scaledWidth.clone();
d1.scaleBy( point.x );
var d2:Vector3D = _scaledHeight.clone();
d2.scaleBy( point.y );
d1.incrementBy( d2 );
return _corner.add( d1 );
}
/**
* The getVolume method returns the size of the zone.
* This method is used by the MultiZone class. Usually,
* it need not be called directly by the user.
*
* @return a random point inside the zone.
*/
public function getVolume():Number
{
return _volume;
}
}
}
|
Fix error in 3D BitmapDataZone
|
Fix error in 3D BitmapDataZone
|
ActionScript
|
mit
|
richardlord/Flint
|
fae4515f3a0952d108f129187b8dbcd8d8d06bcd
|
src/org/mangui/hls/model/FragmentData.as
|
src/org/mangui/hls/model/FragmentData.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.model {
import org.mangui.hls.demux.ID3Tag;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.utils.AES;
import org.mangui.hls.utils.PTS;
import flash.utils.ByteArray;
/** Fragment Data. **/
public class FragmentData {
/** valid fragment **/
public var valid : Boolean;
/** fragment byte array **/
public var bytes : ByteArray;
/* Total bytes this Fragment _will_ have */
public var bytesTotal: int;
/** bytes Loaded **/
public var bytesLoaded : int;
/** AES decryption instance **/
public var decryptAES : AES;
/** Start PTS of this chunk. **/
public var pts_start : Number;
/** computed Start PTS of this chunk. **/
public var pts_start_computed : Number;
/** min/max audio/video PTS/DTS of this chunk. **/
public var pts_min_audio : Number;
public var pts_max_audio : Number;
public var pts_min_video : Number;
public var pts_max_video : Number;
public var dts_min : Number;
/** audio/video found ? */
public var audio_found : Boolean;
public var video_found : Boolean;
/** tag related stuff */
public var metadata_tag_injected : Boolean;
private var tags_pts_min_audio : Number;
private var tags_pts_max_audio : Number;
private var tags_pts_min_video : Number;
private var tags_pts_max_video : Number;
private var tags_audio_found : Boolean;
private var tags_video_found : Boolean;
public var tags : Vector.<FLVTag>;
/* video dimension */
public var video_width : int;
public var video_height : int;
/* is fragment loaded selected by autolevel algo */
public var auto_level : Boolean;
/* ID3 tags linked to this fragment */
public var id3_tags : Vector.<ID3Tag>;
/** Whether this Fragment starts with IDR **/
public var starts_with_idr : Boolean;
/** PTS of earliest AVC_HEADER */
public var pts_min_video_header : Number;
/** tag duration */
private var audio_tag_duration : Number;
private var video_tag_duration : Number;
private var audio_tag_last_dts : Number;
private var video_tag_last_dts : Number;
/** Fragment metrics **/
public function FragmentData() {
this.pts_start = NaN;
this.pts_start_computed = NaN;
this.valid = true;
this.video_width = 0;
this.video_height = 0;
this.starts_with_idr = false;
this.pts_min_video_header = NaN;
};
public function appendTags(tags : Vector.<FLVTag>) : void {
// Audio PTS/DTS normalization + min/max computation
for each (var tag : FLVTag in tags) {
tag.pts = PTS.normalize(pts_start_computed, tag.pts);
tag.dts = PTS.normalize(pts_start_computed, tag.dts);
dts_min = Math.min(dts_min, tag.dts);
switch( tag.type ) {
case FLVTag.AAC_RAW:
case FLVTag.AAC_HEADER:
case FLVTag.MP3_RAW:
audio_found = true;
tags_audio_found = true;
audio_tag_duration = tag.dts - audio_tag_last_dts;
audio_tag_last_dts = tag.dts;
tags_pts_min_audio = Math.min(tags_pts_min_audio, tag.pts);
tags_pts_max_audio = Math.max(tags_pts_max_audio, tag.pts);
pts_min_audio = Math.min(pts_min_audio, tag.pts);
pts_max_audio = Math.max(pts_max_audio, tag.pts);
break;
case FLVTag.AVC_HEADER:
if (isNaN(pts_min_video_header)) {
pts_min_video_header = tag.pts;
}
case FLVTag.AVC_NALU:
video_found = true;
tags_video_found = true;
video_tag_duration = tag.dts - video_tag_last_dts;
video_tag_last_dts = tag.dts;
tags_pts_min_video = Math.min(tags_pts_min_video, tag.pts);
tags_pts_max_video = Math.max(tags_pts_max_video, tag.pts);
pts_min_video = Math.min(pts_min_video, tag.pts);
pts_max_video = Math.max(pts_max_video, tag.pts);
starts_with_idr = !isNaN(pts_min_video_header) && pts_min_video_header <= tag.pts;
break;
case FLVTag.DISCONTINUITY:
case FLVTag.METADATA:
default:
break;
}
this.tags.push(tag);
}
}
public function flushTags() : void {
// clean-up tags
tags = new Vector.<FLVTag>();
tags_audio_found = tags_video_found = false;
metadata_tag_injected = false;
pts_min_audio = pts_min_video = dts_min = tags_pts_min_audio = tags_pts_min_video = Number.POSITIVE_INFINITY;
pts_max_audio = pts_max_video = tags_pts_max_audio = tags_pts_max_video = Number.NEGATIVE_INFINITY;
audio_found = video_found = tags_audio_found = tags_video_found = false;
starts_with_idr = false;
pts_min_video_header = NaN;
}
public function shiftTags() : void {
tags = new Vector.<FLVTag>();
if (tags_audio_found) {
tags_pts_min_audio = tags_pts_max_audio;
tags_audio_found = false;
}
if (tags_video_found) {
tags_pts_min_video = tags_pts_max_video;
tags_video_found = false;
}
}
public function get pts_min() : Number {
if (audio_found) {
return pts_min_audio;
} else {
return pts_min_video;
}
}
public function get pts_max() : Number {
if (audio_found) {
return pts_max_audio;
} else {
return pts_max_video;
}
}
public function get tag_duration() : Number {
var duration : Number;
if (audio_found) {
duration = audio_tag_duration;
} else {
duration = video_tag_duration;
}
if(isNaN(duration)) {
duration = 0;
}
return duration;
}
public function get tag_pts_min() : Number {
if (audio_found) {
return tags_pts_min_audio;
} else {
return tags_pts_min_video;
}
}
public function get tag_pts_max() : Number {
if (audio_found) {
return tags_pts_max_audio;
} else {
return tags_pts_max_video;
}
}
public function get tag_pts_start_offset() : Number {
if (tags_audio_found) {
return tags_pts_min_audio - pts_min_audio;
} else {
return tags_pts_min_video - pts_min_video;
}
}
public function get tag_pts_end_offset() : Number {
if (tags_audio_found) {
return tags_pts_max_audio - pts_min_audio;
} else {
return tags_pts_max_video - pts_min_video;
}
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.model {
import org.mangui.hls.demux.ID3Tag;
import org.mangui.hls.flv.FLVTag;
import org.mangui.hls.utils.AES;
import org.mangui.hls.utils.PTS;
import flash.utils.ByteArray;
/** Fragment Data. **/
public class FragmentData {
/** valid fragment **/
public var valid : Boolean;
/** fragment byte array **/
public var bytes : ByteArray;
/* Total bytes this Fragment _will_ have */
public var bytesTotal: int;
/** bytes Loaded **/
public var bytesLoaded : int;
/** AES decryption instance **/
public var decryptAES : AES;
/** Start PTS of this chunk. **/
public var pts_start : Number;
/** computed Start PTS of this chunk. **/
public var pts_start_computed : Number;
/** min/max audio/video PTS/DTS of this chunk. **/
public var pts_min_audio : Number;
public var pts_max_audio : Number;
public var pts_min_video : Number;
public var pts_max_video : Number;
public var dts_min : Number;
/** audio/video found ? */
public var audio_found : Boolean;
public var video_found : Boolean;
/** tag related stuff */
public var metadata_tag_injected : Boolean;
private var tags_pts_min_audio : Number;
private var tags_pts_max_audio : Number;
private var tags_pts_min_video : Number;
private var tags_pts_max_video : Number;
private var tags_audio_found : Boolean;
private var tags_video_found : Boolean;
public var tags : Vector.<FLVTag>;
/* video dimension */
public var video_width : int;
public var video_height : int;
/* is fragment loaded selected by autolevel algo */
public var auto_level : Boolean;
/* ID3 tags linked to this fragment */
public var id3_tags : Vector.<ID3Tag>;
/** Whether this Fragment starts with IDR **/
public var starts_with_idr : Boolean;
/** PTS of earliest AVC_HEADER */
public var pts_min_video_header : Number;
/** tag duration */
private var audio_tag_duration : Number;
private var video_tag_duration : Number;
private var audio_tag_last_dts : Number;
private var video_tag_last_dts : Number;
/** Fragment metrics **/
public function FragmentData() {
this.pts_start = NaN;
this.pts_start_computed = NaN;
this.valid = true;
this.video_width = 0;
this.video_height = 0;
this.starts_with_idr = true;
this.pts_min_video_header = NaN;
};
public function appendTags(tags : Vector.<FLVTag>) : void {
// Audio PTS/DTS normalization + min/max computation
for each (var tag : FLVTag in tags) {
tag.pts = PTS.normalize(pts_start_computed, tag.pts);
tag.dts = PTS.normalize(pts_start_computed, tag.dts);
dts_min = Math.min(dts_min, tag.dts);
switch( tag.type ) {
case FLVTag.AAC_RAW:
case FLVTag.AAC_HEADER:
case FLVTag.MP3_RAW:
audio_found = true;
tags_audio_found = true;
audio_tag_duration = tag.dts - audio_tag_last_dts;
audio_tag_last_dts = tag.dts;
tags_pts_min_audio = Math.min(tags_pts_min_audio, tag.pts);
tags_pts_max_audio = Math.max(tags_pts_max_audio, tag.pts);
pts_min_audio = Math.min(pts_min_audio, tag.pts);
pts_max_audio = Math.max(pts_max_audio, tag.pts);
break;
case FLVTag.AVC_HEADER:
if (isNaN(pts_min_video_header)) {
pts_min_video_header = tag.pts;
}
case FLVTag.AVC_NALU:
video_found = true;
tags_video_found = true;
video_tag_duration = tag.dts - video_tag_last_dts;
video_tag_last_dts = tag.dts;
tags_pts_min_video = Math.min(tags_pts_min_video, tag.pts);
tags_pts_max_video = Math.max(tags_pts_max_video, tag.pts);
pts_min_video = Math.min(pts_min_video, tag.pts);
pts_max_video = Math.max(pts_max_video, tag.pts);
if (isNaN(pts_min_video_header)) {
starts_with_idr = false;
}
break;
case FLVTag.DISCONTINUITY:
case FLVTag.METADATA:
default:
break;
}
this.tags.push(tag);
}
}
public function flushTags() : void {
// clean-up tags
tags = new Vector.<FLVTag>();
tags_audio_found = tags_video_found = false;
metadata_tag_injected = false;
pts_min_audio = pts_min_video = dts_min = tags_pts_min_audio = tags_pts_min_video = Number.POSITIVE_INFINITY;
pts_max_audio = pts_max_video = tags_pts_max_audio = tags_pts_max_video = Number.NEGATIVE_INFINITY;
audio_found = video_found = tags_audio_found = tags_video_found = false;
starts_with_idr = true;
pts_min_video_header = NaN;
}
public function shiftTags() : void {
tags = new Vector.<FLVTag>();
if (tags_audio_found) {
tags_pts_min_audio = tags_pts_max_audio;
tags_audio_found = false;
}
if (tags_video_found) {
tags_pts_min_video = tags_pts_max_video;
tags_video_found = false;
}
}
public function get pts_min() : Number {
if (audio_found) {
return pts_min_audio;
} else {
return pts_min_video;
}
}
public function get pts_max() : Number {
if (audio_found) {
return pts_max_audio;
} else {
return pts_max_video;
}
}
public function get tag_duration() : Number {
var duration : Number;
if (audio_found) {
duration = audio_tag_duration;
} else {
duration = video_tag_duration;
}
if(isNaN(duration)) {
duration = 0;
}
return duration;
}
public function get tag_pts_min() : Number {
if (audio_found) {
return tags_pts_min_audio;
} else {
return tags_pts_min_video;
}
}
public function get tag_pts_max() : Number {
if (audio_found) {
return tags_pts_max_audio;
} else {
return tags_pts_max_video;
}
}
public function get tag_pts_start_offset() : Number {
if (tags_audio_found) {
return tags_pts_min_audio - pts_min_audio;
} else {
return tags_pts_min_video - pts_min_video;
}
}
public function get tag_pts_end_offset() : Number {
if (tags_audio_found) {
return tags_pts_max_audio - pts_min_audio;
} else {
return tags_pts_max_video - pts_min_video;
}
}
}
}
|
Fix starts_with_idr setting
|
[FragmentData] Fix starts_with_idr setting
Poor implementation did not retain the fact that Fragment did not start
with IDR after successive headers were found.
|
ActionScript
|
mpl-2.0
|
codex-corp/flashls,codex-corp/flashls
|
166a2d65dc1bacbea37a5644da140c2a8126bc3e
|
flash/org/windmill/WMExplorer.as
|
flash/org/windmill/WMExplorer.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 {
import org.windmill.Windmill;
import org.windmill.WMLocator;
import org.windmill.WMLogger;
import org.windmill.WMRecorder;
import flash.display.Stage;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.external.ExternalInterface;
public class WMExplorer {
// Sprite which gets superimposed on the moused-over element
// and provides the border effect
private static var borderSprite:Sprite = new Sprite();
private static var running:Boolean = false;
public static function init():void {
}
public static function start():void {
// Stop the recorder if it's going
WMRecorder.stop();
running = true;
var stage:Stage = Windmill.getStage();
var spr:Sprite = borderSprite;
// Add the border-sprite to the stage
spr.name = 'borderSprite';
stage.addChild(spr);
// Highlight every element, create locator chain on mouseover
stage.addEventListener(MouseEvent.MOUSE_OVER, select);
// Stop on click
stage.addEventListener(MouseEvent.MOUSE_DOWN, annihilateEvent, true);
stage.addEventListener(MouseEvent.MOUSE_UP, annihilateEvent, true);
// This passes off to annihilateEvent to kill clicks too
stage.addEventListener(MouseEvent.CLICK, stop, true);
}
public static function stop(e:MouseEvent = null):void {
if (!running) { return; }
var stage:Stage = Windmill.getStage();
stage.removeChild(borderSprite);
stage.removeEventListener(MouseEvent.MOUSE_OVER, select);
stage.removeEventListener(MouseEvent.MOUSE_DOWN, stop);
running = false;
// Pass off to annihilateEvent to prevent the app from responding
annihilateEvent(e);
}
// Highlights the clicked-on itema and generates a chained-locator
// expression for it
public static function select(e:MouseEvent):void {
var targ:* = e.target;
// Bordered sprite for highlighting
var spr:Sprite = borderSprite;
// Get the global coords of the moused-over elem
// Overlay the border sprite in the same position
var bounds:Rectangle = targ.getBounds(targ.parent);
var p:Point = new Point(bounds.x, bounds.y);
p = targ.parent.localToGlobal(p);
spr.x = p.x;
spr.y = p.y;
// Clear any previous border, and draw a new border
// the same size as the moused-over elem
spr.graphics.clear()
spr.graphics.lineStyle(2, 0x3875d7, 1);
spr.graphics.drawRect(0, 0, targ.width, targ.height);
// Generate the expression
var expr:String = WMLocator.generateLocator(targ);
if (expr.length) {
// Strip off trailing slash
expr = expr.replace(/\/$/, '');
var res:* = ExternalInterface.call('wm_explorerSelect', expr);
if (!res) {
WMLogger.log('Locator chain: ' expr);
}
}
else {
throw new Error('Could not find any usable attributes for locator.');
}
}
public static function annihilateEvent(e:MouseEvent):void {
e.preventDefault();
e.stopImmediatePropagation();
}
}
}
|
/*
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 {
import org.windmill.Windmill;
import org.windmill.WMLocator;
import org.windmill.WMLogger;
import org.windmill.WMRecorder;
import flash.display.Stage;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.external.ExternalInterface;
public class WMExplorer {
// Sprite which gets superimposed on the moused-over element
// and provides the border effect
private static var borderSprite:Sprite = new Sprite();
private static var running:Boolean = false;
public static function init():void {
}
public static function start():void {
// Stop the recorder if it's going
WMRecorder.stop();
running = true;
var stage:Stage = Windmill.getStage();
var spr:Sprite = borderSprite;
// Add the border-sprite to the stage
spr.name = 'borderSprite';
stage.addChild(spr);
// Highlight every element, create locator chain on mouseover
stage.addEventListener(MouseEvent.MOUSE_OVER, select, false);
// Stop on click
stage.addEventListener(MouseEvent.MOUSE_DOWN, annihilateEvent, true);
stage.addEventListener(MouseEvent.MOUSE_UP, annihilateEvent, true);
// This passes off to annihilateEvent to kill clicks too
stage.addEventListener(MouseEvent.CLICK, stop, true);
}
public static function stop(e:MouseEvent = null):void {
if (!running) { return; }
var stage:Stage = Windmill.getStage();
stage.removeChild(borderSprite);
stage.removeEventListener(MouseEvent.MOUSE_OVER, select);
// Call removeEventListener with useCapture of 'true', since
// the listener was added with true
stage.removeEventListener(MouseEvent.MOUSE_DOWN, annihilateEvent, true);
stage.removeEventListener(MouseEvent.MOUSE_UP, annihilateEvent, true);
stage.removeEventListener(MouseEvent.CLICK, stop, true);
running = false;
// Pass off to annihilateEvent to prevent the app from responding
annihilateEvent(e);
}
// Highlights the clicked-on itema and generates a chained-locator
// expression for it
public static function select(e:MouseEvent):void {
var targ:* = e.target;
// Bordered sprite for highlighting
var spr:Sprite = borderSprite;
// Get the global coords of the moused-over elem
// Overlay the border sprite in the same position
var bounds:Rectangle = targ.getBounds(targ.parent);
var p:Point = new Point(bounds.x, bounds.y);
p = targ.parent.localToGlobal(p);
spr.x = p.x;
spr.y = p.y;
// Clear any previous border, and draw a new border
// the same size as the moused-over elem
spr.graphics.clear()
spr.graphics.lineStyle(2, 0x3875d7, 1);
spr.graphics.drawRect(0, 0, targ.width, targ.height);
// Generate the expression
var expr:String = WMLocator.generateLocator(targ);
if (expr.length) {
// Strip off trailing slash
expr = expr.replace(/\/$/, '');
var res:* = ExternalInterface.call('wm_explorerSelect', expr);
if (!res) {
WMLogger.log('Locator chain: ' + expr);
}
}
else {
throw new Error('Could not find any usable attributes for locator.');
}
}
public static function annihilateEvent(e:MouseEvent):void {
trace('Annihilating ' + e.type);
e.preventDefault();
e.stopImmediatePropagation();
}
}
}
|
Call removeEventListener with useCapture of true, since events were added with it.
|
Call removeEventListener with useCapture of true, since events were added with it.
|
ActionScript
|
apache-2.0
|
windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill,windmill/windmill
|
f4248581385f4dcdf657d2eaedc89ad266a80d29
|
src/org/puremvc/as3/demos/flex/weborb/login/view/LoginPanelMediator.as
|
src/org/puremvc/as3/demos/flex/weborb/login/view/LoginPanelMediator.as
|
/*
PureMVC Flex/WebORB Demo – Login
Copyright (c) 2007 Jens Krause <[email protected]> <www.websector.de>
Your reuse is governed by the Creative Commons Attribution 3.0 License
*/
package org.puremvc.as3.demos.flex.weborb.login.view
{
import flash.events.Event;
import org.puremvc.as3.demos.flex.weborb.login.ApplicationFacade;
import org.puremvc.as3.demos.flex.weborb.login.model.LoginProxy;
import org.puremvc.as3.demos.flex.weborb.login.model.vo.LoginVO;
import org.puremvc.as3.demos.flex.weborb.login.view.components.LoginPanel;
import org.puremvc.interfaces.*;
import org.puremvc.patterns.mediator.Mediator;
/**
* A Mediator for interacting with the LoginPanel component.
*/
public class LoginPanelMediator extends Mediator implements IMediator
{
private var loginProxy: LoginProxy;
public static const NAME:String = 'LoginPanelMediator';
/**
* Constructor.
* @param object the viewComponent
*/
public function LoginPanelMediator(viewComponent:Object)
{
super(viewComponent);
loginProxy = LoginProxy(facade.retrieveProxy(LoginProxy.NAME));
loginPanel.addEventListener( LoginPanel.LOGIN, login);
}
/**
* Get the Mediator name
*
* @return String the Mediator name
*/
override public function getMediatorName():String
{
return LoginPanelMediator.NAME;
}
/**
* List all notifications this Mediator is interested in.
*
* @return Array the list of Nofitication names
*/
override public function listNotificationInterests():Array
{
return [ ApplicationFacade.LOGIN_FAILED ];
}
/**
* Handle all notifications this Mediator is interested in.
*
* @param INotification a notification
*/
override public function handleNotification( note:INotification ):void
{
switch (note.getName())
{
case ApplicationFacade.LOGIN_FAILED:
loginFault(note.getBody());
break;
default:
}
}
/**
* The user has initiated to log in.
*/
private function login (event:Event=null):void
{
var loginVO: LoginVO = new LoginVO();
loginVO.username = loginPanel.username.text;
loginVO.password = loginPanel.password.text;
// loginProxy.getUser(loginVO);
sendNotification(ApplicationFacade.LOGIN, loginVO);
}
/**
* Shows an error message on login panel
* @param message
*/
private function loginFault (message: Object):void
{
loginPanel.statusMessage.htmlText = "<font color='#FF6600'>" + loginProxy.faultMessage + "</font>";
}
/**
* Cast the viewComponent to its actual type.
* @return app the viewComponent cast to LoginPanel
*/
protected function get loginPanel(): LoginPanel
{
return viewComponent as LoginPanel;
}
}
}
|
/*
PureMVC Flex/WebORB Demo – Login
Copyright (c) 2007 Jens Krause <[email protected]> <www.websector.de>
Your reuse is governed by the Creative Commons Attribution 3.0 License
*/
package org.puremvc.as3.demos.flex.weborb.login.view
{
import flash.events.Event;
import org.puremvc.as3.demos.flex.weborb.login.ApplicationFacade;
import org.puremvc.as3.demos.flex.weborb.login.model.LoginProxy;
import org.puremvc.as3.demos.flex.weborb.login.model.vo.LoginVO;
import org.puremvc.as3.demos.flex.weborb.login.view.components.LoginPanel;
import org.puremvc.interfaces.*;
import org.puremvc.patterns.mediator.Mediator;
/**
* A Mediator for interacting with the LoginPanel component.
*/
public class LoginPanelMediator extends Mediator implements IMediator
{
private var loginProxy: LoginProxy;
public static const NAME:String = 'LoginPanelMediator';
/**
* Constructor.
* @param object the viewComponent
*/
public function LoginPanelMediator(viewComponent:Object)
{
super(viewComponent);
loginProxy = LoginProxy(facade.retrieveProxy(LoginProxy.NAME));
loginPanel.addEventListener( LoginPanel.LOGIN, login);
}
/**
* Get the Mediator name
*
* @return String the Mediator name
*/
override public function getMediatorName():String
{
return LoginPanelMediator.NAME;
}
/**
* List all notifications this Mediator is interested in.
*
* @return Array the list of Nofitication names
*/
override public function listNotificationInterests():Array
{
return [ ApplicationFacade.LOGIN_FAILED ];
}
/**
* Handle all notifications this Mediator is interested in.
*
* @param INotification a notification
*/
override public function handleNotification( note:INotification ):void
{
switch (note.getName())
{
case ApplicationFacade.LOGIN_FAILED:
loginFault(note.getBody());
break;
default:
}
}
/**
* The user has initiated to log in.
*/
private function login (event:Event=null):void
{
var loginVO: LoginVO = new LoginVO();
loginVO.username = loginPanel.username.text;
loginVO.password = loginPanel.password.text;
sendNotification(ApplicationFacade.LOGIN, loginVO);
}
/**
* Shows an error message on login panel
* @param message
*/
private function loginFault (message: Object):void
{
loginPanel.statusMessage.htmlText = "<font color='#FF6600'>" + loginProxy.faultMessage + "</font>";
}
/**
* Cast the viewComponent to its actual type.
* @return app the viewComponent cast to LoginPanel
*/
protected function get loginPanel(): LoginPanel
{
return viewComponent as LoginPanel;
}
}
}
|
comment changed
|
comment changed
|
ActionScript
|
bsd-3-clause
|
PureMVC/puremvc-as3-demo-flex-weborb-login
|
42f0d078495ecda679c22bdd483fed43218b17a0
|
src/org/flintparticles/twoD/activities/FollowDisplayObject.as
|
src/org/flintparticles/twoD/activities/FollowDisplayObject.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.twoD.activities
{
import org.flintparticles.common.activities.ActivityBase;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.twoD.emitters.Emitter2D;
import flash.display.DisplayObject;
import flash.geom.Point;
/**
* The FollowDisplayObject activity causes the emitter to follow
* the position of a DisplayObject. The purpose is for the emitter
* to emit particles from the vicinity of the DisplayObject.
*/
public class FollowDisplayObject extends ActivityBase
{
private var _renderer:DisplayObject;
private var _displayObject:DisplayObject;
/**
* The constructor creates a FollowDisplayObject activity for use by
* an emitter. To add a FollowDisplayObject to an emitter, use the
* emitter's addActvity method.
*
* @param renderer The display object whose coordinate system the DisplayObject's position is
* converted to. This is usually the renderer for the particle system created by the emitter.
*
* @see org.flintparticles.common.emitters.Emitter#addActivity()
*/
public function FollowDisplayObject( displayObject:DisplayObject = null, renderer:DisplayObject = null )
{
this.displayObject = displayObject;
this.renderer = renderer;
}
/**
* The DisplayObject whose coordinate system the DisplayObject's position is converted to. This
* is usually the renderer for the particle system created by the emitter.
*/
public function get renderer():DisplayObject
{
return _renderer;
}
public function set renderer( value:DisplayObject ):void
{
_renderer = value;
}
/**
* The display object that the emitter follows.
*/
public function get displayObject():DisplayObject
{
return _displayObject;
}
public function set displayObject( value:DisplayObject ):void
{
_displayObject = value;
}
/**
* @inheritDoc
*/
override public function update( emitter : Emitter, time : Number ) : void
{
var e:Emitter2D = Emitter2D( emitter );
var p:Point = new Point( 0, 0 );
p = _displayObject.localToGlobal( p );
p = _renderer.globalToLocal( p );
e.x = p.x;
e.y = p.y;
}
}
}
|
/*
* 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.twoD.activities
{
import org.flintparticles.common.utils.DisplayObjectUtils;
import org.flintparticles.common.activities.ActivityBase;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.twoD.emitters.Emitter2D;
import flash.display.DisplayObject;
import flash.geom.Point;
/**
* The FollowDisplayObject activity causes the emitter to follow
* the position and rotation of a DisplayObject. The purpose is for the emitter
* to emit particles from the location of the DisplayObject.
*/
public class FollowDisplayObject extends ActivityBase
{
private var _renderer:DisplayObject;
private var _displayObject:DisplayObject;
/**
* The constructor creates a FollowDisplayObject activity for use by
* an emitter. To add a FollowDisplayObject to an emitter, use the
* emitter's addActvity method.
*
* @param renderer The display object whose coordinate system the DisplayObject's position is
* converted to. This is usually the renderer for the particle system created by the emitter.
*
* @see org.flintparticles.common.emitters.Emitter#addActivity()
*/
public function FollowDisplayObject( displayObject:DisplayObject = null, renderer:DisplayObject = null )
{
this.displayObject = displayObject;
this.renderer = renderer;
}
/**
* The DisplayObject whose coordinate system the DisplayObject's position is converted to. This
* is usually the renderer for the particle system created by the emitter.
*/
public function get renderer():DisplayObject
{
return _renderer;
}
public function set renderer( value:DisplayObject ):void
{
_renderer = value;
}
/**
* The display object that the emitter follows.
*/
public function get displayObject():DisplayObject
{
return _displayObject;
}
public function set displayObject( value:DisplayObject ):void
{
_displayObject = value;
}
/**
* @inheritDoc
*/
override public function update( emitter : Emitter, time : Number ) : void
{
var e:Emitter2D = Emitter2D( emitter );
var p:Point = new Point( 0, 0 );
p = _displayObject.localToGlobal( p );
p = _renderer.globalToLocal( p );
var r:Number = 0;
r = DisplayObjectUtils.localToGlobalRotation( _displayObject, r );
r = DisplayObjectUtils.globalToLocalRotation( _renderer, r );
e.x = p.x;
e.y = p.y;
e.rotation = r;
}
}
}
|
Add rotation to the FollowDisplayObject activity
|
Add rotation to the FollowDisplayObject activity
|
ActionScript
|
mit
|
richardlord/Flint
|
3faf6fb001265002247a6c1f8b0d86861914d77f
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
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.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
if (value != _frustumCulling)
{
_frustumCulling = value;
if (value == FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
if (_mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler))
{
_mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
}
}
else if (_mesh && _mesh.scene)
{
_mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
testCulling();
}
}
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider(
{ computedVisibility : true },
'MeshVisibilityDataProvider',
DataProviderUsage.EXCLUSIVE
);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
{
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
}
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
bindingName : String,
oldValue : Matrix4x4,
value : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (_mesh && _mesh.geometry && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
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.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
if (value != _frustumCulling)
{
_frustumCulling = value;
if (value == FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
if (_mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler))
_mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
}
else if (_mesh && _mesh.scene)
{
_mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
testCulling();
}
}
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider(
{ computedVisibility : true },
'MeshVisibilityDataProvider',
DataProviderUsage.EXCLUSIVE
);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
{
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
}
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
bindingName : String,
oldValue : Matrix4x4,
value : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (_mesh && _mesh.geometry && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
remove useless brackets
|
remove useless brackets
|
ActionScript
|
mit
|
aerys/minko-as3
|
b9151e11051c229a5f4a0c0f981baa47dcf6d196
|
src/com/esri/builder/views/supportClasses/PopUpInfoUtil.as
|
src/com/esri/builder/views/supportClasses/PopUpInfoUtil.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.views.supportClasses
{
import com.esri.ags.layers.supportClasses.Field;
import com.esri.ags.portal.supportClasses.PopUpFieldFormat;
import com.esri.ags.portal.supportClasses.PopUpFieldInfo;
import com.esri.ags.portal.supportClasses.PopUpMediaInfo;
public final class PopUpInfoUtil
{
public static function popUpFieldInfosFromXML(fieldsXML:XMLList):Array
{
var fields:Array = [];
for each (var fieldXML:XML in fieldsXML)
{
fields.push(popUpFieldInfoFromXML(fieldXML));
}
return fields;
}
private static function popUpFieldInfoFromXML(fieldXML:XML):PopUpFieldInfo
{
var popUpFieldInfo:PopUpFieldInfo = new PopUpFieldInfo();
popUpFieldInfo.fieldName = fieldXML.@name;
popUpFieldInfo.label = (fieldXML.@alias[0]) ? fieldXML.@alias : fieldXML.@name;
popUpFieldInfo.visible = (fieldXML.@visible[0] == "true");
if (fieldXML.format[0])
{
popUpFieldInfo.format = popUpFieldFormatFromXML(fieldXML.format[0]);
}
return popUpFieldInfo;
}
private static function popUpFieldFormatFromXML(formatXML:XML):PopUpFieldFormat
{
var popUpFieldFormat:PopUpFieldFormat = new PopUpFieldFormat();
if (formatXML.@dateformat[0])
{
popUpFieldFormat.dateFormat = formatXML.@dateformat;
}
popUpFieldFormat.precision = formatXML.@precision[0] ? formatXML.@precision : -1;
popUpFieldFormat.useThousandsSeparator = (formatXML.@usethousandsseparator == "true");
popUpFieldFormat.useUTC = (formatXML.@useutc == "true");
return popUpFieldFormat;
}
public static function popUpMediaInfosFromXML(mediasXML:XMLList):Array
{
var medias:Array = [];
for each (var mediaXML:XML in mediasXML)
{
medias.push(popUpMediaInfoFromXML(mediaXML));
}
return medias;
}
private static function popUpMediaInfoFromXML(mediaXML:XML):PopUpMediaInfo
{
var popUpMediaInfo:PopUpMediaInfo = new PopUpMediaInfo();
popUpMediaInfo.type = mediaXML.@type;
popUpMediaInfo.title = mediaXML.@title;
popUpMediaInfo.caption = mediaXML.@caption;
popUpMediaInfo.imageLinkURL = mediaXML.@imagelink;
popUpMediaInfo.imageSourceURL = mediaXML.@imagesource;
if (mediaXML.@chartfields[0])
{
popUpMediaInfo.chartFields = [email protected](',');
}
popUpMediaInfo.chartNormalizationField = mediaXML.@chartnormalizationfield;
return popUpMediaInfo;
}
public static function popUpMediaInfosToXML(medias:Array):XML
{
var mediasXML:XML = <medias/>;
var mediaXML:XML;
for each (var popUpMediaInfo:PopUpMediaInfo in medias)
{
mediaXML = <media/>;
if (popUpMediaInfo.type)
{
mediaXML.@type = popUpMediaInfo.type;
}
if (popUpMediaInfo.title)
{
mediaXML.@title = popUpMediaInfo.title;
}
if (popUpMediaInfo.caption)
{
mediaXML.@caption = popUpMediaInfo.caption;
}
if (popUpMediaInfo.imageLinkURL)
{
mediaXML.@imagelink = popUpMediaInfo.imageLinkURL;
}
if (popUpMediaInfo.imageSourceURL)
{
mediaXML.@imagesource = popUpMediaInfo.imageSourceURL;
}
if (popUpMediaInfo.chartFields)
{
mediaXML.@chartfields = popUpMediaInfo.chartFields;
}
mediasXML.appendChild(mediaXML);
}
return mediasXML;
}
public static function popUpFieldInfosToXML(fields:Array):XML
{
var fieldsXML:XML = <fields/>;
var fieldXML:XML;
for each (var popUpFieldInfo:PopUpFieldInfo in fields)
{
fieldXML = <field/>;
if (popUpFieldInfo.fieldName)
{
fieldXML.@name = popUpFieldInfo.fieldName;
}
if (popUpFieldInfo.label)
{
fieldXML.@alias = popUpFieldInfo.label;
}
if (popUpFieldInfo.visible)
{
fieldXML.@visible = popUpFieldInfo.visible;
}
fieldsXML.appendChild(fieldXML);
}
return fieldsXML;
}
public static function popUpFieldInfosFromFields(fields:Array):Array
{
var popUpFieldInfos:Array = [];
var popUpFieldInfo:PopUpFieldInfo;
for each (var field:Field in fields)
{
popUpFieldInfo = new PopUpFieldInfo();
popUpFieldInfo.fieldName = field.name;
popUpFieldInfo.label = field.alias;
popUpFieldInfos.push(popUpFieldInfo);
}
return popUpFieldInfos;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// 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.views.supportClasses
{
import com.esri.ags.layers.supportClasses.Field;
import com.esri.ags.portal.supportClasses.PopUpFieldFormat;
import com.esri.ags.portal.supportClasses.PopUpFieldInfo;
import com.esri.ags.portal.supportClasses.PopUpMediaInfo;
public final class PopUpInfoUtil
{
public static function popUpFieldInfosFromXML(fieldsXML:XMLList):Array
{
var fields:Array = [];
for each (var fieldXML:XML in fieldsXML)
{
fields.push(popUpFieldInfoFromXML(fieldXML));
}
return fields;
}
private static function popUpFieldInfoFromXML(fieldXML:XML):PopUpFieldInfo
{
var popUpFieldInfo:PopUpFieldInfo = new PopUpFieldInfo();
popUpFieldInfo.fieldName = fieldXML.@name;
popUpFieldInfo.label = (fieldXML.@alias[0]) ? fieldXML.@alias : fieldXML.@name;
popUpFieldInfo.visible = (fieldXML.@visible[0] == "true");
if (fieldXML.format[0])
{
popUpFieldInfo.format = popUpFieldFormatFromXML(fieldXML.format[0]);
}
return popUpFieldInfo;
}
private static function popUpFieldFormatFromXML(formatXML:XML):PopUpFieldFormat
{
var popUpFieldFormat:PopUpFieldFormat = new PopUpFieldFormat();
if (formatXML.@dateformat[0])
{
popUpFieldFormat.dateFormat = formatXML.@dateformat;
}
popUpFieldFormat.precision = formatXML.@precision[0] ? formatXML.@precision : -1;
popUpFieldFormat.useThousandsSeparator = (formatXML.@usethousandsseparator == "true");
popUpFieldFormat.useUTC = (formatXML.@useutc == "true");
return popUpFieldFormat;
}
public static function popUpMediaInfosFromXML(mediasXML:XMLList):Array
{
var medias:Array = [];
for each (var mediaXML:XML in mediasXML)
{
medias.push(popUpMediaInfoFromXML(mediaXML));
}
return medias;
}
private static function popUpMediaInfoFromXML(mediaXML:XML):PopUpMediaInfo
{
var popUpMediaInfo:PopUpMediaInfo = new PopUpMediaInfo();
popUpMediaInfo.type = mediaXML.@type;
popUpMediaInfo.title = mediaXML.@title;
popUpMediaInfo.caption = mediaXML.@caption;
popUpMediaInfo.imageLinkURL = mediaXML.@imagelink;
popUpMediaInfo.imageSourceURL = mediaXML.@imagesource;
if (mediaXML.@chartfields[0])
{
popUpMediaInfo.chartFields = [email protected](',');
}
popUpMediaInfo.chartNormalizationField = mediaXML.@chartnormalizationfield;
return popUpMediaInfo;
}
public static function popUpMediaInfosToXML(medias:Array):XML
{
var mediasXML:XML = <medias/>;
var mediaXML:XML;
for each (var popUpMediaInfo:PopUpMediaInfo in medias)
{
mediaXML = <media/>;
if (popUpMediaInfo.type)
{
mediaXML.@type = popUpMediaInfo.type;
}
if (popUpMediaInfo.title)
{
mediaXML.@title = popUpMediaInfo.title;
}
if (popUpMediaInfo.caption)
{
mediaXML.@caption = popUpMediaInfo.caption;
}
if (popUpMediaInfo.imageLinkURL)
{
mediaXML.@imagelink = popUpMediaInfo.imageLinkURL;
}
if (popUpMediaInfo.imageSourceURL)
{
mediaXML.@imagesource = popUpMediaInfo.imageSourceURL;
}
if (popUpMediaInfo.chartFields)
{
mediaXML.@chartfields = popUpMediaInfo.chartFields;
}
mediasXML.appendChild(mediaXML);
}
return mediasXML;
}
public static function popUpFieldInfosToXML(fields:Array):XML
{
var fieldsXML:XML = <fields/>;
var fieldXML:XML;
for each (var popUpFieldInfo:PopUpFieldInfo in fields)
{
fieldXML = <field/>;
if (popUpFieldInfo.fieldName)
{
fieldXML.@name = popUpFieldInfo.fieldName;
}
if (popUpFieldInfo.label)
{
fieldXML.@alias = popUpFieldInfo.label;
}
if (popUpFieldInfo.visible)
{
fieldXML.@visible = popUpFieldInfo.visible;
}
if (popUpFieldInfo.format)
{
fieldXML.appendChild(popUpFieldFormatToXML(popUpFieldInfo.format));
}
fieldsXML.appendChild(fieldXML);
}
return fieldsXML;
}
private static function popUpFieldFormatToXML(format:PopUpFieldFormat):XML
{
var formatXML:XML = <format precision={format.precision}
usethousandsseparator={format.useThousandsSeparator}
useutc={format.useUTC}/>;
var dateFormat:String = format.dateFormat;
if (dateFormat)
{
formatXML.@dateformat = dateFormat;
}
return formatXML;
}
public static function popUpFieldInfosFromFields(fields:Array):Array
{
var popUpFieldInfos:Array = [];
var popUpFieldInfo:PopUpFieldInfo;
for each (var field:Field in fields)
{
popUpFieldInfo = new PopUpFieldInfo();
popUpFieldInfo.fieldName = field.name;
popUpFieldInfo.label = field.alias;
popUpFieldInfos.push(popUpFieldInfo);
}
return popUpFieldInfos;
}
}
}
|
Update PopUpInfoUtil#popUpFieldInfosToXML() to include pop-up field format.
|
Update PopUpInfoUtil#popUpFieldInfosToXML() to include pop-up field format.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
023bdb3934bc1d14bb199591ce321155f1c695dd
|
skinnable-popup-fx/src/main/actionscript/net/riastar/components/Toaster.as
|
skinnable-popup-fx/src/main/actionscript/net/riastar/components/Toaster.as
|
/*
* Copyright (c) 2013 Maxime Cowez a.k.a. RIAstar.
*
* 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 NON-INFRINGEMENT. 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.
*/
/**
* @author RIAstar
*/
package net.riastar.components {
import flash.events.TimerEvent;
import flash.utils.Dictionary;
import flash.utils.Timer;
import mx.collections.ArrayList;
import mx.collections.IList;
import mx.core.IDataRenderer;
import mx.core.IFactory;
import mx.core.IVisualElement;
import mx.effects.Effect;
import mx.events.EffectEvent;
import mx.events.ResizeEvent;
import net.riastar.components.supportClasses.PopUpAbsolutePosition;
import spark.components.DataGroup;
import spark.components.supportClasses.ListBase;
import spark.events.IndexChangeEvent;
import spark.events.RendererExistenceEvent;
import spark.events.SkinPartEvent;
public class Toaster extends SkinnablePopUp {
/* ----------------- */
/* --- skinparts --- */
/* ----------------- */
[SkinPart(required="true")]
public var messageList:ListBase;
[SkinPart(required="false")]
public var rendererCreationEffect:Effect;
[SkinPart(required="false")]
public var rendererDestructionEffect:Effect;
/* ------------------ */
/* --- properties --- */
/* ------------------ */
public var showTime:int = 5000;
private var _labelField:String;
public function get labelField():String { return _labelField; }
public function set labelField(value:String):void {
_labelField = value;
if (messageList) messageList.labelField = value;
}
private var _labelFunction:Function;
public function get labelFunction():Function { return _labelFunction; }
public function set labelFunction(value:Function):void {
_labelFunction = value;
if (messageList) messageList.labelFunction = value;
}
private var _itemRenderer:IFactory;
public function get itemRenderer():IFactory { return _itemRenderer; }
public function set itemRenderer(value:IFactory):void {
_itemRenderer = value;
if (messageList) messageList.itemRenderer = value;
}
private var messages:IList = new ArrayList();
private var timerMap:Dictionary = new Dictionary();
/* -------------------- */
/* --- construction --- */
/* -------------------- */
override public function initialize():void {
position = new PopUpAbsolutePosition();
super.initialize();
}
override protected function partAdded(partName:String, instance:Object):void {
super.partAdded(partName, instance);
switch (instance) {
case messageList:
initMessageList();
break;
case rendererDestructionEffect:
rendererDestructionEffect.addEventListener(EffectEvent.EFFECT_END, handleDestructionEffectEnd);
break;
}
}
private function initMessageList():void {
messageList.labelField = _labelField;
messageList.labelFunction = _labelFunction;
messageList.dataProvider = messages;
if (_itemRenderer) messageList.itemRenderer = _itemRenderer;
else _itemRenderer = messageList.itemRenderer;
messageList.addEventListener(IndexChangeEvent.CHANGE, handleMessageSelection);
messageList.addEventListener(ResizeEvent.RESIZE, handleListResize);
messageList.addEventListener(SkinPartEvent.PART_ADDED, initRendererListeners);
}
private function initRendererListeners(event:SkinPartEvent):void {
if (!(event.instance is DataGroup)) return;
messageList.removeEventListener(SkinPartEvent.PART_ADDED, initRendererListeners);
messageList.dataGroup.addEventListener(RendererExistenceEvent.RENDERER_ADD, handleItemRendererAdded);
}
/* ---------------------- */
/* --- event handlers --- */
/* ---------------------- */
private function handleMessageSelection(event:IndexChangeEvent):void {
//TODO handle toast selection
}
private function handleTimerComplete(event:TimerEvent):void {
var timer:Timer = event.currentTarget as Timer;
removeToast(timerMap[timer], true);
destroyTimer(timer);
}
private function handleListResize(event:ResizeEvent):void {
position.update(this);
}
private function handleItemRendererAdded(event:RendererExistenceEvent):void {
playCreationEffect(event.renderer);
}
private function handleDestructionEffectEnd(event:EffectEvent):void {
var itemRenderer:IDataRenderer = event.effectInstance.target as IDataRenderer;
removeToast(itemRenderer.data, false);
}
/* ----------------- */
/* --- behaviour --- */
/* ----------------- */
public function toast(item:Object):void {
messages.addItem(item);
createTimer(item);
invalidateState();
}
protected function removeToast(item:Object, playEffect:Boolean):void {
var index:int = messages.getItemIndex(item);
if (index == -1) return;
var itemRenderer:IVisualElement = messageList.dataGroup.getElementAt(index);
if (!playEffect || !playDestructionEffect(itemRenderer)) {
messages.removeItemAt(index);
invalidateState();
}
}
protected function playCreationEffect(itemRenderer:IVisualElement):Boolean {
if (rendererCreationEffect) rendererCreationEffect.play([itemRenderer]);
return rendererCreationEffect != null;
}
protected function playDestructionEffect(itemRenderer:IVisualElement):Boolean {
if (rendererDestructionEffect) rendererDestructionEffect.play([itemRenderer]);
return rendererDestructionEffect != null;
}
protected function createTimer(item:Object):void {
var timer:Timer = new Timer(showTime, 1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, handleTimerComplete);
timerMap[timer] = item;
timer.start();
}
protected function destroyTimer(timer:Timer):void {
timer.removeEventListener(TimerEvent.TIMER_COMPLETE, handleTimerComplete);
delete timerMap[timer];
timer = null;
}
protected function invalidateState():void {
messages.length ? open() : close();
}
}
}
|
/*
* Copyright (c) 2013 Maxime Cowez a.k.a. RIAstar.
*
* 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 NON-INFRINGEMENT. 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.
*/
/**
* @author RIAstar
*/
package net.riastar.components {
import flash.events.TimerEvent;
import flash.utils.Dictionary;
import flash.utils.Timer;
import mx.collections.ArrayList;
import mx.collections.IList;
import mx.core.IDataRenderer;
import mx.core.IFactory;
import mx.core.IVisualElement;
import mx.effects.Effect;
import mx.events.EffectEvent;
import mx.events.ResizeEvent;
import net.riastar.components.supportClasses.PopUpAbsolutePosition;
import spark.components.DataGroup;
import spark.components.supportClasses.ListBase;
import spark.events.IndexChangeEvent;
import spark.events.RendererExistenceEvent;
import spark.events.SkinPartEvent;
public class Toaster extends SkinnablePopUp {
/* ----------------- */
/* --- skinparts --- */
/* ----------------- */
[SkinPart(required="true")]
public var messageList:ListBase;
[SkinPart(required="false")]
public var rendererCreationEffect:Effect;
[SkinPart(required="false")]
public var rendererDestructionEffect:Effect;
/* ------------------ */
/* --- properties --- */
/* ------------------ */
public var showTime:int = 5000;
private var _labelField:String;
public function get labelField():String { return _labelField; }
public function set labelField(value:String):void {
_labelField = value;
if (messageList) messageList.labelField = value;
}
private var _labelFunction:Function;
public function get labelFunction():Function { return _labelFunction; }
public function set labelFunction(value:Function):void {
_labelFunction = value;
if (messageList) messageList.labelFunction = value;
}
private var _itemRenderer:IFactory;
public function get itemRenderer():IFactory { return _itemRenderer; }
public function set itemRenderer(value:IFactory):void {
_itemRenderer = value;
if (messageList) messageList.itemRenderer = value;
}
private var messages:IList = new ArrayList();
private var timerMap:Dictionary = new Dictionary();
/* -------------------- */
/* --- construction --- */
/* -------------------- */
override public function initialize():void {
position = new PopUpAbsolutePosition();
super.initialize();
}
override protected function partAdded(partName:String, instance:Object):void {
super.partAdded(partName, instance);
switch (instance) {
case messageList:
initMessageList();
break;
case rendererDestructionEffect:
rendererDestructionEffect.addEventListener(EffectEvent.EFFECT_END, handleDestructionEffectEnd);
break;
}
}
private function initMessageList():void {
messageList.labelField = _labelField;
messageList.labelFunction = _labelFunction;
messageList.dataProvider = messages;
if (_itemRenderer) messageList.itemRenderer = _itemRenderer;
else _itemRenderer = messageList.itemRenderer;
messageList.addEventListener(IndexChangeEvent.CHANGE, handleMessageSelection);
messageList.addEventListener(ResizeEvent.RESIZE, handleListResize);
messageList.addEventListener(SkinPartEvent.PART_ADDED, initRendererListeners);
}
private function initRendererListeners(event:SkinPartEvent):void {
if (!(event.instance is DataGroup)) return;
messageList.removeEventListener(SkinPartEvent.PART_ADDED, initRendererListeners);
messageList.dataGroup.addEventListener(RendererExistenceEvent.RENDERER_ADD, handleItemRendererAdded);
}
/* ---------------------- */
/* --- event handlers --- */
/* ---------------------- */
private function handleMessageSelection(event:IndexChangeEvent):void {
//TODO handle toast selection
}
private function handleTimerComplete(event:TimerEvent):void {
var timer:Timer = event.currentTarget as Timer;
removeToast(timerMap[timer], true);
destroyTimer(timer);
}
private function handleListResize(event:ResizeEvent):void {
position.update(this);
}
private function handleItemRendererAdded(event:RendererExistenceEvent):void {
playCreationEffect(event.renderer);
}
private function handleDestructionEffectEnd(event:EffectEvent):void {
var itemRenderer:IDataRenderer = event.effectInstance.target as IDataRenderer;
removeToast(itemRenderer.data, false);
}
/* ----------------- */
/* --- behaviour --- */
/* ----------------- */
public function toast(item:Object):void {
messages.addItem(item);
createTimer(item);
invalidateState();
}
protected function removeToast(item:Object, playEffect:Boolean):void {
var index:int = messages.getItemIndex(item);
if (index == -1) return;
var itemRenderer:IVisualElement = messageList.dataGroup.getElementAt(index);
if (!playEffect || !playDestructionEffect(itemRenderer)) {
messages.removeItemAt(index);
invalidateState();
}
}
protected function playCreationEffect(itemRenderer:IVisualElement):Boolean {
if (rendererCreationEffect) rendererCreationEffect.play([itemRenderer]);
return rendererCreationEffect != null;
}
protected function playDestructionEffect(itemRenderer:IVisualElement):Boolean {
if (rendererDestructionEffect) rendererDestructionEffect.play([itemRenderer]);
return rendererDestructionEffect != null;
}
protected function createTimer(item:Object):void {
var timer:Timer = new Timer(showTime, 1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, handleTimerComplete);
timerMap[timer] = item;
timer.start();
}
protected function destroyTimer(timer:Timer):void {
timer.removeEventListener(TimerEvent.TIMER_COMPLETE, handleTimerComplete);
delete timerMap[timer];
timer = null;
}
protected function invalidateState():void {
messages.length ? open() : close();
}
/* ------------------- */
/* --- destruction --- */
/* ------------------- */
override protected function partRemoved(partName:String, instance:Object):void {
switch (instance) {
case messageList:
messageList.dataGroup.removeEventListener(RendererExistenceEvent.RENDERER_ADD, handleItemRendererAdded);
messageList.removeEventListener(IndexChangeEvent.CHANGE, handleMessageSelection);
messageList.removeEventListener(ResizeEvent.RESIZE, handleListResize);
break;
case rendererDestructionEffect:
rendererDestructionEffect.removeEventListener(EffectEvent.EFFECT_END, handleDestructionEffectEnd);
break;
}
super.partRemoved(partName, instance);
}
}
}
|
clean up event listeners
|
clean up event listeners
|
ActionScript
|
apache-2.0
|
RIAstar/SkinnablePopUpFx,RIAstar/SkinnablePopUpFx
|
f9dad07b8f1113582b4aabedd3fb8148ccdd2f2e
|
actionscript/com/hipchat/Linkify.as
|
actionscript/com/hipchat/Linkify.as
|
package com.hipchat {
public class Linkify {
public static const RE_EMAIL_PATTERN:String = '(?<=\\s|\\A)[\\w.-]+\\+*[\\w.-]+@(?:(?:[\\w-]+\\.)+[A-Za-z]{2,6}|(?:\\d{1,3}\\.){3}\\d{1,3})';
public static const RE_TLD:String = '(?:aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)'; // Top level domains
public static const RE_URL_MIDCHAR:String = '[^\\s<>]'; // characters allowed in URL center
public static const RE_URL_ENDCHAR:String = '[\\w@?^=%&/~\+#-]'; // URL must end with one of these chars
public static const RE_URL_ENDING:String = '(?:'+RE_URL_MIDCHAR+'*'+RE_URL_ENDCHAR+')?';
public static const RE_URL_SCHEME:String = '(?:http|ftp|https|news|mms)://';
// If we have the scheme/protocol, always linkify (don't require a valid TLD)
public static const RE_FULL_URL:String = RE_URL_SCHEME+'\\w+(?:.\\w+)'+RE_URL_ENDING;
// URLs not starting with a protocol (e.g. www.google.com instead of http://www.google.com)
public static const RE_OTHER_URL:String = '\\w[\\w_-]*(?:\\.\\w[\\w_-]*)*\\.'+RE_TLD+'(?:\\/'+RE_URL_ENDING+')?\\b';
// Text to turn in to emoticon images
// emoticons.regex is a pattern to be used in the RegExp constructor
// emoticons.shortcut is the text actually typed to get the emoticon
// Width and height provided to avoid jittering as images load
private static const emoticons:Array = [
{regex: ':-?D', shortcut: ':D', width: 18, height: 18, image: 'bigsmile.png'},
{regex: ':-?o', shortcut: ':o', width: 18, height: 18, image: 'gasp.png'},
{regex: ':-?p', shortcut: ':p', width: 18, height: 18, image: 'tongue.png'},
{regex: '8-?\\)', shortcut: '8)', width: 18, height: 18, image: 'cool.png'},
{regex: ':-?\\(', shortcut: ':(', width: 18, height: 18, image: 'frown.png'},
{regex: ':-\\*', shortcut: ':-*', width: 18, height: 18, image: 'kiss.png'},
{regex: ':\\\\', shortcut: ':\\', width: 18, height: 18, image: 'slant.png'},
{regex: ':-?\\)', shortcut: ':)', width: 18, height: 18, image: 'smile.png'},
{regex: ':-?\\|', shortcut: ':|', width: 18, height: 18, image: 'straightface.png'},
{regex: ';-?\\)', shortcut: ';)', width: 18, height: 18, image: 'wink.png'}];
/**
* Linkify a string, replacing text urls with <a href="url">url</a>
*
* @param text - String to be linkified
* @param emoticonify - Whether to replace text emoticons with images
* @param dispatchEvent - Whether to dispatch a link: event (to be handled in actionscript)
* see: http://blog.flexexamples.com/2008/01/26/listening-for-the-link-event-in-a-flex-label-control/
* see: http://livedocs.adobe.com/flex/3/html/help.html?content=textcontrols_04.html
* @param matchedLinks - Return param (pass by ref) - Array of links matched during linkification
**/
public static function linkify(text:String,
emoticonify:Boolean = true,
dispatchEvent:Boolean = false,
truncateLength:uint = 0,
matchedLinks:Array = null):String {
text = Linkify.matchAndReplace(RE_EMAIL_PATTERN, text, false, false, dispatchEvent, truncateLength, matchedLinks);
text = Linkify.matchAndReplace(RE_FULL_URL, text, true, false, dispatchEvent, truncateLength, matchedLinks);
text = Linkify.matchAndReplace(RE_OTHER_URL, text, true, true, dispatchEvent, truncateLength, matchedLinks);
if (emoticonify)
text = Linkify.emoticonText(text);
return text;
}
/**
* Internal helper function for linkification
**/
private static function matchAndReplace(pattern:String,
input:String,
isURL:Boolean = false,
addHTTP:Boolean = true,
dispatchEvent:Boolean = false,
truncateLength:uint = 0,
matchedLinks:Array = null):String {
var start:int = 0;
var offset:int = 0;
var matchLength:int = 0;
var endTagPos:int = 0;
var closeAnchorRe:RegExp = /<\/[aA]>/;
var re:RegExp = new RegExp(pattern, "g");
var match:Object = new Object();
// Limit the number of links we match in one pass
var maxIter:int = 20;
var curIter:int = 0;
while (match = re.exec(input)) {
curIter++;
if (curIter > maxIter)
break;
start = match.index; // start of match
matchLength = match[0].length;
// If we find an opening anchor tag, advance to its end and continue looking
var substr:String = input.substring(offset, start);
if (substr.search(/<[aA]/) >= 0) {
// Find the closing anchor tag
closeAnchorRe.lastIndex = offset;
var closeAnchorPos:int = input.substring(offset, input.length).search(closeAnchorRe);
// If we find an opening tag without a closing match, just return the current input
if (closeAnchorPos < 0)
return input;
endTagPos = closeAnchorPos + offset;
// RegExp.lastIndex is used to tell the regexp where to start matching
re.lastIndex = endTagPos + 4;
offset = endTagPos + 4;
continue;
}
// Do the replacement of url text with anchor tag
var address:String = input.substr(start, matchLength);
var actual:String = input.substr(start, matchLength);
if (addHTTP) {
actual = 'http://'+actual;
}
var replacement:String = '<a href="';
if (dispatchEvent) {
replacement += 'event:';
} else if (!isURL) {
replacement += 'mailto:';
}
replacement += actual.replace(new RegExp('"', 'g'), '%22')+'"';
if (truncateLength && address.length > truncateLength) {
address = address.substr(0, truncateLength) + '...';
}
// Add word break tags to allow wrapping where appropriate
// Manually put font styles around the link so they actually look like links
// see: http://livedocs.adobe.com/flex/3/html/help.html?content=textcontrols_04.html
replacement += '><font color="#0000ff"><u>'+address.replace(new RegExp("([/=&])", 'g'), "<wbr>$1")+'</u></font></a>';
if (matchedLinks) {
matchedLinks.push(actual);
}
input = input.slice(0, start) + replacement + input.slice(start+matchLength, input.length);
re.lastIndex = start + replacement.length;
offset = start + replacement.length;
}
return input;
}
/**
* Replace text emoticons with images
**/
private static function emoticonText(text:String):String {
for each (var eData:Object in Linkify.emoticons) {
var regex:String = eData.regex;
var img:String = eData.image;
// (not a word character)(smiley regex)(not a word character)
var pattern:RegExp = new RegExp('(?<!\\w)'+regex+'(?!\\w)', 'gim');
text = text.replace(pattern, '<img name="emoticon" alt="'+eData.shortcut+'" height="'+eData.height+'" width="'+eData.width+'" src="http://emoticon-hosting-site/'+img+'" />');
}
return text;
}
}
}
|
package com.hipchat {
public class Linkify {
public static const RE_EMAIL_PATTERN:String = '(?<=\\s|\\A)[\\w.-]+\\+*[\\w.-]+@(?:(?:[\\w-]+\\.)+[A-Za-z]{2,6}|(?:\\d{1,3}\\.){3}\\d{1,3})';
public static const RE_TLD:String = '(?:aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)'; // Top level domains
public static const RE_URL_MIDCHAR:String = '[^\\s<>]'; // characters allowed in URL center
public static const RE_URL_ENDCHAR:String = '[\\w@?^=%&/~\+#-]'; // URL must end with one of these chars
public static const RE_URL_ENDING:String = '(?:'+RE_URL_MIDCHAR+'*'+RE_URL_ENDCHAR+')?';
public static const RE_URL_SCHEME:String = '(?:http|ftp|https|news|mms)://';
// If we have the scheme/protocol, always linkify (don't require a valid TLD)
public static const RE_FULL_URL:String = RE_URL_SCHEME+'\\w+(?:.\\w+)'+RE_URL_ENDING;
// URLs not starting with a protocol (e.g. www.google.com instead of http://www.google.com)
public static const RE_OTHER_URL:String = '\\w[\\w_-]*(?:\\.\\w[\\w_-]*)*\\.'+RE_TLD+'(?:\\/'+RE_URL_ENDING+')?';
// Text to turn in to emoticon images
// emoticons.regex is a pattern to be used in the RegExp constructor
// emoticons.shortcut is the text actually typed to get the emoticon
// Width and height provided to avoid jittering as images load
private static const emoticons:Array = [
{regex: ':-?D', shortcut: ':D', width: 18, height: 18, image: 'bigsmile.png'},
{regex: ':-?o', shortcut: ':o', width: 18, height: 18, image: 'gasp.png'},
{regex: ':-?p', shortcut: ':p', width: 18, height: 18, image: 'tongue.png'},
{regex: '8-?\\)', shortcut: '8)', width: 18, height: 18, image: 'cool.png'},
{regex: ':-?\\(', shortcut: ':(', width: 18, height: 18, image: 'frown.png'},
{regex: ':-\\*', shortcut: ':-*', width: 18, height: 18, image: 'kiss.png'},
{regex: ':\\\\', shortcut: ':\\', width: 18, height: 18, image: 'slant.png'},
{regex: ':-?\\)', shortcut: ':)', width: 18, height: 18, image: 'smile.png'},
{regex: ':-?\\|', shortcut: ':|', width: 18, height: 18, image: 'straightface.png'},
{regex: ';-?\\)', shortcut: ';)', width: 18, height: 18, image: 'wink.png'}];
/**
* Linkify a string, replacing text urls with <a href="url">url</a>
*
* @param text - String to be linkified
* @param emoticonify - Whether to replace text emoticons with images
* @param dispatchEvent - Whether to dispatch a link: event (to be handled in actionscript)
* see: http://blog.flexexamples.com/2008/01/26/listening-for-the-link-event-in-a-flex-label-control/
* see: http://livedocs.adobe.com/flex/3/html/help.html?content=textcontrols_04.html
* @param matchedLinks - Return param (pass by ref) - Array of links matched during linkification
**/
public static function linkify(text:String,
emoticonify:Boolean = true,
dispatchEvent:Boolean = false,
truncateLength:uint = 0,
matchedLinks:Array = null):String {
text = Linkify.matchAndReplace(RE_EMAIL_PATTERN, text, false, false, dispatchEvent, truncateLength, matchedLinks);
text = Linkify.matchAndReplace(RE_FULL_URL, text, true, false, dispatchEvent, truncateLength, matchedLinks);
text = Linkify.matchAndReplace(RE_OTHER_URL, text, true, true, dispatchEvent, truncateLength, matchedLinks);
if (emoticonify)
text = Linkify.emoticonText(text);
return text;
}
/**
* Internal helper function for linkification
**/
private static function matchAndReplace(pattern:String,
input:String,
isURL:Boolean = false,
addHTTP:Boolean = true,
dispatchEvent:Boolean = false,
truncateLength:uint = 0,
matchedLinks:Array = null):String {
var start:int = 0;
var offset:int = 0;
var matchLength:int = 0;
var endTagPos:int = 0;
var closeAnchorRe:RegExp = /<\/[aA]>/;
var re:RegExp = new RegExp(pattern, "g");
var match:Object = new Object();
// Limit the number of links we match in one pass
var maxIter:int = 20;
var curIter:int = 0;
while (match = re.exec(input)) {
curIter++;
if (curIter > maxIter)
break;
start = match.index; // start of match
matchLength = match[0].length;
// If we find an opening anchor tag, advance to its end and continue looking
var substr:String = input.substring(offset, start);
if (substr.search(/<[aA]/) >= 0) {
// Find the closing anchor tag
closeAnchorRe.lastIndex = offset;
var closeAnchorPos:int = input.substring(offset, input.length).search(closeAnchorRe);
// If we find an opening tag without a closing match, just return the current input
if (closeAnchorPos < 0)
return input;
endTagPos = closeAnchorPos + offset;
// RegExp.lastIndex is used to tell the regexp where to start matching
re.lastIndex = endTagPos + 4;
offset = endTagPos + 4;
continue;
}
// Do the replacement of url text with anchor tag
var address:String = input.substr(start, matchLength);
var actual:String = input.substr(start, matchLength);
if (addHTTP) {
actual = 'http://'+actual;
}
var replacement:String = '<a href="';
if (dispatchEvent) {
replacement += 'event:';
} else if (!isURL) {
replacement += 'mailto:';
}
replacement += actual.replace(new RegExp('"', 'g'), '%22')+'"';
if (truncateLength && address.length > truncateLength) {
address = address.substr(0, truncateLength) + '...';
}
// Add word break tags to allow wrapping where appropriate
// Manually put font styles around the link so they actually look like links
// see: http://livedocs.adobe.com/flex/3/html/help.html?content=textcontrols_04.html
replacement += '><font color="#0000ff"><u>'+address.replace(new RegExp("([/=&])", 'g'), "<wbr>$1")+'</u></font></a>';
if (matchedLinks) {
matchedLinks.push(actual);
}
input = input.slice(0, start) + replacement + input.slice(start+matchLength, input.length);
re.lastIndex = start + replacement.length;
offset = start + replacement.length;
}
return input;
}
/**
* Replace text emoticons with images
**/
private static function emoticonText(text:String):String {
for each (var eData:Object in Linkify.emoticons) {
var regex:String = eData.regex;
var img:String = eData.image;
// (not a word character)(smiley regex)(not a word character)
var pattern:RegExp = new RegExp('(?<!\\w)'+regex+'(?!\\w)', 'gim');
text = text.replace(pattern, '<img name="emoticon" alt="'+eData.shortcut+'" height="'+eData.height+'" width="'+eData.width+'" src="http://emoticon-hosting-site/'+img+'" />');
}
return text;
}
}
}
|
Fix trailing slash linkification
|
Fix trailing slash linkification
|
ActionScript
|
mit
|
hipchat/linkify
|
27429eed7f01ac5a9c7186b34740a008fc1ced75
|
src/aerys/minko/type/clone/CloneOptions.as
|
src/aerys/minko/type/clone/CloneOptions.as
|
package aerys.minko.type.clone
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.AnimationController;
import aerys.minko.scene.controller.TransformController;
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.scene.controller.mesh.skinning.SkinningController;
public final class CloneOptions
{
private var _clonedControllerTypes : Vector.<Class>;
private var _ignoredControllerTypes : Vector.<Class>;
private var _reassignedControllerTypes : Vector.<Class>;
private var _defaultControllerAction : uint;
public function get defaultControllerAction() : uint
{
return _defaultControllerAction;
}
public function set defaultControllerAction(v : uint) : void
{
if (v != ControllerCloneAction.CLONE
&& v != ControllerCloneAction.IGNORE
&& v != ControllerCloneAction.REASSIGN)
throw new Error('Unknown action type.');
_defaultControllerAction = v;
}
public function CloneOptions()
{
initialize();
}
private function initialize() : void
{
_clonedControllerTypes = new <Class>[];
_ignoredControllerTypes = new <Class>[];
_reassignedControllerTypes = new <Class>[];
_defaultControllerAction = ControllerCloneAction.REASSIGN;
}
public static function get defaultOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._clonedControllerTypes.push(
AnimationController,
SkinningController
);
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN;
return cloneOptions;
}
public static function get cloneAllOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE;
return cloneOptions;
}
public function addControllerAction(controllerClass : Class, action : uint) : CloneOptions
{
switch (action)
{
case ControllerCloneAction.CLONE:
_clonedControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.IGNORE:
_ignoredControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.REASSIGN:
_reassignedControllerTypes.push(controllerClass);
break;
default:
throw new Error('Unknown action type.');
}
return this;
}
public function removeControllerAction(controllerClass : Class) : void
{
throw new Error('Implement me.');
}
public function getActionForController(controller : AbstractController) : uint
{
var numControllersToClone : uint = _clonedControllerTypes.length;
var numControllersToIgnore : uint = _ignoredControllerTypes.length;
var numControllersToReassign : uint = _reassignedControllerTypes.length;
var controllerId : uint;
for (controllerId = 0; controllerId < numControllersToClone; ++controllerId)
if (controller is _clonedControllerTypes[controllerId])
return ControllerCloneAction.CLONE;
for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId)
if (controller is _ignoredControllerTypes[controllerId])
return ControllerCloneAction.IGNORE;
for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId)
if (controller is _reassignedControllerTypes[controllerId])
return ControllerCloneAction.REASSIGN;
return _defaultControllerAction;
}
}
}
|
package aerys.minko.type.clone
{
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.AnimationController;
import aerys.minko.scene.controller.TransformController;
import aerys.minko.scene.controller.camera.CameraController;
import aerys.minko.scene.controller.light.DirectionalLightController;
import aerys.minko.scene.controller.light.LightController;
import aerys.minko.scene.controller.light.PointLightController;
import aerys.minko.scene.controller.light.SpotLightController;
import aerys.minko.scene.controller.mesh.MeshController;
import aerys.minko.scene.controller.mesh.MeshVisibilityController;
import aerys.minko.scene.controller.mesh.skinning.SkinningController;
public final class CloneOptions
{
private var _clonedControllerTypes : Vector.<Class>;
private var _ignoredControllerTypes : Vector.<Class>;
private var _reassignedControllerTypes : Vector.<Class>;
private var _defaultControllerAction : uint;
public function get defaultControllerAction() : uint
{
return _defaultControllerAction;
}
public function set defaultControllerAction(v : uint) : void
{
if (v != ControllerCloneAction.CLONE
&& v != ControllerCloneAction.IGNORE
&& v != ControllerCloneAction.REASSIGN)
throw new Error('Unknown action type.');
_defaultControllerAction = v;
}
public function CloneOptions()
{
initialize();
}
private function initialize() : void
{
_clonedControllerTypes = new <Class>[];
_ignoredControllerTypes = new <Class>[];
_reassignedControllerTypes = new <Class>[];
_defaultControllerAction = ControllerCloneAction.REASSIGN;
}
public static function get defaultOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._clonedControllerTypes.push(
AnimationController,
SkinningController
);
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController,
LightController,
DirectionalLightController,
SpotLightController,
PointLightController,
);
cloneOptions._defaultControllerAction = ControllerCloneAction.REASSIGN;
return cloneOptions;
}
public static function get cloneAllOptions() : CloneOptions
{
var cloneOptions : CloneOptions = new CloneOptions();
cloneOptions._ignoredControllerTypes.push(
MeshController,
MeshVisibilityController,
CameraController,
TransformController,
LightController,
DirectionalLightController,
SpotLightController,
PointLightController
);
cloneOptions._defaultControllerAction = ControllerCloneAction.CLONE;
return cloneOptions;
}
public function addControllerAction(controllerClass : Class, action : uint) : CloneOptions
{
switch (action)
{
case ControllerCloneAction.CLONE:
_clonedControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.IGNORE:
_ignoredControllerTypes.push(controllerClass);
break;
case ControllerCloneAction.REASSIGN:
_reassignedControllerTypes.push(controllerClass);
break;
default:
throw new Error('Unknown action type.');
}
return this;
}
public function removeControllerAction(controllerClass : Class) : void
{
throw new Error('Implement me.');
}
public function getActionForController(controller : AbstractController) : uint
{
var numControllersToClone : uint = _clonedControllerTypes.length;
var numControllersToIgnore : uint = _ignoredControllerTypes.length;
var numControllersToReassign : uint = _reassignedControllerTypes.length;
var controllerId : uint;
for (controllerId = 0; controllerId < numControllersToClone; ++controllerId)
if (controller is _clonedControllerTypes[controllerId])
return ControllerCloneAction.CLONE;
for (controllerId = 0; controllerId < numControllersToIgnore; ++controllerId)
if (controller is _ignoredControllerTypes[controllerId])
return ControllerCloneAction.IGNORE;
for (controllerId = 0; controllerId < numControllersToReassign; ++controllerId)
if (controller is _reassignedControllerTypes[controllerId])
return ControllerCloneAction.REASSIGN;
return _defaultControllerAction;
}
}
}
|
update CloneOptions.cloneAllOptions and CloneOptions.defaultOptions to ignore the light related controller
|
update CloneOptions.cloneAllOptions and CloneOptions.defaultOptions to ignore the light related controller
|
ActionScript
|
mit
|
aerys/minko-as3
|
3f0290c220de97335b386d77619b7b7f806941bf
|
swfobject/src/expressInstall.as
|
swfobject/src/expressInstall.as
|
/* SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
Express Install Copyright (c) 2007-2008 Adobe Systems Incorporated and its licensors. All Rights Reserved.
*/
System.security.allowDomain("fpdownload2.macromedia.com");
var time = 0;
var timeOut = 5; // in seconds
var delay = 10; // in milliseconds
var int_id = setInterval(checkLoaded, delay);
var old_si = null;
var loaderClip = this.createEmptyMovieClip("loaderClip", 0);
var updateSWF = "http://fpdownload2.macromedia.com/pub/flashplayer/update/current/swf/autoUpdater.swf?" + Math.random();
loaderClip.loadMovie(updateSWF);
function checkLoaded(){
time += delay / 1000;
if (time > timeOut) {
// updater did not load in time, abort load and force alternative content
clearInterval(int_id);
loaderClip.unloadMovie();
loadTimeOut();
}
else if (loaderClip.startInstall.toString() == "[type Function]") {
// updater has loaded successfully AND has determined that it can do the express install
if (old_si == null) {
old_si = loaderClip.startInstall;
loaderClip.startInstall = function() {
clearInterval(int_id);
old_si();
}
loadComplete();
}
}
}
function loadTimeOut() {
callbackSWFObject();
}
function callbackSWFObject() {
getURL("javascript:swfobject.expressInstallCallback();");
}
function loadComplete() {
loaderClip.redirectURL = _level0.MMredirectURL;
loaderClip.MMplayerType = _level0.MMplayerType;
loaderClip.MMdoctitle = _level0.MMdoctitle;
loaderClip.startUpdate();
}
function installStatus(statusValue) {
switch (statusValue) {
case "Download.Complete":
// Installation is complete.
// In most cases the browser window that this SWF is hosted in will be closed by the installer or otherwise it has to be closed manually by the end user.
// The Adobe Flash installer will attempt to reopen the browser window and reload the page containing the SWF.
break;
case "Download.Cancelled":
// The end user chose "NO" when prompted to install the new player.
// By default the SWFObject callback function is called to force alternative content.
callbackSWFObject();
break;
case "Download.Failed":
// The end user failed to download the installer due to a network failure.
// By default the SWFObject callback function is called to force alternative content.
callbackSWFObject();
break;
}
}
|
/* SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
Express Install Copyright (c) 2007-2008 Adobe Systems Incorporated and its licensors. All Rights Reserved.
*/
System.security.allowDomain("fpdownload.macromedia.com");
var time = 0;
var timeOut = 5; // in seconds
var delay = 10; // in milliseconds
var int_id = setInterval(checkLoaded, delay);
var old_si = null;
var loaderClip = this.createEmptyMovieClip("loaderClip", 0);
var updateSWF = "http://fpdownload.macromedia.com/pub/flashplayer/update/current/swf/autoUpdater.swf?" + Math.random();
loaderClip.loadMovie(updateSWF);
function checkLoaded(){
time += delay / 1000;
if (time > timeOut) {
// updater did not load in time, abort load and force alternative content
clearInterval(int_id);
loaderClip.unloadMovie();
loadTimeOut();
}
else if (loaderClip.startInstall.toString() == "[type Function]") {
// updater has loaded successfully AND has determined that it can do the express install
if (old_si == null) {
old_si = loaderClip.startInstall;
loaderClip.startInstall = function() {
clearInterval(int_id);
old_si();
}
loadComplete();
}
}
}
function loadTimeOut() {
callbackSWFObject();
}
function callbackSWFObject() {
getURL("javascript:swfobject.expressInstallCallback();");
}
function loadComplete() {
loaderClip.redirectURL = _level0.MMredirectURL;
loaderClip.MMplayerType = _level0.MMplayerType;
loaderClip.MMdoctitle = _level0.MMdoctitle;
loaderClip.startUpdate();
}
function installStatus(statusValue) {
switch (statusValue) {
case "Download.Complete":
// Installation is complete.
// In most cases the browser window that this SWF is hosted in will be closed by the installer or otherwise it has to be closed manually by the end user.
// The Adobe Flash installer will attempt to reopen the browser window and reload the page containing the SWF.
break;
case "Download.Cancelled":
// The end user chose "NO" when prompted to install the new player.
// By default the SWFObject callback function is called to force alternative content.
callbackSWFObject();
break;
case "Download.Failed":
// The end user failed to download the installer due to a network failure.
// By default the SWFObject callback function is called to force alternative content.
callbackSWFObject();
break;
}
}
|
Rollback to previous version, Adobe change request was cancelled
|
Rollback to previous version, Adobe change request was cancelled
git-svn-id: c79b92e96100ef39c59e158da2f25328426f47b5@372 5cf17b04-402e-0410-8052-5f67ef7ba858
|
ActionScript
|
mit
|
swfobject/swfobject,swfobject/swfobject
|
929a5cda33421c68da234f43e1c4fea052f4964d
|
frameworks/projects/spark/src/spark/utils/MouseEventUtil.as
|
frameworks/projects/spark/src/spark/utils/MouseEventUtil.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.utils
{
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.display.InteractiveObject;
import mx.core.UIComponent;
import mx.events.FlexMouseEvent;
import mx.events.SandboxMouseEvent;
[ExcludeClass]
/**
* @private
*
* Utilities to help with mouse event dispatching or event handling.
*/
public class MouseEventUtil
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Static Methods
//
//--------------------------------------------------------------------------
/**
* Set up event listeners for a complete down-drag-up mouse gesture.
*
* Add MOUSE_DOWN, MOUSE_MOVE, and MOUSE_UP listeners to the target component
* which call the handleDown(), handleDrag(), and handleUp() functions respectively.
*
* The handleDrag() method will be called for as long as the mouse button is down,
* whenever the mouse is dragged within the stage. The handleUp() method will be
* called no matter where the mouse button is released, however a MouseEvent type argument
* will only be provided if the button is released over the stage.
*
* The handleDown() and handleDrag() functions are passed a single MouseEvent
* argument, and the handleUp() is passed an Event which may be a MouseEvent
* or a SandboxMouseEvent. Typically handleUp() functions ignore their event
* argument.
*
* Any of the functions arguments can be null.
*
* The implementation only adds MOUSE_MOVE and MOUSE_UP listeners in response
* to a MOUSE_DOWN event. Similarly, the implementation removes its MOUSE_MOVE
* and MOUSE_UP listeners when it receives a MOUSE_UP event.
*
* @param target A MOUSE_DOWN event on this component begins the down-drag-up gesture
* @param handleDown A function with a MouseEvent parameter; called when the MOUSE_DOWN event occurs.
* @param handleDrag A function with a MouseEvent parameter; called when the mouse moves with the button down.
* @param handleUp A function with an Event parameter; called when the button is relesed.
*
* @see #removeDownDragUpListeners
*/
public static function addDownDragUpListeners(
target:UIComponent,
handleDown:Function,
handleDrag:Function,
handleUp:Function):void
{
var f:Function = function(e:Event):void
{
var sbr:IEventDispatcher;
switch(e.type)
{
case MouseEvent.MOUSE_DOWN:
if (e.isDefaultPrevented())
break;
handleDown(e);
sbr = target.systemManager.getSandboxRoot();
sbr.addEventListener(MouseEvent.MOUSE_MOVE, f, true);
sbr.addEventListener(MouseEvent.MOUSE_UP, f, true );
sbr.addEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, f, true);
// Add the mouse shield so we can drag over untrusted applications.
target.systemManager.deployMouseShields(true);
break;
case MouseEvent.MOUSE_MOVE:
handleDrag(e);
break;
case MouseEvent.MOUSE_UP:
handleUp(e);
sbr = target.systemManager.getSandboxRoot();
sbr.removeEventListener(MouseEvent.MOUSE_MOVE, f, true);
sbr.removeEventListener(MouseEvent.MOUSE_UP, f, true);
sbr.removeEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, f, true);
target.systemManager.deployMouseShields(false);
break;
case "removeHandler":
target.removeEventListener("removeHandler", f);
target.removeEventListener(MouseEvent.MOUSE_DOWN, f);
sbr = target.systemManager.getSandboxRoot();
sbr.removeEventListener(MouseEvent.MOUSE_MOVE, f, true);
sbr.removeEventListener(MouseEvent.MOUSE_UP, f, true);
sbr.removeEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, f, true);
target.systemManager.deployMouseShields(false);
break;
}
}
target.addEventListener(MouseEvent.MOUSE_DOWN, f);
target.addEventListener("removeHandler", f);
}
/**
* Removes the listeners added by a matching addDownDragUpListeners call.
*
* @param target A MOUSE_DOWN event on this component begins the down-drag-up gesture
* @param handleDown The listener for MOUSE_DOWN events
* @param handleDrag The listener for MOUSE_MOVE events when the button is down.
* @param handleUp The listener for MOUSE_UP events
*
* @see #addDownDragUpListeners
*/
public static function removeDownDragUpListeners(
target:UIComponent,
handleDown:Function,
handleDrag:Function,
handleUp:Function):void
{
target.dispatchEvent(
new RemoveHandlerEvent(handleDown, handleDrag, handleUp));
}
/**
* Create a 'mouseWheelChanging' FlexMouseEvent from a 'mouseWheel'
* MouseEvent.
*/
public static function createMouseWheelChangingEvent(event:MouseEvent):FlexMouseEvent
{
const flexEvent:FlexMouseEvent = new FlexMouseEvent(
FlexMouseEvent.MOUSE_WHEEL_CHANGING,
true, true, // bubbles and cancelable
event.localX, event.localY,
InteractiveObject(event.target),
event.ctrlKey, event.altKey, event.shiftKey,
event.buttonDown, event.delta);
return flexEvent;
}
}
}
/**
* Event used to remove the handlers associated with the press-drag-release
* gesture handlers.
*/
class RemoveHandlerEvent extends flash.events.Event
{
public var handleDown:Function;
public var handleDrag:Function;
public var handleUp:Function;
public function RemoveHandlerEvent(handleDown:Function,
handleDrag:Function = null,
handleUp:Function = null)
{
this.handleDown = handleDown;
this.handleDown = handleDrag;
this.handleUp = handleUp;
super("removeHandler");
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.utils
{
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.display.InteractiveObject;
import mx.core.UIComponent;
import mx.events.FlexMouseEvent;
import mx.events.SandboxMouseEvent;
[ExcludeClass]
/**
* @private
*
* Utilities to help with mouse event dispatching or event handling.
*/
public class MouseEventUtil
{
include "../core/Version.as";
//--------------------------------------------------------------------------
//
// Static Methods
//
//--------------------------------------------------------------------------
/**
* Set up event listeners for a complete down-drag-up mouse gesture.
*
* Add MOUSE_DOWN, MOUSE_MOVE, and MOUSE_UP listeners to the target component
* which call the handleDown(), handleDrag(), and handleUp() functions respectively.
*
* The handleDrag() method will be called for as long as the mouse button is down,
* whenever the mouse is dragged within the stage. The handleUp() method will be
* called no matter where the mouse button is released, however a MouseEvent type argument
* will only be provided if the button is released over the stage.
*
* The handleDown() and handleDrag() functions are passed a single MouseEvent
* argument, and the handleUp() is passed an Event which may be a MouseEvent
* or a SandboxMouseEvent. Typically handleUp() functions ignore their event
* argument.
*
* Any of the functions arguments can be null.
*
* The implementation only adds MOUSE_MOVE and MOUSE_UP listeners in response
* to a MOUSE_DOWN event. Similarly, the implementation removes its MOUSE_MOVE
* and MOUSE_UP listeners when it receives a MOUSE_UP event.
*
* @param target A MOUSE_DOWN event on this component begins the down-drag-up gesture
* @param handleDown A function with a MouseEvent parameter; called when the MOUSE_DOWN event occurs.
* @param handleDrag A function with a MouseEvent parameter; called when the mouse moves with the button down.
* @param handleUp A function with an Event parameter; called when the button is relesed.
*
* @see #removeDownDragUpListeners
*/
public static function addDownDragUpListeners(
target:UIComponent,
handleDown:Function,
handleDrag:Function,
handleUp:Function):void
{
var f:Function = function(e:Event):void
{
var sbr:IEventDispatcher;
switch(e.type)
{
case MouseEvent.MOUSE_DOWN:
if (e.isDefaultPrevented())
break;
handleDown(e);
sbr = target.systemManager.getSandboxRoot();
sbr.addEventListener(MouseEvent.MOUSE_MOVE, f, true);
sbr.addEventListener(MouseEvent.MOUSE_UP, f, true );
sbr.addEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, f, true);
// Add the mouse shield so we can drag over untrusted applications.
target.systemManager.deployMouseShields(true);
break;
case MouseEvent.MOUSE_MOVE:
handleDrag(e);
break;
case MouseEvent.MOUSE_UP:
handleUp(e);
sbr = target.systemManager.getSandboxRoot();
sbr.removeEventListener(MouseEvent.MOUSE_MOVE, f, true);
sbr.removeEventListener(MouseEvent.MOUSE_UP, f, true);
sbr.removeEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, f, true);
target.systemManager.deployMouseShields(false);
break;
case "removeHandler":
target.removeEventListener("removeHandler", f);
target.removeEventListener(MouseEvent.MOUSE_DOWN, f);
sbr = target.systemManager.getSandboxRoot();
sbr.removeEventListener(MouseEvent.MOUSE_MOVE, f, true);
sbr.removeEventListener(MouseEvent.MOUSE_UP, f, true);
sbr.removeEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE, f, true);
target.systemManager.deployMouseShields(false);
break;
}
}
target.addEventListener(MouseEvent.MOUSE_DOWN, f);
target.addEventListener("removeHandler", f);
}
/**
* Removes the listeners added by a matching addDownDragUpListeners call.
*
* @param target A MOUSE_DOWN event on this component begins the down-drag-up gesture
* @param handleDown The listener for MOUSE_DOWN events
* @param handleDrag The listener for MOUSE_MOVE events when the button is down.
* @param handleUp The listener for MOUSE_UP events
*
* @see #addDownDragUpListeners
*/
public static function removeDownDragUpListeners(
target:UIComponent,
handleDown:Function,
handleDrag:Function,
handleUp:Function):void
{
target.dispatchEvent(
new RemoveHandlerEvent(handleDown, handleDrag, handleUp));
}
/**
* Create a 'mouseWheelChanging' FlexMouseEvent from a 'mouseWheel'
* MouseEvent.
*/
public static function createMouseWheelChangingEvent(event:MouseEvent):FlexMouseEvent
{
const flexEvent:FlexMouseEvent = new FlexMouseEvent(
FlexMouseEvent.MOUSE_WHEEL_CHANGING,
true, true, // bubbles and cancelable
event.localX, event.localY,
InteractiveObject(event.target),
event.ctrlKey, event.altKey, event.shiftKey,
event.buttonDown, event.delta);
return flexEvent;
}
}
}
import flash.events.Event;
/**
* Event used to remove the handlers associated with the press-drag-release
* gesture handlers.
*/
class RemoveHandlerEvent extends flash.events.Event
{
public var handleDown:Function;
public var handleDrag:Function;
public var handleUp:Function;
public function RemoveHandlerEvent(handleDown:Function,
handleDrag:Function = null,
handleUp:Function = null)
{
this.handleDown = handleDown;
this.handleDown = handleDrag;
this.handleUp = handleUp;
super("removeHandler");
}
}
|
add missing import. Falcon cares about this stuff
|
add missing import. Falcon cares about this stuff
|
ActionScript
|
apache-2.0
|
shyamalschandra/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,apache/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk
|
01d0ab6664cbb11edbb3ab45c25ffc7ce6cbe585
|
src/com/esri/builder/views/supportClasses/KeyValueEditor.as
|
src/com/esri/builder/views/supportClasses/KeyValueEditor.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.views.supportClasses
{
import com.esri.ags.layers.supportClasses.Field;
import com.esri.ags.portal.supportClasses.PopUpFieldFormat;
import com.esri.ags.portal.supportClasses.PopUpFieldInfo;
import com.esri.builder.components.ItemModifierDataGrid;
import com.esri.builder.components.ModifyItemEvent;
import com.esri.builder.views.popups.FieldFormatPopUp;
import flash.display.DisplayObjectContainer;
import flash.utils.Dictionary;
import mx.collections.IList;
import mx.core.FlexGlobals;
import spark.components.supportClasses.SkinnableComponent;
import spark.events.PopUpEvent;
public class KeyValueEditor extends SkinnableComponent
{
[SkinPart(required="true")]
public var fieldEditor:ItemModifierDataGrid;
private var editedFieldInfo:PopUpFieldInfo;
private var _popUpFieldInfos:IList;
[Bindable]
public function get popUpFieldInfos():IList
{
return _popUpFieldInfos;
}
public function set popUpFieldInfos(value:IList):void
{
_popUpFieldInfos = value;
invalidateProperties();
}
[Bindable]
private var _fields:IList;
public function get fields():IList
{
return _fields;
}
public function set fields(value:IList):void
{
_fields = value;
invalidateProperties();
}
override protected function commitProperties():void
{
if (!fieldNameToFieldLookUp
&& _fields && _popUpFieldInfos)
{
initFieldNameToFieldLookUp();
}
super.commitProperties();
}
public var fieldNameToFieldLookUp:Dictionary;
private function initFieldNameToFieldLookUp():void
{
fieldNameToFieldLookUp = new Dictionary();
for each (var field:Field in _fields.toArray())
{
fieldNameToFieldLookUp[field.name] = field;
}
}
override protected function partAdded(partName:String, instance:Object):void
{
super.partAdded(partName, instance);
if (instance == fieldEditor)
{
fieldEditor.addEventListener(ModifyItemEvent.MOVE_ITEM_DOWN, popUpFieldsDataGrid_moveItemDownHandler);
fieldEditor.addEventListener(ModifyItemEvent.MOVE_ITEM_UP, popUpFieldsDataGrid_moveItemUpHandler);
fieldEditor.addEventListener(ModifyItemEvent.EDIT_ITEM, popUpFieldsDataGrid_editItemHandler);
}
}
protected function popUpFieldsDataGrid_moveItemDownHandler(event:ModifyItemEvent):void
{
var itemIndex:int = _popUpFieldInfos.getItemIndex(event.item);
var isItemAtBottom:Boolean = (itemIndex == (_popUpFieldInfos.length - 1));
if (isItemAtBottom)
{
return;
}
var removedItem:Object = _popUpFieldInfos.removeItemAt(itemIndex);
_popUpFieldInfos.addItemAt(removedItem, ++itemIndex);
}
protected function popUpFieldsDataGrid_moveItemUpHandler(event:ModifyItemEvent):void
{
var itemIndex:int = _popUpFieldInfos.getItemIndex(event.item);
var isItemAtTop:Boolean = (itemIndex == 0);
if (isItemAtTop)
{
return;
}
var removedItem:Object = _popUpFieldInfos.removeItemAt(itemIndex);
_popUpFieldInfos.addItemAt(removedItem, --itemIndex);
}
private function popUpFieldsDataGrid_editItemHandler(event:ModifyItemEvent):void
{
var fieldFormatPopUp:FieldFormatPopUp = new FieldFormatPopUp();
editedFieldInfo = event.item as PopUpFieldInfo;
fieldFormatPopUp.field = findMatchingField(editedFieldInfo.fieldName);
if (editedFieldInfo.format)
{
fieldFormatPopUp.overrideFieldFormat(editedFieldInfo.format);
}
fieldFormatPopUp.addEventListener(PopUpEvent.CLOSE, fieldFormatPopUp_closeHandler);
fieldFormatPopUp.open(FlexGlobals.topLevelApplication as DisplayObjectContainer, true);
}
public function findMatchingField(fieldName:String):Field
{
return fieldNameToFieldLookUp[fieldName];
}
private function fieldFormatPopUp_closeHandler(event:PopUpEvent):void
{
var fieldFormatPopUp:FieldFormatPopUp = event.currentTarget as FieldFormatPopUp;
fieldFormatPopUp.removeEventListener(PopUpEvent.CLOSE, fieldFormatPopUp_closeHandler);
if (event.commit)
{
editedFieldInfo.format = event.data.fieldFormat as PopUpFieldFormat;
}
}
override protected function partRemoved(partName:String, instance:Object):void
{
super.partRemoved(partName, instance);
if (instance == fieldEditor)
{
fieldEditor.removeEventListener(ModifyItemEvent.MOVE_ITEM_DOWN, popUpFieldsDataGrid_moveItemDownHandler);
fieldEditor.removeEventListener(ModifyItemEvent.MOVE_ITEM_UP, popUpFieldsDataGrid_moveItemUpHandler);
fieldEditor.removeEventListener(ModifyItemEvent.EDIT_ITEM, popUpFieldsDataGrid_editItemHandler);
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// 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.views.supportClasses
{
import com.esri.ags.layers.supportClasses.Field;
import com.esri.ags.portal.supportClasses.PopUpFieldFormat;
import com.esri.ags.portal.supportClasses.PopUpFieldInfo;
import com.esri.builder.components.ItemModifierDataGrid;
import com.esri.builder.components.ModifyItemEvent;
import com.esri.builder.views.popups.FieldFormatPopUp;
import flash.display.DisplayObjectContainer;
import flash.utils.Dictionary;
import mx.collections.IList;
import mx.core.FlexGlobals;
import spark.components.supportClasses.SkinnableComponent;
import spark.events.PopUpEvent;
public class KeyValueEditor extends SkinnableComponent
{
[SkinPart(required="true")]
public var fieldEditor:ItemModifierDataGrid;
private var editedFieldInfo:PopUpFieldInfo;
private var _popUpFieldInfos:IList;
[Bindable]
public function get popUpFieldInfos():IList
{
return _popUpFieldInfos;
}
public function set popUpFieldInfos(value:IList):void
{
_popUpFieldInfos = value;
invalidateProperties();
}
[Bindable]
private var _fields:IList;
public function get fields():IList
{
return _fields;
}
public function set fields(value:IList):void
{
_fields = value;
invalidateProperties();
}
override protected function commitProperties():void
{
if (!fieldNameToFieldLookUp
&& _fields && _popUpFieldInfos)
{
initFieldNameToFieldLookUp();
}
super.commitProperties();
}
public var fieldNameToFieldLookUp:Dictionary;
private function initFieldNameToFieldLookUp():void
{
fieldNameToFieldLookUp = new Dictionary();
for each (var field:Field in _fields.toArray())
{
fieldNameToFieldLookUp[field.name] = field;
}
}
override protected function partAdded(partName:String, instance:Object):void
{
super.partAdded(partName, instance);
if (instance == fieldEditor)
{
fieldEditor.addEventListener(ModifyItemEvent.MOVE_ITEM_DOWN, popUpFieldsDataGrid_moveItemDownHandler);
fieldEditor.addEventListener(ModifyItemEvent.MOVE_ITEM_UP, popUpFieldsDataGrid_moveItemUpHandler);
fieldEditor.addEventListener(ModifyItemEvent.EDIT_ITEM, popUpFieldsDataGrid_editItemHandler);
}
}
protected function popUpFieldsDataGrid_moveItemDownHandler(event:ModifyItemEvent):void
{
var itemIndex:int = _popUpFieldInfos.getItemIndex(event.item);
var isItemAtBottom:Boolean = (itemIndex == (_popUpFieldInfos.length - 1));
if (isItemAtBottom)
{
return;
}
var removedItem:Object = _popUpFieldInfos.removeItemAt(itemIndex);
_popUpFieldInfos.addItemAt(removedItem, ++itemIndex);
}
protected function popUpFieldsDataGrid_moveItemUpHandler(event:ModifyItemEvent):void
{
var itemIndex:int = _popUpFieldInfos.getItemIndex(event.item);
var isItemAtTop:Boolean = (itemIndex == 0);
if (isItemAtTop)
{
return;
}
var removedItem:Object = _popUpFieldInfos.removeItemAt(itemIndex);
_popUpFieldInfos.addItemAt(removedItem, --itemIndex);
}
private function popUpFieldsDataGrid_editItemHandler(event:ModifyItemEvent):void
{
var fieldFormatPopUp:FieldFormatPopUp = new FieldFormatPopUp();
editedFieldInfo = event.item as PopUpFieldInfo;
fieldFormatPopUp.field = findMatchingField(editedFieldInfo.fieldName);
if (editedFieldInfo.format)
{
fieldFormatPopUp.overrideFieldFormat(editedFieldInfo.format);
}
fieldFormatPopUp.addEventListener(PopUpEvent.CLOSE, fieldFormatPopUp_closeHandler);
fieldFormatPopUp.open(FlexGlobals.topLevelApplication as DisplayObjectContainer, true);
}
public function findMatchingField(fieldName:String):Field
{
return fieldNameToFieldLookUp ? fieldNameToFieldLookUp[fieldName] : null;
}
private function fieldFormatPopUp_closeHandler(event:PopUpEvent):void
{
var fieldFormatPopUp:FieldFormatPopUp = event.currentTarget as FieldFormatPopUp;
fieldFormatPopUp.removeEventListener(PopUpEvent.CLOSE, fieldFormatPopUp_closeHandler);
if (event.commit)
{
editedFieldInfo.format = event.data.fieldFormat as PopUpFieldFormat;
}
}
override protected function partRemoved(partName:String, instance:Object):void
{
super.partRemoved(partName, instance);
if (instance == fieldEditor)
{
fieldEditor.removeEventListener(ModifyItemEvent.MOVE_ITEM_DOWN, popUpFieldsDataGrid_moveItemDownHandler);
fieldEditor.removeEventListener(ModifyItemEvent.MOVE_ITEM_UP, popUpFieldsDataGrid_moveItemUpHandler);
fieldEditor.removeEventListener(ModifyItemEvent.EDIT_ITEM, popUpFieldsDataGrid_editItemHandler);
}
}
}
}
|
Handle uninitialized KeyValueEditor field map.
|
Handle uninitialized KeyValueEditor field map.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
a20a23c505450e4fc3720a151b32f98b9eb21395
|
src/org/mangui/hls/utils/Hex.as
|
src/org/mangui/hls/utils/Hex.as
|
/**
* Hex
*
* Utility class to convert Hex strings to ByteArray or String types.
* Copyright (c) 2007 Henri Torgemane
*
* See LICENSE.txt for full license information.
*/
package org.mangui.hls.utils {
import flash.utils.ByteArray;
public class Hex {
/**
* Generates byte-array from given hexadecimal string
*
* Supports straight and colon-laced hex (that means 23:03:0e:f0, but *NOT* 23:3:e:f0)
* The first nibble (hex digit) may be omitted.
* Any whitespace characters are ignored.
*/
public static function toArray(hex : String) : ByteArray {
hex = hex.replace(/^0x|\s|:/gm, '');
var a : ByteArray = new ByteArray;
if ((hex.length & 1) == 1) hex = "0" + hex;
for (var i : uint = 0; i < hex.length; i += 2) {
a[i / 2] = parseInt(hex.substr(i, 2), 16);
}
return a;
}
/**
* Generates lowercase hexadecimal string from given byte-array
*/
public static function fromArray(array : ByteArray, colons : Boolean = false) : String {
var s : String = "";
for (var i : uint = 0; i < array.length; i++) {
s += ("0" + array[i].toString(16)).substr(-2, 2);
if (colons) {
if (i < array.length - 1) s += ":";
}
}
return s;
}
}
}
|
/**
* Hex
*
* Utility class to convert Hex strings to ByteArray or String types.
* Copyright (c) 2007 Henri Torgemane
*
* See LICENSE.txt for full license information.
*/
package org.mangui.hls.utils {
import flash.utils.ByteArray;
public class Hex {
/**
* Generates byte-array from given hexadecimal string
*
* Supports straight and colon-laced hex (that means 23:03:0e:f0, but *NOT* 23:3:e:f0)
* The first nibble (hex digit) may be omitted.
* Any whitespace characters are ignored.
*/
public static function toArray(hex : String) : ByteArray {
hex = hex.replace(/^0x|\s|:/gm, '');
var a : ByteArray = new ByteArray;
var len : uint = hex.length;
if ((len & 1) == 1) hex = "0" + hex;
for (var i : uint = 0; i < len; i += 2) {
a[i / 2] = parseInt(hex.substr(i, 2), 16);
}
return a;
}
/**
* Generates lowercase hexadecimal string from given byte-array
*/
public static function fromArray(array : ByteArray, colons : Boolean = false) : String {
var s : String = "";
var len : uint = array.length;
for (var i : uint = 0; i < len; i++) {
s += ("0" + array[i].toString(16)).substr(-2, 2);
if (colons) {
if (i < len - 1) s += ":";
}
}
return s;
}
}
}
|
optimize loop
|
optimize loop
|
ActionScript
|
mpl-2.0
|
aevange/flashls,fixedmachine/flashls,thdtjsdn/flashls,School-Improvement-Network/flashls,mangui/flashls,Peer5/flashls,neilrackett/flashls,Boxie5/flashls,Corey600/flashls,suuhas/flashls,viktorot/flashls,suuhas/flashls,dighan/flashls,jlacivita/flashls,aevange/flashls,School-Improvement-Network/flashls,thdtjsdn/flashls,clappr/flashls,codex-corp/flashls,dighan/flashls,aevange/flashls,hola/flashls,loungelogic/flashls,JulianPena/flashls,Peer5/flashls,Peer5/flashls,viktorot/flashls,viktorot/flashls,School-Improvement-Network/flashls,vidible/vdb-flashls,Boxie5/flashls,NicolasSiver/flashls,aevange/flashls,mangui/flashls,loungelogic/flashls,suuhas/flashls,tedconf/flashls,fixedmachine/flashls,clappr/flashls,NicolasSiver/flashls,JulianPena/flashls,jlacivita/flashls,vidible/vdb-flashls,Peer5/flashls,neilrackett/flashls,suuhas/flashls,Corey600/flashls,tedconf/flashls,hola/flashls,codex-corp/flashls
|
d05a3fb91de1d1ceb2e660eb0f5868e9e6865bff
|
src/com/merlinds/miracle_tool/controllers/PublishCommand.as
|
src/com/merlinds/miracle_tool/controllers/PublishCommand.as
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 15:14
*/
package com.merlinds.miracle_tool.controllers {
import com.merlinds.debug.log;
import com.merlinds.miracle.meshes.MeshMatrix;
import com.merlinds.miracle.utils.UMath;
import com.merlinds.miracle_tool.events.ActionEvent;
import com.merlinds.miracle_tool.events.DialogEvent;
import com.merlinds.miracle_tool.models.ProjectModel;
import com.merlinds.miracle_tool.models.vo.AnimationVO;
import com.merlinds.miracle_tool.models.vo.ElementVO;
import com.merlinds.miracle_tool.models.vo.FrameVO;
import com.merlinds.miracle_tool.models.vo.SourceVO;
import com.merlinds.miracle_tool.models.vo.TimelineVO;
import com.merlinds.miracle_tool.services.ActionService;
import com.merlinds.miracle_tool.services.FileSystemService;
import com.merlinds.miracle_tool.utils.MeshUtils;
import flash.display.BitmapData;
import flash.geom.Point;
import flash.utils.ByteArray;
import org.robotlegs.mvcs.Command;
public class PublishCommand extends Command {
[Inject]
public var projectModel:ProjectModel;
[Inject]
public var fileSystemService:FileSystemService;
[Inject]
public var actionService:ActionService;
[Inject]
public var event:ActionEvent;
private var _mesh:ByteArray;
private var _png:ByteArray;
private var _animations:ByteArray;
//==============================================================================
//{region PUBLIC METHODS
public function PublishCommand() {
super();
}
override public function execute():void {
log(this, "execute");
if(event.body == null){
var data:Object = {
projectName:this.projectModel.name
};
this.actionService.addAcceptActions(new <String>[ActionEvent.PUBLISHING]);
this.dispatch(new DialogEvent(DialogEvent.PUBLISH_SETTINGS, data));
}else{
var projectName:String = event.body.projectName;
this.createOutput();
this.fileSystemService.writeTexture(projectName, _png, _mesh);
this.fileSystemService.writeAnimation(_animations);
}
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function createOutput():void{
var buffer:BitmapData = new BitmapData(this.projectModel.outputSize, this.projectModel.outputSize, true, 0x0);
var mesh:Array = [];
var n:int = this.projectModel.sources.length;
for(var i:int = 0; i < n; i++){
var source:SourceVO = this.projectModel.sources[i];
var m:int = source.elements.length;
for(var j:int = 0; j < m; j++){
//push element view to buffer
var element:ElementVO = source.elements[j];
var depth:Point = new Point(element.x + this.projectModel.boundsOffset,
element.y + this.projectModel.boundsOffset);
buffer.copyPixels(element.bitmapData, element.bitmapData.rect, depth);
//get mesh
mesh.push({
name:element.name,
vertexes:MeshUtils.flipToY(element.vertexes),
uv:MeshUtils.covertToRelative(element.uv, this.projectModel.outputSize),
indexes:element.indexes
});
}
//get animation
m = source.animations.length;
var animations:Array = [];
for(j = 0; j < m; j++){
var animation:Object = this.createAnimationOutput(source.animations[j]);
animations.push(animation);
}
}
_mesh = new ByteArray();
_mesh.writeObject(mesh);
_png = PNGEncoder.encode(buffer);
_animations = new ByteArray();
_animations.writeObject(animations);
}
private function createAnimationOutput(animationVO:AnimationVO):Object {
var data:Object = { name:animationVO.name.substr(0, -4),// name of the matrix
totalFrames:animationVO.totalFrames,// Total animation frames
layers:[]};
var n:int = animationVO.timelines.length;
//find matrix sequence for current animation
for(var i:int = 0; i < n; i++){
var timelineVO:TimelineVO = animationVO.timelines[i];
var m:int = timelineVO.frames.length;
var layer:Layer = new Layer();
for(var j:int = 0; j < m; j++){
var frameVO:FrameVO = timelineVO.frames[j];
//create matrix
var prevMatrix:MeshMatrix = layer.matrixList.length > 0
? layer.matrixList[ layer.matrixList.length - 1] : null;
var matrix:MeshMatrix = MeshMatrix.fromMatrix(frameVO.matrix, 0, 0);
if(prevMatrix != null && matrix != null){
//calculate shortest angle between previous matrix skew and current matrix skew
matrix.skewX = this.getShortest(matrix.skewX, prevMatrix.skewX);
matrix.skewY = this.getShortest(matrix.skewY, prevMatrix.skewY);
//
}
var index:int = matrix == null ? -1 : layer.matrixList.push(matrix) - 1;
var framesArray:Array = this.createFramesInfo(index, frameVO.name,
frameVO.duration, frameVO.type == "motion");
layer.framesList = layer.framesList.concat(framesArray);
prevMatrix = matrix;
}
data.layers.unshift(layer);
}
trace(JSON.stringify(data));
return data;
}
[Inline]
private function createFramesInfo(index:int, polygonName:String,
duration:int, motion:Boolean):Array {
var result:Array = new Array(duration);
if(duration < 2){
motion = false;
}
if(index > -1){
var t:Number = 1 / duration;
for(var i:int = 0; i < duration; i++){
var frameInfoData:FrameInfoData = new FrameInfoData();
frameInfoData.index = index;
frameInfoData.polygonName = polygonName;
frameInfoData.motion = motion;
frameInfoData.t = motion ? t * i : 0;
result[i] = frameInfoData;
}
}
return result;
}
private function getShortest(a:Number, b:Number):Number {
if(Math.abs(a - b) > Math.PI){
if(a > 0){
return a - Math.PI * 2;
}else if(a < 0){
return Math.PI * 2 + a;
}
}
return a;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
class Layer{
public var matrixList:Array;
public var framesList:Array;
public function Layer() {
this.framesList = [];
this.matrixList = [];
}
}
class FrameInfoData{
public var polygonName:String;
public var motion:Boolean;
public var index:int;
public var t:Number;
}
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 15:14
*/
package com.merlinds.miracle_tool.controllers {
import com.merlinds.debug.log;
import com.merlinds.miracle.meshes.MeshMatrix;
import com.merlinds.miracle_tool.events.ActionEvent;
import com.merlinds.miracle_tool.events.DialogEvent;
import com.merlinds.miracle_tool.models.ProjectModel;
import com.merlinds.miracle_tool.models.vo.AnimationVO;
import com.merlinds.miracle_tool.models.vo.ElementVO;
import com.merlinds.miracle_tool.models.vo.FrameVO;
import com.merlinds.miracle_tool.models.vo.SourceVO;
import com.merlinds.miracle_tool.models.vo.TimelineVO;
import com.merlinds.miracle_tool.services.ActionService;
import com.merlinds.miracle_tool.services.FileSystemService;
import com.merlinds.miracle_tool.utils.MeshUtils;
import flash.display.BitmapData;
import flash.geom.Point;
import flash.utils.ByteArray;
import org.robotlegs.mvcs.Command;
public class PublishCommand extends Command {
[Inject]
public var projectModel:ProjectModel;
[Inject]
public var fileSystemService:FileSystemService;
[Inject]
public var actionService:ActionService;
[Inject]
public var event:ActionEvent;
private var _mesh:ByteArray;
private var _png:ByteArray;
private var _animations:ByteArray;
//==============================================================================
//{region PUBLIC METHODS
public function PublishCommand() {
super();
}
override public function execute():void {
log(this, "execute");
if(event.body == null){
var data:Object = {
projectName:this.projectModel.name
};
this.actionService.addAcceptActions(new <String>[ActionEvent.PUBLISHING]);
this.dispatch(new DialogEvent(DialogEvent.PUBLISH_SETTINGS, data));
}else{
var projectName:String = event.body.projectName;
this.createOutput();
this.fileSystemService.writeTexture(projectName, _png, _mesh);
this.fileSystemService.writeAnimation(_animations);
}
}
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function createOutput():void{
var buffer:BitmapData = new BitmapData(this.projectModel.outputSize, this.projectModel.outputSize, true, 0x0);
var mesh:Array = [];
var n:int = this.projectModel.sources.length;
for(var i:int = 0; i < n; i++){
var source:SourceVO = this.projectModel.sources[i];
var m:int = source.elements.length;
for(var j:int = 0; j < m; j++){
//push element view to buffer
var element:ElementVO = source.elements[j];
var depth:Point = new Point(element.x + this.projectModel.boundsOffset,
element.y + this.projectModel.boundsOffset);
buffer.copyPixels(element.bitmapData, element.bitmapData.rect, depth);
//get mesh
mesh.push({
name:element.name,
vertexes:MeshUtils.flipToY(element.vertexes),
uv:MeshUtils.covertToRelative(element.uv, this.projectModel.outputSize),
indexes:element.indexes
});
}
//get animation
m = source.animations.length;
var animations:Array = [];
for(j = 0; j < m; j++){
var animation:Object = this.createAnimationOutput(source.animations[j]);
animations.push(animation);
}
}
_mesh = new ByteArray();
_mesh.writeObject(mesh);
_png = PNGEncoder.encode(buffer);
_animations = new ByteArray();
_animations.writeObject(animations);
}
private function createAnimationOutput(animationVO:AnimationVO):Object {
var data:Object = { name:animationVO.name.substr(0, -4),// name of the matrix
totalFrames:animationVO.totalFrames,// Total animation frames
layers:[]};
var n:int = animationVO.timelines.length;
//find matrix sequence for current animation
for(var i:int = 0; i < n; i++){
var timelineVO:TimelineVO = animationVO.timelines[i];
var m:int = timelineVO.frames.length;
var layer:Layer = new Layer();
for(var j:int = 0; j < m; j++){
var frameVO:FrameVO = timelineVO.frames[j];
//create matrix
var prevMatrix:MeshMatrix = layer.matrixList.length > 0
? layer.matrixList[ layer.matrixList.length - 1] : null;
var matrix:MeshMatrix = MeshMatrix.fromMatrix(frameVO.matrix, frameVO.transformationPoint.x, frameVO.transformationPoint.y);
if(prevMatrix != null && matrix != null){
//calculate shortest angle between previous matrix skew and current matrix skew
matrix.skewX = this.getShortest(matrix.skewX, prevMatrix.skewX);
matrix.skewY = this.getShortest(matrix.skewY, prevMatrix.skewY);
//
}
var index:int = matrix == null ? -1 : layer.matrixList.push(matrix) - 1;
var framesArray:Array = this.createFramesInfo(index, frameVO.name,
frameVO.duration, frameVO.type == "motion");
layer.framesList = layer.framesList.concat(framesArray);
prevMatrix = matrix;
}
data.layers.unshift(layer);
}
trace(JSON.stringify(data));
return data;
}
[Inline]
private function createFramesInfo(index:int, polygonName:String,
duration:int, motion:Boolean):Array {
var result:Array = new Array(duration);
if(duration < 2){
motion = false;
}
if(index > -1){
var t:Number = 1 / duration;
for(var i:int = 0; i < duration; i++){
var frameInfoData:FrameInfoData = new FrameInfoData();
frameInfoData.index = index;
frameInfoData.polygonName = polygonName;
frameInfoData.motion = motion;
frameInfoData.t = motion ? t * i : 0;
result[i] = frameInfoData;
}
}
return result;
}
private function getShortest(a:Number, b:Number):Number {
if(Math.abs(a - b) > Math.PI){
if(a > 0){
return a - Math.PI * 2;
}else if(a < 0){
return Math.PI * 2 + a;
}
}
return a;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
class Layer{
public var matrixList:Array;
public var framesList:Array;
public function Layer() {
this.framesList = [];
this.matrixList = [];
}
}
class FrameInfoData{
public var polygonName:String;
public var motion:Boolean;
public var index:int;
public var t:Number;
}
|
refactor scene
|
refactor scene
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
be9552b123406d2a7944276e487f7b2da2da2bd3
|
com/ozg/adcore/vpaid/vpaidLinearFullPage.as
|
com/ozg/adcore/vpaid/vpaidLinearFullPage.as
|
package com.ozg.adcore.vpaid
{
import flash.display.Sprite;
import flash.utils.Timer;
import flash.external.ExternalInterface;
import com.ozg.events.vpaidEvent;
import flash.events.TimerEvent;
import com.ozg.events.helperEvents;
import flash.system.Security;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.net.URLLoader;
public class vpaidLinearFullPage extends Sprite implements IVPAID
{
public function vpaidLinearFullPage()
{
super();
Security.allowDomain("*");
mouseEnabled = false;
}
private static const VPAID_VERSION:String = "1.1";
protected var creativeLoadTimer:Timer;
protected var creativeLoadTimeout:Number = 15;
protected var creativePath:String;
protected var clickUrl:String;
protected var timeRemaining:Number;
protected var adPlayerVolume:Number;
protected var initWidth:Number;
protected var initHeight:Number;
private var viewMode:String;
private var adContainerSprite:Sprite;
protected var isLinearAd:Boolean = true;
private var clickThru:String;
private var impressionURL:String;
public function getVPAID() : Object
{
return this;
}
public function get adLinear() : Boolean
{
return this.isLinearAd;
}
public function get adExpanded() : Boolean
{
return false;
}
public function get adRemainingTime() : Number
{
return this.timeRemaining;
}
public function get adVolume() : Number
{
return this.adPlayerVolume;
}
public function set adVolume(param1:Number) : void
{
this.adPlayerVolume = param1;
}
public function handshakeVersion(param1:String) : String
{
this.log("The player supports VPAID version " + param1 + " and the ad supports " + VPAID_VERSION);
return VPAID_VERSION;
}
protected function log(param1:String) : void
{
var _loc2_:Object = {"message":param1};
dispatchEvent(new vpaidEvent(vpaidEvent.AdLog,_loc2_));
}
public function initAd(param1:Number, param2:Number, param3:String, param4:Number, param5:String, param6:String) : void
{
this.handleData(param5);
this.resizeAd(param1,param2,param3);
this.loadAd();
}
protected function handleData(param1:String) : void
{
var xmlData:XML = null;
var creativeData:String = param1;
if(creativeData != null)
{
try
{
xmlData = new XML(creativeData);
this.creativePath = xmlData.setting;
this.creativeLoadTimeout = xmlData.duration;
this.clickThru = xmlData.clickThru;
this.impressionURL = xmlData.impressionURL;
initWidth = xmlData.creativeWidth;
initHeight = xmlData.creativeHeight;
handleVpaidEvent('AdImpression');
var s:SendAndLoadExample = new SendAndLoadExample();
s.sendData(impressionURL,'no message');
}
catch(e:Error)
{
onError();
}
}
else
{
this.onError();
}
if(creativeData != null)
{
return;
}
}
protected function loadAd() : void
{
dispatchEvent(new vpaidEvent(vpaidEvent.AdLoaded));
}
public function startAd() : void
{
this.log("Beginning the display of the VPAID ad");
dispatchEvent(new vpaidEvent(vpaidEvent.AdStarted));
this.creativeLoadTimer = new Timer(1000,this.creativeLoadTimeout);
this.creativeLoadTimer.addEventListener(TimerEvent.TIMER,this.onTimer);
this.creativeLoadTimer.addEventListener(TimerEvent.TIMER_COMPLETE,this.timerComplete);
this.creativeLoadTimer.start();
this.addJsCallbacks();
this.addEventListeners();
this.adContainerSprite = new adContainer(this.initWidth,this.initHeight);
addChild(this.adContainerSprite);
}
private function timerComplete(param1:TimerEvent) : void
{
this.stopAd();
}
private function addJsCallbacks() : void
{
ExternalInterface.addCallback("handleVpaidEvent",this.handleVpaidEvent);
ExternalInterface.addCallback("getPlayerVolume",this.getAdPlayerVolume);
ExternalInterface.call("initVpaid",creativePath,this.initWidth,this.initHeight);
}
private function getAdPlayerVolume() : void
{
//js will come here
}
public function comingHTML() : void
{
ExternalInterface.call("console.log","i am talking with js");
}
private function addEventListeners() : void
{
addEventListener(vpaidEvent.AdUserClose,this.userClose);
}
private function userClose(param1:vpaidEvent) : void
{
this.stopAd();
}
protected function handleVpaidEvent(param1:String) : void
{
// ExternalInterface.call('console.log','param : '+param1);
switch(param1)
{
case "AdImpression":
dispatchEvent(new vpaidEvent(vpaidEvent.AdImpression));
break;
case "AdVideoStart":
dispatchEvent(new vpaidEvent(vpaidEvent.AdVideoStart));
break;
case "AdVideoFirstQuartile":
dispatchEvent(new vpaidEvent(vpaidEvent.AdVideoFirstQuartile));
break;
case "AdVideoMidpoint":
dispatchEvent(new vpaidEvent(vpaidEvent.AdVideoMidpoint));
break;
case "AdVideoThirdQuartile":
dispatchEvent(new vpaidEvent(vpaidEvent.AdVideoThirdQuartile));
break;
case "AdVideoComplete":
dispatchEvent(new vpaidEvent(vpaidEvent.AdVideoComplete));
break;
case "AdStopped":
this.stopAd();
break;
case "AdUserClose":
dispatchEvent(new vpaidEvent(vpaidEvent.AdUserClose));
break;
case "AdClickThru":
this.onAdClick();
break;
case "AdError":
this.onError();
break;
case "CreativeLoaded":
this.onCreativeLoad();
break;
}
}
private function onCreativeLoad() : void
{
if(this.creativeLoadTimer)
{
this.creativeLoadTimer.stop();
this.creativeLoadTimer.removeEventListener(TimerEvent.TIMER,this.onTimer);
this.creativeLoadTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,this.timerComplete);
this.creativeLoadTimer = null;
}
this.adContainerSprite.dispatchEvent(new helperEvents(helperEvents.RemoveLoader));
}
private function onError() : void
{
dispatchEvent(new vpaidEvent(vpaidEvent.AdError));
this.stopAd();
}
protected function onTimer(param1:TimerEvent) : void
{
this.timeRemaining--;
}
public function onAdClick(event:Object = null) : void
{
var data:Object = { "playerHandles":true };
dispatchEvent(new vpaidEvent(vpaidEvent.AdClickThru, data));
ExternalInterface.call("function setWMWindow() {window.open('" + this.clickThru + "');}");
stopAd();
}
public function stopAd() : void
{
if(this.creativeLoadTimer)
{
this.creativeLoadTimer.removeEventListener(TimerEvent.TIMER,this.onTimer);
this.creativeLoadTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,this.timerComplete);
this.creativeLoadTimer = null;
}
this.log("Stopping the display of the VPAID Ad");
ExternalInterface.call("closeVpaid");
dispatchEvent(new vpaidEvent(vpaidEvent.AdStopped));
}
public function resizeAd(param1:Number, param2:Number, param3:String) : void
{
this.log("resizeAd() width=" + param1 + ", height=" + param2 + ", viewMode=" + param3);
// this.initWidth = param1;
// this.initHeight = param2;
this.viewMode = param3;
}
public function pauseAd() : void
{
}
public function resumeAd() : void
{
}
public function expandAd() : void
{
}
public function collapseAd() : void
{
}
public function skipAd() : void
{
}
}
}
|
package com.ozg.adcore.vpaid
{
import flash.display.Sprite;
import flash.utils.Timer;
import flash.external.ExternalInterface;
import com.ozg.events.vpaidEvent;
import flash.events.TimerEvent;
import com.ozg.events.helperEvents;
import flash.system.Security;
import flash.net.navigateToURL;
import flash.net.URLRequest;
import flash.net.URLLoader;
public class vpaidLinearFullPage extends Sprite implements IVPAID
{
public function vpaidLinearFullPage()
{
super();
Security.allowDomain("*");
mouseEnabled = false;
}
private static const VPAID_VERSION:String = "1.1";
protected var creativeLoadTimer:Timer;
protected var creativeLoadTimeout:Number = 15;
protected var creativePath:String;
protected var clickUrl:String;
protected var timeRemaining:Number;
protected var adPlayerVolume:Number;
protected var initWidth:Number;
protected var initHeight:Number;
private var viewMode:String;
private var adContainerSprite:Sprite;
protected var isLinearAd:Boolean = true;
private var clickThru:String;
private var impressionURL:String;
public function getVPAID() : Object
{
return this;
}
public function get adLinear() : Boolean
{
return this.isLinearAd;
}
public function get adExpanded() : Boolean
{
return false;
}
public function get adRemainingTime() : Number
{
return this.timeRemaining;
}
public function get adVolume() : Number
{
return this.adPlayerVolume;
}
public function set adVolume(param1:Number) : void
{
this.adPlayerVolume = param1;
}
public function handshakeVersion(param1:String) : String
{
this.log("The player supports VPAID version " + param1 + " and the ad supports " + VPAID_VERSION);
return VPAID_VERSION;
}
protected function log(param1:String) : void
{
var _loc2_:Object = {"message":param1};
dispatchEvent(new vpaidEvent(vpaidEvent.AdLog,_loc2_));
}
public function initAd(param1:Number, param2:Number, param3:String, param4:Number, param5:String, param6:String) : void
{
this.handleData(param5);
this.resizeAd(param1,param2,param3);
this.loadAd();
}
protected function handleData(param1:String) : void
{
var xmlData:XML = null;
var creativeData:String = param1;
if(creativeData != null)
{
try
{
xmlData = new XML(creativeData);
this.creativePath = xmlData.setting;
this.creativeLoadTimeout = xmlData.duration;
this.clickThru = xmlData.clickThru;
this.impressionURL = xmlData.impressionURL;
initWidth = xmlData.creativeWidth;
initHeight = xmlData.creativeHeight;
handleVpaidEvent('AdImpression');
var s:SendAndLoadExample = new SendAndLoadExample();
s.sendData(impressionURL,'no message');
}
catch(e:Error)
{
onError();
}
}
else
{
this.onError();
}
if(creativeData != null)
{
return;
}
}
protected function loadAd() : void
{
dispatchEvent(new vpaidEvent(vpaidEvent.AdLoaded));
}
public function startAd() : void
{
this.log("Beginning the display of the VPAID ad");
dispatchEvent(new vpaidEvent(vpaidEvent.AdStarted));
this.creativeLoadTimer = new Timer(1000,this.creativeLoadTimeout);
this.creativeLoadTimer.addEventListener(TimerEvent.TIMER,this.onTimer);
this.creativeLoadTimer.addEventListener(TimerEvent.TIMER_COMPLETE,this.timerComplete);
this.creativeLoadTimer.start();
this.addJsCallbacks();
this.addEventListeners();
this.adContainerSprite = new adContainer(this.initWidth,this.initHeight);
addChild(this.adContainerSprite);
}
private function timerComplete(param1:TimerEvent) : void
{
this.stopAd();
}
private function addJsCallbacks() : void
{
ExternalInterface.addCallback("handleVpaidEvent",this.handleVpaidEvent);
ExternalInterface.addCallback("getPlayerVolume",this.getAdPlayerVolume);
ExternalInterface.call("initVpaid",creativePath,this.initWidth,this.initHeight);
}
private function getAdPlayerVolume() : void
{
//js will come here
}
private function addEventListeners() : void
{
addEventListener(vpaidEvent.AdUserClose,this.userClose);
}
private function userClose(param1:vpaidEvent) : void
{
this.stopAd();
}
protected function handleVpaidEvent(param1:String) : void
{
// ExternalInterface.call('console.log','param : '+param1);
switch(param1)
{
case "AdImpression":
dispatchEvent(new vpaidEvent(vpaidEvent.AdImpression));
break;
case "AdVideoStart":
dispatchEvent(new vpaidEvent(vpaidEvent.AdVideoStart));
break;
case "AdVideoFirstQuartile":
dispatchEvent(new vpaidEvent(vpaidEvent.AdVideoFirstQuartile));
break;
case "AdVideoMidpoint":
dispatchEvent(new vpaidEvent(vpaidEvent.AdVideoMidpoint));
break;
case "AdVideoThirdQuartile":
dispatchEvent(new vpaidEvent(vpaidEvent.AdVideoThirdQuartile));
break;
case "AdVideoComplete":
dispatchEvent(new vpaidEvent(vpaidEvent.AdVideoComplete));
break;
case "AdStopped":
this.stopAd();
break;
case "AdUserClose":
dispatchEvent(new vpaidEvent(vpaidEvent.AdUserClose));
break;
case "AdClickThru":
this.onAdClick();
break;
case "AdError":
this.onError();
break;
case "CreativeLoaded":
this.onCreativeLoad();
break;
}
}
private function onCreativeLoad() : void
{
if(this.creativeLoadTimer)
{
this.creativeLoadTimer.stop();
this.creativeLoadTimer.removeEventListener(TimerEvent.TIMER,this.onTimer);
this.creativeLoadTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,this.timerComplete);
this.creativeLoadTimer = null;
}
this.adContainerSprite.dispatchEvent(new helperEvents(helperEvents.RemoveLoader));
}
private function onError() : void
{
dispatchEvent(new vpaidEvent(vpaidEvent.AdError));
this.stopAd();
}
protected function onTimer(param1:TimerEvent) : void
{
this.timeRemaining--;
}
public function onAdClick(event:Object = null) : void
{
var data:Object = { "playerHandles":true };
dispatchEvent(new vpaidEvent(vpaidEvent.AdClickThru, data));
ExternalInterface.call("function setWMWindow() {window.open('" + this.clickThru + "');}");
stopAd();
}
public function stopAd() : void
{
if(this.creativeLoadTimer)
{
this.creativeLoadTimer.removeEventListener(TimerEvent.TIMER,this.onTimer);
this.creativeLoadTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,this.timerComplete);
this.creativeLoadTimer = null;
}
this.log("Stopping the display of the VPAID Ad");
ExternalInterface.call("closeVpaid");
dispatchEvent(new vpaidEvent(vpaidEvent.AdStopped));
}
public function resizeAd(param1:Number, param2:Number, param3:String) : void
{
this.log("resizeAd() width=" + param1 + ", height=" + param2 + ", viewMode=" + param3);
// this.initWidth = param1;
// this.initHeight = param2;
this.viewMode = param3;
}
public function pauseAd() : void
{
}
public function resumeAd() : void
{
}
public function expandAd() : void
{
}
public function collapseAd() : void
{
}
public function skipAd() : void
{
}
}
}
|
Update vpaidLinearFullPage.as
|
Update vpaidLinearFullPage.as
|
ActionScript
|
mit
|
ozgurersil/VPAID
|
c07d823bdd37bcc42bdf180e0b0a96992b610ae7
|
com/ozg/utils/loadingAnimation.as
|
com/ozg/utils/loadingAnimation.as
|
package com.ozg.utils
{
import flash.display.Sprite;
import flash.utils.Timer;
import flash.events.TimerEvent;
import com.ozg.events.helperEvents;
public class loadingAnimation extends Sprite
{
public function loadingAnimation(param1:Number = 16777215)
{
super();
this.animationColor = param1;
this.animation = new Sprite();
addChild(this.animation);
this.makeAnimation();
}
private var animation:Sprite;
private var rotate:Number = 0;
private var animationTimer:Timer;
private var animationColor:Number;
private var animationStopped:Boolean = false;
public function stopAnimation() : void
{
if(this.animationStopped == false)
{
removeChild(this.animation);
this.animationTimer.removeEventListener(TimerEvent.TIMER,this.rotateMe);
this.animationTimer.stop();
this.animationStopped = true;
}
}
private function makeAnimation() : void
{
this.renderAnimation();
addEventListener(helperEvents.RemoveLoader,this.removeLoaderHandler);
this.animationTimer = new Timer(70);
this.animationTimer.addEventListener(TimerEvent.TIMER,this.rotateMe);
this.animationTimer.start();
}
private function removeLoaderHandler(param1:helperEvents) : void
{
this.stopAnimation();
}
private function rotateMe(param1:TimerEvent) : void
{
this.rotate = this.rotate + 30;
if(this.rotate == 360)
{
this.rotate = 0;
}
this.renderAnimation(this.rotate);
}
private function renderAnimation(param1:Number = 0) : void
{
var _loc4_:Sprite = null;
this.clearAnimation();
var _loc2_:Sprite = new Sprite();
var _loc3_:uint = 0;
while(_loc3_ <= 12)
{
_loc4_ = this.getShape();
_loc4_.rotation = _loc3_ * 30 + param1;
_loc4_.alpha = 0 + 1 / 12 * _loc3_;
_loc2_.addChild(_loc4_);
_loc3_++;
}
this.animation.addChild(_loc2_);
}
private function clearAnimation() : void
{
if(this.animation.numChildren == 0)
{
return;
}
this.animation.removeChildAt(0);
}
private function getShape() : Sprite
{
var _loc1_:Sprite = new Sprite();
_loc1_.graphics.beginFill(this.animationColor,1);
_loc1_.graphics.moveTo(-1,-12);
_loc1_.graphics.lineTo(2,-12);
_loc1_.graphics.lineTo(1,-5);
_loc1_.graphics.lineTo(0,-5);
_loc1_.graphics.lineTo(-1,-12);
_loc1_.graphics.endFill();
return _loc1_;
}
}
}
|
package com.ozg.utils
{
import flash.display.Sprite;
public class loadingAnimation extends Sprite
{
public function loadingAnimation(param1:Number = 16777215)
{
super();
}
}
}
|
comment outs
|
comment outs
|
ActionScript
|
mit
|
ozgurersil/VPAID
|
95698ee114141d46057c480eff2c38439febea5f
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
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.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
if (value != _frustumCulling)
{
_frustumCulling = value;
if (value == FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
_mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
}
else if (_mesh && _mesh.scene)
{
_mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
testCulling();
}
}
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider(
{ computedVisibility : true },
'MeshVisibilityDataProvider',
DataProviderUsage.EXCLUSIVE
);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
{
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
}
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
propertyName : String,
bindingName : String,
value : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (_mesh && _mesh.geometry && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.ns.minko_math;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
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.enum.FrustumCulling;
import aerys.minko.type.math.BoundingBox;
import aerys.minko.type.math.BoundingSphere;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
/**
* The MeshVisibilityController watches the Mesh and the active Camera of a Scene
* to determine whether the object is actually inside the view frustum or not.
*
* @author Jean-Marc Le Roux
*
*/
public final class MeshVisibilityController extends AbstractController
{
use namespace minko_math;
private static const TMP_VECTOR4 : Vector4 = new Vector4();
private static const STATE_UNDEFINED : uint = 0;
private static const STATE_INSIDE : uint = 1;
private static const STATE_OUTSIDE : uint = 2;
private var _mesh : Mesh;
private var _state : uint;
private var _lastTest : int;
private var _boundingBox : BoundingBox;
private var _boundingSphere : BoundingSphere;
private var _data : DataProvider;
private var _frustumCulling : uint;
private var _insideFrustum : Boolean;
public function get frustumCulling() : uint
{
return _frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
if (value != _frustumCulling)
{
_frustumCulling = value;
if (value == FrustumCulling.DISABLED)
{
_data.computedVisibility = true;
if (_mesh.localToWorldTransformChanged.hasCallback(meshLocalToWorldChangedHandler))
{
_mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
}
}
else if (_mesh && _mesh.scene)
{
_mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
testCulling();
}
}
}
public function get insideFrustum() : Boolean
{
return _insideFrustum;
}
public function get computedVisibility() : Boolean
{
return _data.computedVisibility;
}
public function MeshVisibilityController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
_data = new DataProvider(
{ computedVisibility : true },
'MeshVisibilityDataProvider',
DataProviderUsage.EXCLUSIVE
);
_boundingBox = new BoundingBox(Vector4.ZERO, Vector4.ONE);
_boundingSphere = new BoundingSphere(Vector4.ZERO, 0.);
_state = STATE_UNDEFINED;
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
if (_mesh != null)
throw new Error();
_mesh = target;
target.added.add(addedHandler);
target.removed.add(removedHandler);
if (target.root is Scene)
addedHandler(target, target.root as Scene);
if (_frustumCulling)
testCulling();
}
private function targetRemovedHandler(ctrl : MeshVisibilityController,
target : Mesh) : void
{
_mesh = null;
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
if (target.root is Scene)
removedHandler(target, target.root as Scene);
}
private function addedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = mesh.scene;
if (!scene)
return ;
scene.bindings.addCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
{
meshLocalToWorldChangedHandler(mesh, mesh.getLocalToWorldTransform());
mesh.localToWorldTransformChanged.add(meshLocalToWorldChangedHandler);
}
mesh.computedVisibilityChanged.add(computedVisiblityChangedHandler);
mesh.bindings.addProvider(_data);
}
private function removedHandler(mesh : Mesh, ancestor : Group) : void
{
var scene : Scene = ancestor.scene;
if (!scene)
return ;
scene.bindings.removeCallback('worldToScreen', worldToScreenChangedHandler);
if (_frustumCulling)
mesh.localToWorldTransformChanged.remove(meshLocalToWorldChangedHandler);
mesh.computedVisibilityChanged.remove(computedVisiblityChangedHandler);
mesh.bindings.removeProvider(_data);
}
private function computedVisiblityChangedHandler(node : ISceneNode,
computedVisibility : Boolean) : void
{
_data.computedVisibility = computedVisibility;
}
private function worldToScreenChangedHandler(bindings : DataBindings,
propertyName : String,
bindingName : String,
value : Matrix4x4) : void
{
testCulling();
}
private function meshLocalToWorldChangedHandler(mesh : Mesh, transform : Matrix4x4) : void
{
var geom : Geometry = _mesh.geometry;
var culling : uint = _frustumCulling;
if (!geom.boundingBox || !geom.boundingSphere || culling == FrustumCulling.DISABLED)
return ;
if (culling & FrustumCulling.BOX)
transform.transformRawVectors(geom.boundingBox._vertices, _boundingBox._vertices);
if (culling & FrustumCulling.SPHERE)
{
var center : Vector4 = transform.transformVector(geom.boundingSphere.center);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE);
var radius : Number = geom.boundingSphere.radius * Math.max(
Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z)
);
_boundingSphere.update(center, radius);
}
testCulling();
}
private function testCulling() : void
{
var culling : uint = _frustumCulling;
if (_mesh && _mesh.geometry && _mesh.geometry.boundingBox && _mesh.visible)
{
var camera : AbstractCamera = (_mesh.root as Scene).activeCamera;
if (!camera)
return ;
_lastTest = camera.frustum.testBoundingVolume(
_boundingSphere,
_boundingBox,
null,
culling,
_lastTest
);
var inside : Boolean = _lastTest == -1;
if (inside && _state != STATE_INSIDE)
{
_insideFrustum = true;
_data.computedVisibility = _mesh.parent.computedVisibility && _mesh.visible;
_mesh.computedVisibilityChanged.execute(_mesh, computedVisibility);
_state = STATE_INSIDE;
}
else if (!inside && _state != STATE_OUTSIDE)
{
_insideFrustum = false;
_data.computedVisibility = false;
_mesh.computedVisibilityChanged.execute(_mesh, false);
_state = STATE_OUTSIDE;
}
}
}
override public function clone() : AbstractController
{
return new MeshVisibilityController();
}
}
}
|
Update src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
|
Update src/aerys/minko/scene/controller/mesh/MeshVisibilityController.as
fix bug with set frustumCulling = FrustumCulling.DISABLED
example:
```
var m:Mesh = new Mesh(CubeGeometry.cubeGeometry, new BasicMaterial({ diffuseColor : 0xff00ff00 } ));
m.frustumCulling = FrustumCulling.DISABLED;
scene.addChild(m);
```
result:
Error: This callback does not exist.
at aerys.minko.type::Signal/remove()[\aerys\minko\type\Signal.as:98]
at aerys.minko.scene.controller.mesh::MeshVisibilityController/set frustumCulling()[\aerys\minko\scene\controller\mesh\MeshVisibilityController.as:62]
at aerys.minko.scene.node::Mesh/set frustumCulling()[\aerys\minko\scene\node\Mesh.as:155]
|
ActionScript
|
mit
|
aerys/minko-as3
|
b15a2d2471a246503062077d11cefd750abcee0d
|
src/main/as/com/threerings/presents/client/ClientDObjectMgr.as
|
src/main/as/com/threerings/presents/client/ClientDObjectMgr.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2011 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/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.presents.client {
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getTimer;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.presents.dobj.CompoundEvent;
import com.threerings.presents.dobj.DEvent;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.dobj.ObjectAccessError;
import com.threerings.presents.dobj.ObjectDestroyedEvent;
import com.threerings.presents.dobj.Subscriber;
import com.threerings.presents.net.BootstrapNotification;
import com.threerings.presents.net.CompoundDownstreamMessage;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.net.EventNotification;
import com.threerings.presents.net.FailureResponse;
import com.threerings.presents.net.ForwardEventRequest;
import com.threerings.presents.net.ObjectResponse;
import com.threerings.presents.net.PongResponse;
import com.threerings.presents.net.SubscribeRequest;
import com.threerings.presents.net.UnsubscribeRequest;
import com.threerings.presents.net.UnsubscribeResponse;
import com.threerings.presents.net.UpdateThrottleMessage;
/**
* The client distributed object manager manages a set of proxy objects
* which mirror the distributed objects maintained on the server.
* Requests for modifications, etc. are forwarded to the server and events
* are dispatched from the server to this client for objects to which this
* client is subscribed.
*/
public class ClientDObjectMgr
implements DObjectManager
{
private static const log :Log = Log.getLog(ClientDObjectMgr);
/**
* Constructs a client distributed object manager.
*
* @param comm a communicator instance by which it can communicate
* with the server.
* @param client a reference to the client that is managing this whole
* communications and event dispatch business.
*/
public function ClientDObjectMgr (comm :Communicator, client :Client)
{
_comm = comm;
_client = client;
// register a flush interval
_flushInterval = new Timer(FLUSH_INTERVAL);
_flushInterval.addEventListener(TimerEvent.TIMER, flushObjects);
_flushInterval.start();
}
// documentation inherited from interface DObjectManager
public function isManager (object :DObject) :Boolean
{
// we are never authoritative in the present implementation
return false;
}
// inherit documentation from the interface DObjectManager
public function subscribeToObject (oid :int, target :Subscriber) :void
{
if (oid <= 0) {
target.requestFailed(oid, new ObjectAccessError("Invalid oid " + oid + "."));
} else {
doSubscribe(oid, target);
}
}
// inherit documentation from the interface DObjectManager
public function unsubscribeFromObject (oid :int, target :Subscriber) :void
{
doUnsubscribe(oid, target);
}
// inherit documentation from the interface
public function postEvent (event :DEvent) :void
{
// send a forward event request to the server
_comm.postMessage(new ForwardEventRequest(event));
}
// inherit documentation from the interface
public function removedLastSubscriber (
obj :DObject, deathWish :Boolean) :void
{
// if this object has a registered flush delay, don't can it just
// yet, just slip it onto the flush queue
for each (var dclass :Class in _delays.keys()) {
if (obj is dclass) {
var expire :Number = getTimer() + Number(_delays.get(dclass));
_flushes.put(obj.getOid(), new FlushRecord(obj, expire));
// log.info("Flushing " + obj.getOid() + " at " +
// new java.util.Date(expire));
return;
}
}
// if we didn't find a delay registration, flush immediately
flushObject(obj);
}
/**
* Registers an object flush delay.
*
* @see Client#registerFlushDelay
*/
public function registerFlushDelay (objclass :Class, delay :Number) :void
{
_delays.put(objclass, delay);
}
/**
* Called by the communicator when a downstream message arrives from
* the network layer. We queue it up for processing and request some
* processing time on the main thread.
*/
public function processMessage (msg :DownstreamMessage) :void
{
// do the proper thing depending on the object
if (msg is EventNotification) {
var evt :DEvent = (msg as EventNotification).getEvent();
// log.info("Dispatch event: " + evt);
dispatchEvent(evt);
} else if (msg is BootstrapNotification) {
_client.gotBootstrap((msg as BootstrapNotification).getData(), this);
} else if (msg is ObjectResponse) {
registerObjectAndNotify((msg as ObjectResponse).getObject());
} else if (msg is UnsubscribeResponse) {
var oid :int = (msg as UnsubscribeResponse).getOid();
if (_dead.remove(oid) == null) {
log.warning("Received unsub ACK from unknown object [oid=" + oid + "].");
}
} else if (msg is FailureResponse) {
notifyFailure((msg as FailureResponse).getOid(), (msg as FailureResponse).getMessage());
} else if (msg is PongResponse) {
_client.gotPong(msg as PongResponse);
} else if (msg is UpdateThrottleMessage) {
_client.setOutgoingMessageThrottle((msg as UpdateThrottleMessage).messagesPerSec);
} else if (msg is CompoundDownstreamMessage) {
for each (var submsg :DownstreamMessage in CompoundDownstreamMessage(msg).msgs) {
processMessage(submsg);
}
}
}
/**
* Called when a new event arrives from the server that should be
* dispatched to subscribers here on the client.
*/
protected function dispatchEvent (event :DEvent) :void
{
// if this is a compound event, we need to process its contained
// events in order
if (event is CompoundEvent) {
var events :Array = (event as CompoundEvent).getEvents();
var ecount :int = events.length;
for (var ii :int = 0; ii < ecount; ii++) {
dispatchEvent(events[ii] as DEvent);
}
return;
}
// look up the object on which we're dispatching this event
var toid :int = event.getTargetOid();
var target :DObject = (_ocache.get(toid) as DObject);
if (target == null) {
if (_dead.get(toid) == null) {
log.warning("Unable to dispatch event on non-proxied " +
"object [event=" + event + "].");
}
return;
}
try {
// apply the event to the object
var notify :Boolean = event.applyToObject(target);
// if this is an object destroyed event, we need to remove the
// object from our object table
if (event is ObjectDestroyedEvent) {
// log.info("Pitching destroyed object " +
// "[oid=" + toid + ", class=" +
// StringUtil.shortClassName(target) + "].");
_ocache.remove(toid);
}
// have the object pass this event on to its listeners
if (notify) {
target.notifyListeners(event);
}
} catch (e :Error) {
log.warning("Failure processing event", "event", event, "target", target, e);
}
}
/**
* Registers this object in our proxy cache and notifies the
* subscribers that were waiting for subscription to this object.
*/
protected function registerObjectAndNotify (obj :DObject) :void
{
// let the object know that we'll be managing it
obj.setManager(this);
var oid :int = obj.getOid();
// stick the object into the proxy object table
_ocache.put(oid, obj);
// let the penders know that the object is available
var req :PendingRequest = (_penders.remove(oid) as PendingRequest);
if (req == null) {
log.warning("Got object, but no one cares?! " +
"[oid=" + oid + ", obj=" + obj + "].");
return;
}
// log.debug("Got object: pendReq=" + req);
for each (var target :Subscriber in req.targets) {
// log.debug("Notifying subscriber: " + target);
// add them as a subscriber
obj.addSubscriber(target);
// and let them know that the object is in
target.objectAvailable(obj);
}
}
/**
* Notifies the subscribers that had requested this object (for subscription) that it is not
* available.
*/
protected function notifyFailure (oid :int, message :String) :void
{
// let the penders know that the object is not available
var req :PendingRequest = (_penders.remove(oid) as PendingRequest);
if (req == null) {
log.warning("Failed to get object, but no one cares?! [oid=" + oid + "].");
return;
}
for each (var target :Subscriber in req.targets) {
// and let them know that the object is in
target.requestFailed(oid, new ObjectAccessError(message));
}
}
/**
* This is guaranteed to be invoked via the invoker and can safely do
* main thread type things like call back to the subscriber.
*/
protected function doSubscribe (oid :int, target :Subscriber) :void
{
// log.info("doSubscribe: " + oid + ": " + target);
// first see if we've already got the object in our table
var obj :DObject = (_ocache.get(oid) as DObject);
if (obj != null) {
// clear the object out of the flush table if it's in there
_flushes.remove(oid);
// add the subscriber and call them back straight away
obj.addSubscriber(target);
target.objectAvailable(obj);
return;
}
// see if we've already got an outstanding request for this object
var req :PendingRequest = (_penders.get(oid) as PendingRequest);
if (req != null) {
// add this subscriber to the list of subscribers to be
// notified when the request is satisfied
req.addTarget(target);
return;
}
// otherwise we need to create a new request
req = new PendingRequest(oid);
req.addTarget(target);
_penders.put(oid, req);
// log.info("Registering pending request [oid=" + oid + "].");
// and issue a request to get things rolling
_comm.postMessage(new SubscribeRequest(oid));
}
/**
* This is guaranteed to be invoked via the invoker and can safely do
* main thread type things like call back to the subscriber.
*/
protected function doUnsubscribe (oid :int, target :Subscriber) :void
{
var dobj :DObject = (_ocache.get(oid) as DObject);
if (dobj != null) {
dobj.removeSubscriber(target);
} else {
log.info("Requested to remove subscriber from " +
"non-proxied object [oid=" + oid +
", sub=" + target + "].");
}
}
/**
* Flushes a distributed object subscription, issuing an unsubscribe
* request to the server.
*/
protected function flushObject (obj :DObject) :void
{
// move this object into the dead pool so that we don't claim to
// have it around anymore; once our unsubscribe message is
// processed, it'll be 86ed
var ooid :int = obj.getOid();
_ocache.remove(ooid);
_dead.put(ooid, obj);
// ship off an unsubscribe message to the server; we'll remove the
// object from our table when we get the unsub ack
_comm.postMessage(new UnsubscribeRequest(ooid));
}
/**
* Called periodically to flush any objects that have been lingering
* due to a previously enacted flush delay.
*/
protected function flushObjects (event :TimerEvent) :void
{
var now :Number = getTimer();
for each (var oid :int in _flushes.keys()) {
var rec :FlushRecord = (_flushes.get(oid) as FlushRecord);
if (rec.expire <= now) {
_flushes.remove(oid);
flushObject(rec.obj);
}
}
}
/** A reference to the communicator that sends and receives messages
* for this client. */
protected var _comm :Communicator;
/** A reference to our client instance. */
protected var _client :Client;
/** All of the distributed objects that are active on this client. */
protected var _ocache :Map = Maps.newMapOf(int);
/** Objects that have been marked for death. */
protected var _dead :Map = Maps.newMapOf(int);
/** Pending object subscriptions. */
protected var _penders :Map = Maps.newMapOf(int);
/** A mapping from distributed object class to flush delay. */
protected var _delays :Map = Maps.newMapOf(int);
/** A set of objects waiting to be flushed. */
protected var _flushes :Map = Maps.newMapOf(int);
/** Flushes objects every now and again. */
protected var _flushInterval :Timer;
/** Flush expired objects every 30 seconds. */
protected static const FLUSH_INTERVAL :Number = 30 * 1000;
}
}
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.Subscriber;
class PendingRequest
{
public var oid :int;
public var targets :Array = new Array();
public function PendingRequest (oid :int)
{
this.oid = oid;
}
public function addTarget (target :Subscriber) :void
{
targets.push(target);
}
}
/** Used to manage pending object flushes. */
class FlushRecord
{
/** The object to be flushed. */
public var obj :DObject;
/** The time at which we flush it. */
public var expire :Number;
public function FlushRecord (obj :DObject, expire :Number)
{
this.obj = obj;
this.expire = expire;
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2011 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/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.presents.client {
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.utils.getTimer;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.presents.dobj.CompoundEvent;
import com.threerings.presents.dobj.DEvent;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.dobj.ObjectAccessError;
import com.threerings.presents.dobj.ObjectDestroyedEvent;
import com.threerings.presents.dobj.Subscriber;
import com.threerings.presents.net.BootstrapNotification;
import com.threerings.presents.net.CompoundDownstreamMessage;
import com.threerings.presents.net.DownstreamMessage;
import com.threerings.presents.net.EventNotification;
import com.threerings.presents.net.FailureResponse;
import com.threerings.presents.net.ForwardEventRequest;
import com.threerings.presents.net.ObjectResponse;
import com.threerings.presents.net.PongResponse;
import com.threerings.presents.net.SubscribeRequest;
import com.threerings.presents.net.UnsubscribeRequest;
import com.threerings.presents.net.UnsubscribeResponse;
import com.threerings.presents.net.UpdateThrottleMessage;
/**
* The client distributed object manager manages a set of proxy objects
* which mirror the distributed objects maintained on the server.
* Requests for modifications, etc. are forwarded to the server and events
* are dispatched from the server to this client for objects to which this
* client is subscribed.
*/
public class ClientDObjectMgr
implements DObjectManager
{
private static const log :Log = Log.getLog(ClientDObjectMgr);
/**
* Constructs a client distributed object manager.
*
* @param comm a communicator instance by which it can communicate
* with the server.
* @param client a reference to the client that is managing this whole
* communications and event dispatch business.
*/
public function ClientDObjectMgr (comm :Communicator, client :Client)
{
_comm = comm;
_client = client;
// register a flush interval
_flushInterval = new Timer(FLUSH_INTERVAL);
_flushInterval.addEventListener(TimerEvent.TIMER, flushObjects);
_flushInterval.start();
}
// documentation inherited from interface DObjectManager
public function isManager (object :DObject) :Boolean
{
// we are never authoritative in the present implementation
return false;
}
// inherit documentation from the interface DObjectManager
public function subscribeToObject (oid :int, target :Subscriber) :void
{
if (oid <= 0) {
target.requestFailed(oid, new ObjectAccessError("Invalid oid " + oid + "."));
} else {
doSubscribe(oid, target);
}
}
// inherit documentation from the interface DObjectManager
public function unsubscribeFromObject (oid :int, target :Subscriber) :void
{
doUnsubscribe(oid, target);
}
// inherit documentation from the interface
public function postEvent (event :DEvent) :void
{
// send a forward event request to the server
_comm.postMessage(new ForwardEventRequest(event));
}
// inherit documentation from the interface
public function removedLastSubscriber (
obj :DObject, deathWish :Boolean) :void
{
// if this object has a registered flush delay, don't can it just
// yet, just slip it onto the flush queue
for each (var dclass :Class in _delays.keys()) {
if (obj is dclass) {
var expire :Number = getTimer() + Number(_delays.get(dclass));
_flushes.put(obj.getOid(), new FlushRecord(obj, expire));
// log.info("Flushing " + obj.getOid() + " at " +
// new java.util.Date(expire));
return;
}
}
// if we didn't find a delay registration, flush immediately
flushObject(obj);
}
/**
* Registers an object flush delay.
*
* @see Client#registerFlushDelay
*/
public function registerFlushDelay (objclass :Class, delay :Number) :void
{
_delays.put(objclass, delay);
}
/**
* Called by the communicator when a downstream message arrives from
* the network layer. We queue it up for processing and request some
* processing time on the main thread.
*/
public function processMessage (msg :DownstreamMessage) :void
{
// do the proper thing depending on the object
if (msg is EventNotification) {
var evt :DEvent = (msg as EventNotification).getEvent();
// log.info("Dispatch event: " + evt);
dispatchEvent(evt);
} else if (msg is BootstrapNotification) {
_client.gotBootstrap((msg as BootstrapNotification).getData(), this);
} else if (msg is ObjectResponse) {
registerObjectAndNotify((msg as ObjectResponse).getObject());
} else if (msg is UnsubscribeResponse) {
var oid :int = (msg as UnsubscribeResponse).getOid();
if (_dead.remove(oid) == null) {
log.warning("Received unsub ACK from unknown object [oid=" + oid + "].");
}
} else if (msg is FailureResponse) {
notifyFailure((msg as FailureResponse).getOid(), (msg as FailureResponse).getMessage());
} else if (msg is PongResponse) {
_client.gotPong(msg as PongResponse);
} else if (msg is UpdateThrottleMessage) {
_client.setOutgoingMessageThrottle((msg as UpdateThrottleMessage).messagesPerSec);
} else if (msg is CompoundDownstreamMessage) {
for each (var submsg :DownstreamMessage in CompoundDownstreamMessage(msg).msgs) {
processMessage(submsg);
}
}
}
/**
* Called when a new event arrives from the server that should be
* dispatched to subscribers here on the client.
*/
protected function dispatchEvent (event :DEvent) :void
{
// if this is a compound event, we need to process its contained
// events in order
if (event is CompoundEvent) {
var events :Array = (event as CompoundEvent).getEvents();
var ecount :int = events.length;
for (var ii :int = 0; ii < ecount; ii++) {
dispatchEvent(events[ii] as DEvent);
}
return;
}
// look up the object on which we're dispatching this event
var toid :int = event.getTargetOid();
var target :DObject = (_ocache.get(toid) as DObject);
if (target == null) {
if (_dead.get(toid) == null) {
log.warning("Unable to dispatch event on non-proxied " +
"object [event=" + event + "].");
}
return;
}
try {
// apply the event to the object
var notify :Boolean = event.applyToObject(target);
// if this is an object destroyed event, we need to remove the
// object from our object table
if (event is ObjectDestroyedEvent) {
// log.info("Pitching destroyed object " +
// "[oid=" + toid + ", class=" +
// StringUtil.shortClassName(target) + "].");
_ocache.remove(toid);
}
// have the object pass this event on to its listeners
if (notify) {
target.notifyListeners(event);
}
} catch (e :Error) {
log.warning("Failure processing event", "event", event, "target", target, e);
}
}
/**
* Registers this object in our proxy cache and notifies the
* subscribers that were waiting for subscription to this object.
*/
protected function registerObjectAndNotify (obj :DObject) :void
{
// let the object know that we'll be managing it
obj.setManager(this);
var oid :int = obj.getOid();
// stick the object into the proxy object table
_ocache.put(oid, obj);
// let the penders know that the object is available
var req :PendingRequest = (_penders.remove(oid) as PendingRequest);
if (req == null) {
log.warning("Got object, but no one cares?! " +
"[oid=" + oid + ", obj=" + obj + "].");
return;
}
// log.debug("Got object: pendReq=" + req);
for each (var target :Subscriber in req.targets) {
// log.debug("Notifying subscriber: " + target);
// add them as a subscriber
obj.addSubscriber(target);
// and let them know that the object is in
target.objectAvailable(obj);
}
}
/**
* Notifies the subscribers that had requested this object (for subscription) that it is not
* available.
*/
protected function notifyFailure (oid :int, message :String) :void
{
// let the penders know that the object is not available
var req :PendingRequest = (_penders.remove(oid) as PendingRequest);
if (req == null) {
log.warning("Failed to get object, but no one cares?! [oid=" + oid + "].");
return;
}
for each (var target :Subscriber in req.targets) {
// and let them know that the object is in
target.requestFailed(oid, new ObjectAccessError(message));
}
}
/**
* This is guaranteed to be invoked via the invoker and can safely do
* main thread type things like call back to the subscriber.
*/
protected function doSubscribe (oid :int, target :Subscriber) :void
{
// log.info("doSubscribe: " + oid + ": " + target);
// first see if we've already got the object in our table
var obj :DObject = (_ocache.get(oid) as DObject);
if (obj != null) {
// clear the object out of the flush table if it's in there
_flushes.remove(oid);
// add the subscriber and call them back straight away
obj.addSubscriber(target);
target.objectAvailable(obj);
return;
}
// see if we've already got an outstanding request for this object
var req :PendingRequest = (_penders.get(oid) as PendingRequest);
if (req != null) {
// add this subscriber to the list of subscribers to be
// notified when the request is satisfied
req.addTarget(target);
return;
}
// otherwise we need to create a new request
req = new PendingRequest(oid);
req.addTarget(target);
_penders.put(oid, req);
// log.info("Registering pending request [oid=" + oid + "].");
// and issue a request to get things rolling
_comm.postMessage(new SubscribeRequest(oid));
}
/**
* This is guaranteed to be invoked via the invoker and can safely do
* main thread type things like call back to the subscriber.
*/
protected function doUnsubscribe (oid :int, target :Subscriber) :void
{
var dobj :DObject = (_ocache.get(oid) as DObject);
if (dobj != null) {
dobj.removeSubscriber(target);
} else {
log.info("Requested to remove subscriber from " +
"non-proxied object [oid=" + oid +
", sub=" + target + "].");
}
}
/**
* Flushes a distributed object subscription, issuing an unsubscribe
* request to the server.
*/
protected function flushObject (obj :DObject) :void
{
// move this object into the dead pool so that we don't claim to
// have it around anymore; once our unsubscribe message is
// processed, it'll be 86ed
var ooid :int = obj.getOid();
_ocache.remove(ooid);
obj.setManager(null);
_dead.put(ooid, obj);
// ship off an unsubscribe message to the server; we'll remove the
// object from our table when we get the unsub ack
_comm.postMessage(new UnsubscribeRequest(ooid));
}
/**
* Called periodically to flush any objects that have been lingering
* due to a previously enacted flush delay.
*/
protected function flushObjects (event :TimerEvent) :void
{
var now :Number = getTimer();
for each (var oid :int in _flushes.keys()) {
var rec :FlushRecord = (_flushes.get(oid) as FlushRecord);
if (rec.expire <= now) {
_flushes.remove(oid);
flushObject(rec.obj);
}
}
}
/** A reference to the communicator that sends and receives messages
* for this client. */
protected var _comm :Communicator;
/** A reference to our client instance. */
protected var _client :Client;
/** All of the distributed objects that are active on this client. */
protected var _ocache :Map = Maps.newMapOf(int);
/** Objects that have been marked for death. */
protected var _dead :Map = Maps.newMapOf(int);
/** Pending object subscriptions. */
protected var _penders :Map = Maps.newMapOf(int);
/** A mapping from distributed object class to flush delay. */
protected var _delays :Map = Maps.newMapOf(int);
/** A set of objects waiting to be flushed. */
protected var _flushes :Map = Maps.newMapOf(int);
/** Flushes objects every now and again. */
protected var _flushInterval :Timer;
/** Flush expired objects every 30 seconds. */
protected static const FLUSH_INTERVAL :Number = 30 * 1000;
}
}
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.Subscriber;
class PendingRequest
{
public var oid :int;
public var targets :Array = new Array();
public function PendingRequest (oid :int)
{
this.oid = oid;
}
public function addTarget (target :Subscriber) :void
{
targets.push(target);
}
}
/** Used to manage pending object flushes. */
class FlushRecord
{
/** The object to be flushed. */
public var obj :DObject;
/** The time at which we flush it. */
public var expire :Number;
public function FlushRecord (obj :DObject, expire :Number)
{
this.obj = obj;
this.expire = expire;
}
}
|
Clear out the manager on the DObject when it's no longer active
|
Clear out the manager on the DObject when it's no longer active
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@6725 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
34bae8282a85530d9a5b5481aadb7db237b339e1
|
frameworks/projects/apache/tests/promises/cases/PromisesJIRATests.as
|
frameworks/projects/apache/tests/promises/cases/PromisesJIRATests.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 promises.cases
{
import flash.events.TimerEvent;
import flash.net.URLRequest;
import flash.utils.Timer;
import flashx.textLayout.debug.assert;
import org.apache.flex.promises.Promise;
import org.apache.flex.promises.interfaces.IThenable;
import org.flexunit.asserts.assertEquals;
import org.flexunit.async.Async;
public class PromisesJIRATests
{
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
private var expected_:*;
private var promise_:IThenable;
private var got_:*;
private var timer_:Timer;
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
//----------------------------------
// parseGot_
//----------------------------------
private function parseGot_(value:*):void {
this.got_ = value;
}
//----------------------------------
// setUp
//----------------------------------
[Before(async)]
public function setUp():void
{
this.timer_ = new Timer(100, 1);
}
//----------------------------------
// tearDown
//----------------------------------
[After(async)]
public function tearDown():void
{
this.promise_ = null;
if (this.timer_)
{
this.timer_.stop();
this.timer_ = null;
}
}
//----------------------------------
// verifyGotType_
//----------------------------------
private function verifyGotType_(event:TimerEvent, result:*):void {
assertEquals(typeof this.expected_, this.got_);
}
//--------------------------------------------------------------------------
//
// Tests
//
//--------------------------------------------------------------------------
//----------------------------------
// test_FLEX34753
//----------------------------------
[Test(async)]
public function test_FLEX34753():void
{
Async.handleEvent(this, timer_, TimerEvent.TIMER_COMPLETE, verifyGotType_);
timer_.start();
promise_ = new Promise(function (fulfill:Function = null, reject:Function = null):*
{
var urlRequest:URLRequest = new URLRequest('http://flex.apache.org');
fulfill(urlRequest);
});
expected_ = '[object URLRequest]';
promise_.then(parseGot_);
}
}}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 promises.cases
{
import flash.events.TimerEvent;
import flash.net.URLRequest;
import flash.utils.Timer;
import org.apache.flex.promises.Promise;
import org.apache.flex.promises.interfaces.IThenable;
import org.flexunit.asserts.assertEquals;
import org.flexunit.async.Async;
public class PromisesJIRATests
{
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
private var expected_:*;
private var promise_:IThenable;
private var got_:*;
private var timer_:Timer;
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
//----------------------------------
// parseGot_
//----------------------------------
private function parseGot_(value:*):void {
this.got_ = value;
}
//----------------------------------
// setUp
//----------------------------------
[Before(async)]
public function setUp():void
{
this.timer_ = new Timer(100, 1);
}
//----------------------------------
// tearDown
//----------------------------------
[After(async)]
public function tearDown():void
{
this.promise_ = null;
if (this.timer_)
{
this.timer_.stop();
this.timer_ = null;
}
}
//----------------------------------
// verifyGotType_
//----------------------------------
private function verifyGotType_(event:TimerEvent, result:*):void {
assertEquals(this.expected_, this.got_.toString());
}
//--------------------------------------------------------------------------
//
// Tests
//
//--------------------------------------------------------------------------
//----------------------------------
// test_FLEX34753
//----------------------------------
[Test(async)]
public function test_FLEX34753():void
{
Async.handleEvent(this, timer_, TimerEvent.TIMER_COMPLETE, verifyGotType_);
timer_.start();
promise_ = new Promise(function (fulfill:Function = null, reject:Function = null):*
{
var urlRequest:URLRequest = new URLRequest('http://flex.apache.org');
fulfill(urlRequest);
});
expected_ = '[object URLRequest]';
promise_.then(parseGot_);
}
}}
|
Fix test for FLEX-34753
|
Fix test for FLEX-34753
Signed-off-by: Erik de Bruin <[email protected]>
|
ActionScript
|
apache-2.0
|
danteinforno/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk
|
131cb5d83a69849f6eefc05e71046734cc2c7abe
|
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
|
inesaloulou21/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,inesaloulou21/arisgames,augustozuniga/arisgames,augustozuniga/arisgames
|
ddccab58e87fb632a86324859564f5495cadccdd
|
test/src/FRESteamWorksTest.as
|
test/src/FRESteamWorksTest.as
|
/*
* FRESteamWorks.h
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package
{
import com.amanitadesign.steam.FRESteamWorks;
import com.amanitadesign.steam.SteamConstants;
import com.amanitadesign.steam.SteamEvent;
import com.amanitadesign.steam.WorkshopConstants;
import flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.ByteArray;
public class FRESteamWorksTest extends Sprite
{
public var Steamworks:FRESteamWorks = new FRESteamWorks();
public var tf:TextField;
private var _buttonPos:int = 5;
private var _appId:uint;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.x = 160;
tf.width = stage.stageWidth - tf.x;
tf.height = stage.stageHeight;
addChild(tf);
addButton("Check stats/achievements", checkAchievements);
addButton("Toggle achievement", toggleAchievement);
addButton("Toggle cloud enabled", toggleCloudEnabled);
addButton("Toggle file", toggleFile);
addButton("Publish file", publishFile);
addButton("Toggle fullscreen", toggleFullscreen);
addButton("Show Friends overlay", activateOverlay);
addButton("List subscribed files", enumerateSubscribedFiles);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
try {
//Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20");
if(!Steamworks.init()){
log("STEAMWORKS API is NOT available");
return;
}
log("STEAMWORKS API is available\n");
log("User ID: " + Steamworks.getUserID());
_appId = Steamworks.getAppID();
log("App ID: " + _appId);
log("Persona name: " + Steamworks.getPersonaName());
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp());
log("getFileCount() == "+Steamworks.getFileCount());
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt'));
log("getDLCCount() == " + Steamworks.getDLCCount());
Steamworks.resetAllStats(true);
} catch(e:Error) {
log("*** ERROR ***");
log(e.message);
log(e.getStackTrace());
}
}
private function log(value:String):void{
tf.appendText(value+"\n");
tf.scrollV = tf.maxScrollV;
}
public function writeFileToCloud(fileName:String, data:String):Boolean {
var dataOut:ByteArray = new ByteArray();
dataOut.writeUTFBytes(data);
return Steamworks.fileWrite(fileName, dataOut);
}
public function readFileFromCloud(fileName:String):String {
var dataIn:ByteArray = new ByteArray();
var result:String;
dataIn.position = 0;
dataIn.length = Steamworks.getFileSize(fileName);
if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){
result = dataIn.readUTFBytes(dataIn.length);
}
return result;
}
private function checkAchievements(e:Event = null):void {
if(!Steamworks.isReady) return;
// current stats and achievement ids are from steam example app
log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME"));
log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE"));
log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3));
log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2));
Steamworks.storeStats();
log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames'));
log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled'));
}
private function toggleAchievement(e:Event = null):void{
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME");
log("isAchievement('ACH_WIN_ONE_GAME') == " + result);
if(!result) {
log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME"));
} else {
log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME"));
}
}
private function toggleCloudEnabled(e:Event = null):void {
if(!Steamworks.isReady) return;
var enabled:Boolean = Steamworks.isCloudEnabledForApp();
log("isCloudEnabledForApp() == " + enabled);
log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled));
log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp());
}
private function toggleFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.fileExists('test.txt');
log("fileExists('test.txt') == " + result);
if(result){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
}
private function publishFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId,
"Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private,
["TestTag"], WorkshopConstants.FILETYPE_Community);
log("publishWorkshopFile('test.txt' ...) == " + res);
}
private function toggleFullscreen(e:Event = null):void {
if(stage.displayState == StageDisplayState.NORMAL)
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
stage.displayState = StageDisplayState.NORMAL;
}
private function activateOverlay(e:Event = null):void {
if(!Steamworks.isReady) return;
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
}
private function enumerateSubscribedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0));
}
private function onSteamResponse(e:SteamEvent):void{
switch(e.req_type){
case SteamConstants.RESPONSE_OnUserStatsStored:
log("RESPONSE_OnUserStatsStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnUserStatsReceived:
log("RESPONSE_OnUserStatsReceived: "+e.response);
break;
case SteamConstants.RESPONSE_OnAchievementStored:
log("RESPONSE_OnAchievementStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnPublishWorkshopFile:
log("RESPONSE_OnPublishWorkshopFile: " + e.response);
var file:String = Steamworks.publishWorkshopFileResult();
log("File published as " + file);
log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file));
break;
case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles:
log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response);
var result:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + result.resultsReturned + "/" + result.totalResults);
for(var i:int = 0; i < result.resultsReturned; i++)
log(i + ": " + result.publishedFileId[i] + " (" + result.timeSubscribed[i] + ")");
break;
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
private function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
private function addButton(label:String, callback:Function):void {
var button:Sprite = new Sprite();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
button.buttonMode = true;
button.useHandCursor = true;
button.addEventListener(MouseEvent.CLICK, callback);
button.x = 5;
button.y = _buttonPos;
_buttonPos += button.height + 5;
button.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xccccccc);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
button.addEventListener(MouseEvent.MOUSE_OUT, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
var text:TextField = new TextField();
text.text = label;
text.width = 140;
text.height = 25;
text.x = 5;
text.y = 5;
text.mouseEnabled = false;
button.addChild(text);
addChild(button);
}
}
}
|
/*
* FRESteamWorks.h
* This file is part of FRESteamWorks.
*
* Created by David ´Oldes´ Oliva on 3/29/12.
* Contributors: Ventero <http://github.com/Ventero>
* Copyright (c) 2012 Amanita Design. All rights reserved.
* Copyright (c) 2012-2013 Level Up Labs, LLC. All rights reserved.
*/
package
{
import com.amanitadesign.steam.FRESteamWorks;
import com.amanitadesign.steam.SteamConstants;
import com.amanitadesign.steam.SteamEvent;
import com.amanitadesign.steam.WorkshopConstants;
import flash.desktop.NativeApplication;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.StageDisplayState;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.utils.ByteArray;
public class FRESteamWorksTest extends Sprite
{
public var Steamworks:FRESteamWorks = new FRESteamWorks();
public var tf:TextField;
private var _buttonPos:int = 5;
private var _appId:uint;
public function FRESteamWorksTest()
{
tf = new TextField();
tf.x = 160;
tf.width = stage.stageWidth - tf.x;
tf.height = stage.stageHeight;
addChild(tf);
addButton("Check stats/achievements", checkAchievements);
addButton("Toggle achievement", toggleAchievement);
addButton("Toggle cloud enabled", toggleCloudEnabled);
addButton("Toggle file", toggleFile);
addButton("Publish file", publishFile);
addButton("Toggle fullscreen", toggleFullscreen);
addButton("Show Friends overlay", activateOverlay);
addButton("List subscribed files", enumerateSubscribedFiles);
Steamworks.addEventListener(SteamEvent.STEAM_RESPONSE, onSteamResponse);
NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExit);
try {
//Steamworks.useCrashHandler(480, "1.0", "Feb 20 2013", "21:42:20");
if(!Steamworks.init()){
log("STEAMWORKS API is NOT available");
return;
}
log("STEAMWORKS API is available\n");
log("User ID: " + Steamworks.getUserID());
_appId = Steamworks.getAppID();
log("App ID: " + _appId);
log("Persona name: " + Steamworks.getPersonaName());
log("isCloudEnabledForApp() == "+Steamworks.isCloudEnabledForApp());
log("getFileCount() == "+Steamworks.getFileCount());
log("fileExists('test.txt') == "+Steamworks.fileExists('test.txt'));
log("getDLCCount() == " + Steamworks.getDLCCount());
Steamworks.resetAllStats(true);
} catch(e:Error) {
log("*** ERROR ***");
log(e.message);
log(e.getStackTrace());
}
}
private function log(value:String):void{
tf.appendText(value+"\n");
tf.scrollV = tf.maxScrollV;
}
public function writeFileToCloud(fileName:String, data:String):Boolean {
var dataOut:ByteArray = new ByteArray();
dataOut.writeUTFBytes(data);
return Steamworks.fileWrite(fileName, dataOut);
}
public function readFileFromCloud(fileName:String):String {
var dataIn:ByteArray = new ByteArray();
var result:String;
dataIn.position = 0;
dataIn.length = Steamworks.getFileSize(fileName);
if(dataIn.length>0 && Steamworks.fileRead(fileName,dataIn)){
result = dataIn.readUTFBytes(dataIn.length);
}
return result;
}
private function checkAchievements(e:Event = null):void {
if(!Steamworks.isReady) return;
// current stats and achievement ids are from steam example app
log("isAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.isAchievement("ACH_WIN_ONE_GAME"));
log("isAchievement('ACH_TRAVEL_FAR_SINGLE') == "+Steamworks.isAchievement("ACH_TRAVEL_FAR_SINGLE"));
log("setStatFloat('FeetTraveled') == "+Steamworks.setStatFloat('FeetTraveled', 21.3));
log("setStatInt('NumGames', 2) == "+Steamworks.setStatInt('NumGames', 2));
Steamworks.storeStats();
log("getStatInt('NumGames') == "+Steamworks.getStatInt('NumGames'));
log("getStatFloat('FeetTraveled') == "+Steamworks.getStatFloat('FeetTraveled'));
}
private function toggleAchievement(e:Event = null):void{
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.isAchievement("ACH_WIN_ONE_GAME");
log("isAchievement('ACH_WIN_ONE_GAME') == " + result);
if(!result) {
log("setAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.setAchievement("ACH_WIN_ONE_GAME"));
} else {
log("clearAchievement('ACH_WIN_ONE_GAME') == "+Steamworks.clearAchievement("ACH_WIN_ONE_GAME"));
}
}
private function toggleCloudEnabled(e:Event = null):void {
if(!Steamworks.isReady) return;
var enabled:Boolean = Steamworks.isCloudEnabledForApp();
log("isCloudEnabledForApp() == " + enabled);
log("setCloudEnabledForApp(" + !enabled + ") == " + Steamworks.setCloudEnabledForApp(!enabled));
log("isCloudEnabledForApp() == " + Steamworks.isCloudEnabledForApp());
}
private function toggleFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var result:Boolean = Steamworks.fileExists('test.txt');
log("fileExists('test.txt') == " + result);
if(result){
log("readFileFromCloud('test.txt') == "+readFileFromCloud('test.txt') );
log("fileDelete('test.txt') == "+Steamworks.fileDelete('test.txt'));
} else {
log("writeFileToCloud('test.txt','click') == "+writeFileToCloud('test.txt','click'));
}
}
private function publishFile(e:Event = null):void {
if(!Steamworks.isReady) return;
var res:Boolean = Steamworks.publishWorkshopFile("test.txt", "", _appId,
"Test.txt", "Test.txt", WorkshopConstants.VISIBILITY_Private,
["TestTag"], WorkshopConstants.FILETYPE_Community);
log("publishWorkshopFile('test.txt' ...) == " + res);
}
private function toggleFullscreen(e:Event = null):void {
if(stage.displayState == StageDisplayState.NORMAL)
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
else
stage.displayState = StageDisplayState.NORMAL;
}
private function activateOverlay(e:Event = null):void {
if(!Steamworks.isReady) return;
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
log("activateGameOverlay('Friends') == " + Steamworks.activateGameOverlay("Friends"));
log("isOverlayEnabled() == " + Steamworks.isOverlayEnabled());
}
private function enumerateSubscribedFiles(e:Event = null):void {
if(!Steamworks.isReady) return;
log("enumerateUserSubscribedFiles(0) == " + Steamworks.enumerateUserSubscribedFiles(0));
}
private var id:String;
private function onSteamResponse(e:SteamEvent):void{
switch(e.req_type){
case SteamConstants.RESPONSE_OnUserStatsStored:
log("RESPONSE_OnUserStatsStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnUserStatsReceived:
log("RESPONSE_OnUserStatsReceived: "+e.response);
break;
case SteamConstants.RESPONSE_OnAchievementStored:
log("RESPONSE_OnAchievementStored: "+e.response);
break;
case SteamConstants.RESPONSE_OnPublishWorkshopFile:
log("RESPONSE_OnPublishWorkshopFile: " + e.response);
var file:String = Steamworks.publishWorkshopFileResult();
log("File published as " + file);
log("subscribePublishedFile(...) == " + Steamworks.subscribePublishedFile(file));
break;
case SteamConstants.RESPONSE_OnEnumerateUserSubscribedFiles:
log("RESPONSE_OnEnumerateUserSubscribedFiles: " + e.response);
var result:SubscribedFilesResult = Steamworks.enumerateUserSubscribedFilesResult();
log("User subscribed files: " + result.resultsReturned + "/" + result.totalResults);
for(var i:int = 0; i < result.resultsReturned; i++) {
id = result.publishedFileId[i];
var apiCall:Boolean = Steamworks.getPublishedFileDetails(result.publishedFileId[i]);
log(i + ": " + result.publishedFileId[i] + " (" + result.timeSubscribed[i] + ") - " + apiCall);
}
break;
case SteamConstants.RESPONSE_OnGetPublishedFileDetails:
log("RESPONSE_OnGetPublishedFileDetails: " + e.response);
var res:FileDetailsResult = Steamworks.getPublishedFileDetailsResult(id);
log("Result for " + id + ": " + res);
if(res)
log("File: " + res.fileName + ", handle: " + res.fileHandle);
break;
default:
log("STEAMresponse type:"+e.req_type+" response:"+e.response);
}
}
private function onExit(e:Event):void{
log("Exiting application, cleaning up");
Steamworks.dispose();
}
private function addButton(label:String, callback:Function):void {
var button:Sprite = new Sprite();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
button.buttonMode = true;
button.useHandCursor = true;
button.addEventListener(MouseEvent.CLICK, callback);
button.x = 5;
button.y = _buttonPos;
_buttonPos += button.height + 5;
button.addEventListener(MouseEvent.MOUSE_OVER, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xccccccc);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
button.addEventListener(MouseEvent.MOUSE_OUT, function(e:MouseEvent):void {
button.graphics.clear();
button.graphics.beginFill(0xaaaaaa);
button.graphics.drawRoundRect(0, 0, 150, 30, 5, 5);
button.graphics.endFill();
});
var text:TextField = new TextField();
text.text = label;
text.width = 140;
text.height = 25;
text.x = 5;
text.y = 5;
text.mouseEnabled = false;
button.addChild(text);
addChild(button);
}
}
}
|
Add test for PublishedFileDetails
|
Add test for PublishedFileDetails
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
57d016ac759eab031e9a62285be53ec256422791
|
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
|
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2016 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.model.CustomWidgetType;
import com.esri.builder.model.WidgetType;
import com.esri.builder.supportClasses.FileUtil;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
import modules.IBuilderModule;
import modules.supportClasses.CustomXMLModule;
import mx.core.FlexGlobals;
import mx.events.ModuleEvent;
import mx.modules.IModuleInfo;
import mx.modules.ModuleManager;
public class WidgetTypeLoader extends EventDispatcher
{
internal static var loadedModuleInfos:Array = [];
private var swf:File;
private var config:File;
//need reference when loading to avoid being garbage collected before load completes
private var moduleInfo:IModuleInfo;
//requires either swf or config
public function WidgetTypeLoader(swf:File = null, config:File = null)
{
this.swf = swf;
this.config = config;
}
public function get name():String
{
var fileName:String;
if (swf && swf.exists)
{
fileName = FileUtil.getFileName(swf);
}
else if (config && config.exists)
{
fileName = FileUtil.getFileName(config);
}
return fileName;
}
public function load():void
{
if (swf && swf.exists)
{
loadModule();
}
else if (!swf.exists && config.exists)
{
loadConfigModule();
}
else
{
dispatchError();
}
}
private function loadConfigModule():void
{
var moduleConfig:XML = readModuleConfig(config);
if (moduleConfig)
{
var customWidgetType:CustomWidgetType = parseCustomWidgetType(moduleConfig);
if (customWidgetType)
{
dispatchComplete(customWidgetType);
return;
}
}
dispatchError();
}
private function loadModule():void
{
moduleInfo = ModuleManager.getModule(swf.url);
if (moduleInfo.ready)
{
moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
moduleInfo.release();
moduleInfo.unload();
}
else
{
var fileBytes:ByteArray = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(swf, FileMode.READ);
fileStream.readBytes(fileBytes);
fileStream.close();
moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.load(null, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory);
}
}
private function moduleInfo_unloadHandler(event:ModuleEvent):void
{
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
var moduleInfoIndex:int = loadedModuleInfos.indexOf(moduleInfo);
if (moduleInfoIndex > -1)
{
loadedModuleInfos.splice(moduleInfoIndex, 1);
}
this.moduleInfo = null;
FlexGlobals.topLevelApplication.callLater(loadModule);
}
private function moduleInfo_readyHandler(event:ModuleEvent):void
{
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
if (config && config.exists)
{
var moduleConfig:XML = readModuleConfig(config);
}
const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule;
if (builderModule)
{
var widgetType:WidgetType = getWidgetType(moduleInfo, builderModule, moduleConfig);
}
loadedModuleInfos.push(moduleInfo);
this.moduleInfo = null;
dispatchComplete(widgetType);
}
private function dispatchComplete(widgetType:WidgetType):void
{
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_COMPLETE, widgetType));
}
private function getWidgetType(moduleInfo:IModuleInfo, builderModule:IBuilderModule, moduleConfig:XML):WidgetType
{
var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url;
var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1);
if (moduleConfig)
{
var configXML:XML = moduleConfig.configuration[0];
var version:String = moduleConfig.widgetversion[0];
}
return isCustomModule ?
new CustomWidgetType(builderModule, version, configXML) :
new WidgetType(builderModule);
}
private function readModuleConfig(configFile:File):XML
{
var configXML:XML;
var fileStream:FileStream = new FileStream();
try
{
fileStream.open(configFile, FileMode.READ);
configXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
}
catch (e:Error)
{
//ignore
}
finally
{
fileStream.close();
}
return configXML;
}
private function moduleInfo_errorHandler(event:ModuleEvent):void
{
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
this.moduleInfo = null;
dispatchError();
}
private function dispatchError():void
{
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_ERROR));
}
private function parseCustomWidgetType(configXML:XML):CustomWidgetType
{
var customModule:CustomXMLModule = new CustomXMLModule();
customModule.widgetName = configXML.name;
customModule.isOpenByDefault = (configXML.openbydefault == 'true');
var widgetLabel:String = configXML.label[0];
var widgetDescription:String = configXML.description[0];
var widgetHelpURL:String = configXML.helpurl[0];
var widgetConfiguration:XML = configXML.configuration[0] ? configXML.configuration[0] : <configuration/>;
var widgetVersion:String = configXML.widgetversion[0];
customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName);
customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName;
customModule.widgetDescription = widgetDescription ? widgetDescription : "";
customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : "";
return new CustomWidgetType(customModule, widgetVersion, widgetConfiguration);
}
private function createWidgetIconPath(iconPath:String, widgetName:String):String
{
var widgetIconPath:String;
if (iconPath)
{
widgetIconPath = "widgets/" + widgetName + "/" + iconPath;
}
else
{
widgetIconPath = "assets/images/i_widget.png";
}
return widgetIconPath;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2016 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.model.CustomWidgetType;
import com.esri.builder.model.WidgetType;
import com.esri.builder.supportClasses.FileUtil;
import com.esri.builder.supportClasses.LogUtil;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
import modules.IBuilderModule;
import modules.supportClasses.CustomXMLModule;
import mx.core.FlexGlobals;
import mx.events.ModuleEvent;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.modules.IModuleInfo;
import mx.modules.ModuleManager;
public class WidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader);
internal static var loadedModuleInfos:Array = [];
private var swf:File;
private var config:File;
//need reference when loading to avoid being garbage collected before load completes
private var moduleInfo:IModuleInfo;
//requires either swf or config
public function WidgetTypeLoader(swf:File = null, config:File = null)
{
this.swf = swf;
this.config = config;
}
public function get name():String
{
var fileName:String;
if (swf && swf.exists)
{
fileName = FileUtil.getFileName(swf);
}
else if (config && config.exists)
{
fileName = FileUtil.getFileName(config);
}
return fileName;
}
public function load():void
{
if (swf && swf.exists)
{
loadModule();
}
else if (!swf.exists && config.exists)
{
loadConfigModule();
}
else
{
dispatchError();
}
}
private function loadConfigModule():void
{
if (Log.isInfo())
{
LOG.info('Loading XML module: {0}', config.url);
}
var moduleConfig:XML = readModuleConfig(config);
if (moduleConfig)
{
var customWidgetType:CustomWidgetType = parseCustomWidgetType(moduleConfig);
if (customWidgetType)
{
dispatchComplete(customWidgetType);
return;
}
}
dispatchError();
}
private function loadModule():void
{
if (Log.isInfo())
{
LOG.info('Loading SWF module: {0}', swf.url);
}
moduleInfo = ModuleManager.getModule(swf.url);
if (moduleInfo.ready)
{
if (Log.isInfo())
{
LOG.info('Unloading module: {0}', swf.url);
}
moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
moduleInfo.release();
moduleInfo.unload();
}
else
{
if (Log.isInfo())
{
LOG.info('Loading module: {0}', swf.url);
}
var fileBytes:ByteArray = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(swf, FileMode.READ);
fileStream.readBytes(fileBytes);
fileStream.close();
moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.load(null, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory);
}
}
private function moduleInfo_unloadHandler(event:ModuleEvent):void
{
if (Log.isInfo())
{
LOG.info('Module unloaded: {0}', swf.url);
}
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
var moduleInfoIndex:int = loadedModuleInfos.indexOf(moduleInfo);
if (moduleInfoIndex > -1)
{
loadedModuleInfos.splice(moduleInfoIndex, 1);
}
this.moduleInfo = null;
FlexGlobals.topLevelApplication.callLater(loadModule);
}
private function moduleInfo_readyHandler(event:ModuleEvent):void
{
if (Log.isInfo())
{
LOG.info('Module loaded: {0}', swf.url);
}
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
if (config && config.exists)
{
if (Log.isInfo())
{
LOG.info('Reading module config: {0}', config.url);
}
var moduleConfig:XML = readModuleConfig(config);
}
const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule;
if (builderModule)
{
if (Log.isInfo())
{
LOG.info('Widget type created for module: {0}', swf.url);
}
var widgetType:WidgetType = getWidgetType(moduleInfo, builderModule, moduleConfig);
}
loadedModuleInfos.push(moduleInfo);
this.moduleInfo = null;
dispatchComplete(widgetType);
}
private function dispatchComplete(widgetType:WidgetType):void
{
if (Log.isInfo())
{
LOG.info('Module load complete: {0}', name);
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_COMPLETE, widgetType));
}
private function getWidgetType(moduleInfo:IModuleInfo, builderModule:IBuilderModule, moduleConfig:XML):WidgetType
{
var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url;
var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1);
if (moduleConfig)
{
var configXML:XML = moduleConfig.configuration[0];
var version:String = moduleConfig.widgetversion[0];
}
return isCustomModule ?
new CustomWidgetType(builderModule, version, configXML) :
new WidgetType(builderModule);
}
private function readModuleConfig(configFile:File):XML
{
var configXML:XML;
var fileStream:FileStream = new FileStream();
try
{
fileStream.open(configFile, FileMode.READ);
configXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
}
catch (e:Error)
{
//ignore
if (Log.isInfo())
{
LOG.info('Could not read module config: {0}', e.toString());
}
}
finally
{
fileStream.close();
}
return configXML;
}
private function moduleInfo_errorHandler(event:ModuleEvent):void
{
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
this.moduleInfo = null;
dispatchError();
}
private function dispatchError():void
{
if (Log.isInfo())
{
LOG.info('Module load failed: {0}', name);
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_ERROR));
}
private function parseCustomWidgetType(configXML:XML):CustomWidgetType
{
if (Log.isInfo())
{
LOG.info('Creating widget type from XML: {0}', configXML);
}
var customModule:CustomXMLModule = new CustomXMLModule();
customModule.widgetName = configXML.name;
customModule.isOpenByDefault = (configXML.openbydefault == 'true');
var widgetLabel:String = configXML.label[0];
var widgetDescription:String = configXML.description[0];
var widgetHelpURL:String = configXML.helpurl[0];
var widgetConfiguration:XML = configXML.configuration[0] ? configXML.configuration[0] : <configuration/>;
var widgetVersion:String = configXML.widgetversion[0];
customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName);
customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName;
customModule.widgetDescription = widgetDescription ? widgetDescription : "";
customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : "";
return new CustomWidgetType(customModule, widgetVersion, widgetConfiguration);
}
private function createWidgetIconPath(iconPath:String, widgetName:String):String
{
var widgetIconPath:String;
if (iconPath)
{
widgetIconPath = "widgets/" + widgetName + "/" + iconPath;
}
else
{
widgetIconPath = "assets/images/i_widget.png";
}
return widgetIconPath;
}
}
}
|
Add logging to WidgetTypeLoader.
|
Add logging to WidgetTypeLoader.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
f475b23fb4845ee1bd34bf8d88581f16c96470eb
|
src/as/com/threerings/flex/LabeledSlider.as
|
src/as/com/threerings/flex/LabeledSlider.as
|
package com.threerings.flex {
import mx.containers.HBox;
import mx.controls.Label;
import mx.controls.sliderClasses.Slider;
import mx.events.SliderEvent;
/**
* A simple component that displays a label to the left of a slider.
*/
public class LabeledSlider extends HBox
{
/** The slider, all public and accessable. Don't fuck it up! */
public var slider :Slider;
/**
* Create a LabeledSlider holding the specified slider.
*/
public function LabeledSlider (slider :Slider)
{
_label = new Label();
_label.text = String(slider.value);
addChild(_label);
this.slider = slider;
slider.showDataTip = false; // because we do it...
addChild(slider);
slider.addEventListener(SliderEvent.CHANGE, handleSliderChange, false, 0, true);
}
protected function handleSliderChange (event :SliderEvent) :void
{
_label.text = String(event.value);
}
protected var _label :Label;
}
}
|
package com.threerings.flex {
import mx.containers.HBox;
import mx.controls.Label;
import mx.controls.sliderClasses.Slider;
import mx.events.SliderEvent;
/**
* A simple component that displays a label to the left of a slider.
*/
public class LabeledSlider extends HBox
{
/** The actual slider. */
public var slider :Slider;
/**
* Create a LabeledSlider holding the specified slider.
*/
public function LabeledSlider (slider :Slider)
{
_label = new Label();
_label.text = String(slider.value);
addChild(_label);
this.slider = slider;
slider.showDataTip = false; // because we do it...
addChild(slider);
slider.addEventListener(SliderEvent.CHANGE, handleSliderChange, false, 0, true);
}
protected function handleSliderChange (event :SliderEvent) :void
{
_label.text = String(event.value);
}
protected var _label :Label;
}
}
|
Clean up my comment, this is in a public API (and my comment wasn't helpful).
|
Clean up my comment, this is in a public API (and my comment wasn't helpful).
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@166 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
e56bfdde8545fe79bd55df48a7875f8a73b34867
|
src/aerys/minko/render/shader/compiler/graph/ShaderGraph.as
|
src/aerys/minko/render/shader/compiler/graph/ShaderGraph.as
|
package aerys.minko.render.shader.compiler.graph
{
import aerys.minko.Minko;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.Signature;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Interpolate;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.VariadicExtract;
import aerys.minko.render.shader.compiler.graph.visitors.*;
import aerys.minko.render.shader.compiler.register.Components;
import aerys.minko.render.shader.compiler.sequence.AgalInstruction;
import aerys.minko.type.log.DebugLevel;
import aerys.minko.type.stream.format.VertexComponent;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.Endian;
/**
* @private
* @author Romain Gilliotte
*
*/
public class ShaderGraph
{
private static const SPLITTER : SplitterVisitor = new SplitterVisitor();
private static const REMOVE_EXTRACT : RemoveExtractsVisitor = new RemoveExtractsVisitor();
private static const MERGER : MergeVisitor = new MergeVisitor();
private static const OVERWRITER_CLEANER : OverwriterCleanerVisitor = new OverwriterCleanerVisitor();
private static const RESOLVE_CONSTANT : ResolveConstantComputationVisitor = new ResolveConstantComputationVisitor();
private static const CONSTANT_PACKER : ConstantPackerVisitor = new ConstantPackerVisitor();
private static const CONSTANT_GROUPER : ConstantGrouperVisitor = new ConstantGrouperVisitor();
private static const RESOLVE_PARAMETRIZED : ResolveParametrizedComputationVisitor = new ResolveParametrizedComputationVisitor();
private static const REMOVE_USELESS : RemoveUselessComputation = new RemoveUselessComputation();
private static const COPY_INSERTER : CopyInserterVisitor = new CopyInserterVisitor();
private static const ALLOCATOR : AllocationVisitor = new AllocationVisitor();
private static const INTERPOLATE_FINDER : InterpolateFinder = new InterpolateFinder();
private static const WRITE_DOT : WriteDot = new WriteDot();
private static const MATRIX_TRANSFORMATION : MatrixTransformationGrouper = new MatrixTransformationGrouper();
private var _position : AbstractNode;
private var _positionComponents : uint;
private var _interpolates : Vector.<AbstractNode>;
private var _color : AbstractNode;
private var _colorComponents : uint;
private var _kills : Vector.<AbstractNode>;
private var _killComponents : Vector.<uint>;
private var _computableConstants : Object;
private var _isCompiled : Boolean;
private var _vertexSequence : Vector.<AgalInstruction>;
private var _fragmentSequence : Vector.<AgalInstruction>;
private var _bindings : Object;
private var _vertexComponents : Vector.<VertexComponent>;
private var _vertexIndices : Vector.<uint>;
private var _vsConstants : Vector.<Number>;
private var _fsConstants : Vector.<Number>;
private var _textures : Vector.<ITextureResource>;
public function get position() : AbstractNode { return _position; }
public function get interpolates() : Vector.<AbstractNode> { return _interpolates; }
public function get color() : AbstractNode { return _color; }
public function get kills() : Vector.<AbstractNode> { return _kills; }
public function get positionComponents() : uint { return _positionComponents; }
public function get colorComponents() : uint { return _colorComponents; }
public function get killComponents() : Vector.<uint> { return _killComponents; }
public function get computableConstants() : Object { return _computableConstants; }
public function set position (v : AbstractNode) : void { _position = v; }
public function set color (v : AbstractNode) : void { _color = v; }
public function set positionComponents (v : uint) : void { _positionComponents = v; }
public function set colorComponents (v : uint) : void { _colorComponents = v; }
public function ShaderGraph(position : AbstractNode,
color : AbstractNode,
kills : Vector.<AbstractNode>)
{
_isCompiled = false;
_position = position;
_positionComponents = Components.createContinuous(0, 0, 4, position.size);
_interpolates = new Vector.<AbstractNode>();
_color = color;
_colorComponents = Components.createContinuous(0, 0, 4, color.size);
_kills = kills;
_killComponents = new Vector.<uint>();
_computableConstants = new Object();
var numKills : uint = kills.length;
for (var killId : uint = 0; killId < numKills; ++killId)
_killComponents[killId] = Components.createContinuous(0, 0, 1, 1);
}
public function generateProgram(name : String, signature : Signature) : Program3DResource
{
if (!_isCompiled)
compile();
if (Minko.debugLevel & DebugLevel.SHADER_AGAL)
Minko.log(DebugLevel.SHADER_AGAL, generateAGAL());
var vsProgram : ByteArray = computeBinaryProgram(_vertexSequence, true);
var fsProgram : ByteArray = computeBinaryProgram(_fragmentSequence, false);
var program : Program3DResource = new Program3DResource(
name,
signature,
vsProgram,
fsProgram,
_vertexComponents,
_vertexIndices,
_vsConstants,
_fsConstants,
_textures,
_bindings
);
return program;
}
public function generateAGAL() : String
{
var instruction : AgalInstruction;
var shader : String = '';
if (!_isCompiled)
compile();
shader += "---------------- vertex shader ----------------\n";
for each (instruction in _vertexSequence)
shader += instruction.getAgal(true);
shader += "\n";
shader += "--------------- fragment shader ---------------\n";
for each (instruction in _fragmentSequence)
shader += instruction.getAgal(false);
return shader;
}
private function compile() : void
{
// execute consecutive visitors to optimize the shader graph.
// Warning: the order matters, do not swap lines.
// log shader in dotty format
MERGER .process(this); // merge duplicate nodes
REMOVE_EXTRACT .process(this); // remove all extract nodes
OVERWRITER_CLEANER .process(this); // remove nested overwriters
RESOLVE_CONSTANT .process(this); // resolve constant computation
CONSTANT_PACKER .process(this); // pack constants [0,0,0,1] => [0,1].xxxy
REMOVE_USELESS .process(this); // remove some useless operations (add 0, mul 0, mul 1...)
RESOLVE_PARAMETRIZED .process(this); // replace computations that depend on parameters by evalexp parameters
// MATRIX_TRANSFORMATION .process(this); // replace ((vector * matrix1) * matrix2) by vector * (matrix1 * matrix2) to save registers on GPU
// COPY_INSERTER .process(this); // ensure there are no operations between constants
SPLITTER .process(this); // clone nodes that are shared between vertex and fragment shader
CONSTANT_GROUPER .process(this); // group constants [0,1] & [0,2] => [0, 1, 2]
if (Minko.debugLevel & DebugLevel.SHADER_DOTTY)
{
WRITE_DOT.process(this);
Minko.log(DebugLevel.SHADER_DOTTY, WRITE_DOT.result);
WRITE_DOT.clear();
}
// generate final program
INTERPOLATE_FINDER .process(this); // find interpolate nodes. We may skip that in the future.
ALLOCATOR .process(this); // allocate memory and generate final code.
// retrieve program
_vertexSequence = ALLOCATOR.vertexSequence;
_fragmentSequence = ALLOCATOR.fragmentSequence;
_bindings = ALLOCATOR.parameterBindings;
_vertexComponents = ALLOCATOR.vertexComponents;
_vertexIndices = ALLOCATOR.vertexIndices;
_vsConstants = ALLOCATOR.vertexConstants;
_fsConstants = ALLOCATOR.fragmentConstants;
_textures = ALLOCATOR.textures;
ALLOCATOR.clear();
_isCompiled = true;
}
private function computeBinaryProgram(sequence : Vector.<AgalInstruction>,
isVertexShader : Boolean) : ByteArray
{
var program : ByteArray = new ByteArray();
program.endian = Endian.LITTLE_ENDIAN;
program.writeByte(0xa0); // tag version
program.writeUnsignedInt(1); // AGAL version, big endian, bit pattern will be 0x01000000
program.writeByte(0xa1); // tag program id
program.writeByte(isVertexShader ? 0 : 1); // vertex or fragment
for each (var instruction : AgalInstruction in sequence)
instruction.getBytecode(program);
return program;
}
}
}
|
package aerys.minko.render.shader.compiler.graph
{
import aerys.minko.Minko;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.render.shader.Signature;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Extract;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Instruction;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Interpolate;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.Overwriter;
import aerys.minko.render.shader.compiler.graph.nodes.vertex.VariadicExtract;
import aerys.minko.render.shader.compiler.graph.visitors.*;
import aerys.minko.render.shader.compiler.register.Components;
import aerys.minko.render.shader.compiler.sequence.AgalInstruction;
import aerys.minko.type.log.DebugLevel;
import aerys.minko.type.stream.format.VertexComponent;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.Endian;
/**
* @private
* @author Romain Gilliotte
*
*/
public class ShaderGraph
{
private static const SPLITTER : SplitterVisitor = new SplitterVisitor();
private static const REMOVE_EXTRACT : RemoveExtractsVisitor = new RemoveExtractsVisitor();
private static const MERGER : MergeVisitor = new MergeVisitor();
private static const OVERWRITER_CLEANER : OverwriterCleanerVisitor = new OverwriterCleanerVisitor();
private static const RESOLVE_CONSTANT : ResolveConstantComputationVisitor = new ResolveConstantComputationVisitor();
private static const CONSTANT_PACKER : ConstantPackerVisitor = new ConstantPackerVisitor();
private static const CONSTANT_GROUPER : ConstantGrouperVisitor = new ConstantGrouperVisitor();
private static const RESOLVE_PARAMETRIZED : ResolveParametrizedComputationVisitor = new ResolveParametrizedComputationVisitor();
private static const REMOVE_USELESS : RemoveUselessComputation = new RemoveUselessComputation();
private static const COPY_INSERTER : CopyInserterVisitor = new CopyInserterVisitor();
private static const ALLOCATOR : AllocationVisitor = new AllocationVisitor();
private static const INTERPOLATE_FINDER : InterpolateFinder = new InterpolateFinder();
private static const WRITE_DOT : WriteDot = new WriteDot();
private static const MATRIX_TRANSFORMATION : MatrixTransformationGrouper = new MatrixTransformationGrouper();
private var _position : AbstractNode;
private var _positionComponents : uint;
private var _interpolates : Vector.<AbstractNode>;
private var _color : AbstractNode;
private var _colorComponents : uint;
private var _kills : Vector.<AbstractNode>;
private var _killComponents : Vector.<uint>;
private var _computableConstants : Object;
private var _isCompiled : Boolean;
private var _vertexSequence : Vector.<AgalInstruction>;
private var _fragmentSequence : Vector.<AgalInstruction>;
private var _bindings : Object;
private var _vertexComponents : Vector.<VertexComponent>;
private var _vertexIndices : Vector.<uint>;
private var _vsConstants : Vector.<Number>;
private var _fsConstants : Vector.<Number>;
private var _textures : Vector.<ITextureResource>;
public function get position() : AbstractNode { return _position; }
public function get interpolates() : Vector.<AbstractNode> { return _interpolates; }
public function get color() : AbstractNode { return _color; }
public function get kills() : Vector.<AbstractNode> { return _kills; }
public function get positionComponents() : uint { return _positionComponents; }
public function get colorComponents() : uint { return _colorComponents; }
public function get killComponents() : Vector.<uint> { return _killComponents; }
public function get computableConstants() : Object { return _computableConstants; }
public function set position (v : AbstractNode) : void { _position = v; }
public function set color (v : AbstractNode) : void { _color = v; }
public function set positionComponents (v : uint) : void { _positionComponents = v; }
public function set colorComponents (v : uint) : void { _colorComponents = v; }
public function ShaderGraph(position : AbstractNode,
color : AbstractNode,
kills : Vector.<AbstractNode>)
{
_isCompiled = false;
_position = position;
_positionComponents = Components.createContinuous(0, 0, 4, position.size);
_interpolates = new Vector.<AbstractNode>();
_color = color;
_colorComponents = Components.createContinuous(0, 0, 4, color.size);
_kills = kills;
_killComponents = new Vector.<uint>();
_computableConstants = new Object();
var numKills : uint = kills.length;
for (var killId : uint = 0; killId < numKills; ++killId)
_killComponents[killId] = Components.createContinuous(0, 0, 1, 1);
}
public function generateProgram(name : String, signature : Signature) : Program3DResource
{
if (!_isCompiled)
compile();
if (Minko.debugLevel & DebugLevel.SHADER_AGAL)
Minko.log(DebugLevel.SHADER_AGAL, generateAGAL(name));
var vsProgram : ByteArray = computeBinaryProgram(_vertexSequence, true);
var fsProgram : ByteArray = computeBinaryProgram(_fragmentSequence, false);
var program : Program3DResource = new Program3DResource(
name,
signature,
vsProgram,
fsProgram,
_vertexComponents,
_vertexIndices,
_vsConstants,
_fsConstants,
_textures,
_bindings
);
return program;
}
public function generateAGAL(name : String) : String
{
var instruction : AgalInstruction;
var shader : String = name + "\n\n";
if (!_isCompiled)
compile();
shader += "---------------- vertex shader ----------------\n";
for each (instruction in _vertexSequence)
shader += instruction.getAgal(true);
shader += "\n";
shader += "--------------- fragment shader ---------------\n";
for each (instruction in _fragmentSequence)
shader += instruction.getAgal(false);
return shader;
}
private function compile() : void
{
// execute consecutive visitors to optimize the shader graph.
// Warning: the order matters, do not swap lines.
// log shader in dotty format
MERGER .process(this); // merge duplicate nodes
REMOVE_EXTRACT .process(this); // remove all extract nodes
OVERWRITER_CLEANER .process(this); // remove nested overwriters
RESOLVE_CONSTANT .process(this); // resolve constant computation
CONSTANT_PACKER .process(this); // pack constants [0,0,0,1] => [0,1].xxxy
REMOVE_USELESS .process(this); // remove some useless operations (add 0, mul 0, mul 1...)
RESOLVE_PARAMETRIZED .process(this); // replace computations that depend on parameters by evalexp parameters
// MATRIX_TRANSFORMATION .process(this); // replace ((vector * matrix1) * matrix2) by vector * (matrix1 * matrix2) to save registers on GPU
// COPY_INSERTER .process(this); // ensure there are no operations between constants
SPLITTER .process(this); // clone nodes that are shared between vertex and fragment shader
CONSTANT_GROUPER .process(this); // group constants [0,1] & [0,2] => [0, 1, 2]
if (Minko.debugLevel & DebugLevel.SHADER_DOTTY)
{
WRITE_DOT.process(this);
Minko.log(DebugLevel.SHADER_DOTTY, WRITE_DOT.result);
WRITE_DOT.clear();
}
// generate final program
INTERPOLATE_FINDER .process(this); // find interpolate nodes. We may skip that in the future.
ALLOCATOR .process(this); // allocate memory and generate final code.
// retrieve program
_vertexSequence = ALLOCATOR.vertexSequence;
_fragmentSequence = ALLOCATOR.fragmentSequence;
_bindings = ALLOCATOR.parameterBindings;
_vertexComponents = ALLOCATOR.vertexComponents;
_vertexIndices = ALLOCATOR.vertexIndices;
_vsConstants = ALLOCATOR.vertexConstants;
_fsConstants = ALLOCATOR.fragmentConstants;
_textures = ALLOCATOR.textures;
ALLOCATOR.clear();
_isCompiled = true;
}
private function computeBinaryProgram(sequence : Vector.<AgalInstruction>,
isVertexShader : Boolean) : ByteArray
{
var program : ByteArray = new ByteArray();
program.endian = Endian.LITTLE_ENDIAN;
program.writeByte(0xa0); // tag version
program.writeUnsignedInt(1); // AGAL version, big endian, bit pattern will be 0x01000000
program.writeByte(0xa1); // tag program id
program.writeByte(isVertexShader ? 0 : 1); // vertex or fragment
for each (var instruction : AgalInstruction in sequence)
instruction.getBytecode(program);
return program;
}
}
}
|
Add shader name to generateAGAL() debug output
|
Add shader name to generateAGAL() debug output
|
ActionScript
|
mit
|
aerys/minko-as3
|
17505db6becdcc32e21e61cb123e29db02d9579b
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/core/ContainerDataBinding.as
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/core/ContainerDataBinding.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 org.apache.flex.binding.ConstantBinding;
import org.apache.flex.binding.GenericBinding;
import org.apache.flex.binding.PropertyWatcher;
import org.apache.flex.binding.SimpleBinding;
import org.apache.flex.binding.WatcherBase;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The ContainerDataBinding class implements databinding for
* Container instances. Different classes can have
* different databinding implementation that optimize for
* the different lifecycles. For example, an item renderer
* databinding implementation can wait to execute databindings
* until the data property is set.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ContainerDataBinding extends DataBindingBase implements IBead
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ContainerDataBinding()
{
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("initBindings", initCompleteHandler);
}
private function initCompleteHandler(event:Event):void
{
var fieldWatcher:Object;
var sb:SimpleBinding;
var cb:ConstantBinding;
if (!("_bindings" in _strand))
return;
var bindingData:Array = _strand["_bindings"];
var n:int = bindingData[0];
var bindings:Array = [];
var i:int;
var index:int = 1;
for (i = 0; i < n; i++)
{
var binding:Object = {};
binding.source = bindingData[index++];
binding.destFunc = bindingData[index++];
binding.destination = bindingData[index++];
bindings.push(binding);
}
var watchers:Object = decodeWatcher(bindingData.slice(index));
for (i = 0; i < n; i++)
{
binding = bindings[i];
if (binding.source is Array)
{
if (binding.source[0] in _strand)
{
if (binding.source.length == 2 && binding.destination.length == 2)
{
// simple component.property binding
var destObject:Object;
var destination:IStrand;
// can be simplebinding or constantbinding
var compWatcher:Object = watchers.watcherMap[binding.source[0]];
fieldWatcher = compWatcher.children.watcherMap[binding.source[1]];
if (fieldWatcher.eventNames is String)
{
sb = new SimpleBinding();
sb.destinationPropertyName = binding.destination[1];
sb.eventName = fieldWatcher.eventNames as String;
sb.sourceID = binding.source[0];
sb.sourcePropertyName = binding.source[1];
sb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(sb);
else
{
if (destObject)
{
sb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
else if (fieldWatcher.eventNames == null)
{
cb = new ConstantBinding();
cb.destinationPropertyName = binding.destination[1];
cb.sourceID = binding.source[0];
cb.sourcePropertyName = binding.source[1];
cb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(cb);
else
{
if (destObject)
{
cb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
}
}
}
else if (binding.source is String && binding.destination is Array)
{
fieldWatcher = watchers.watcherMap[binding.source];
if (fieldWatcher == null)
{
cb = new ConstantBinding();
cb.destinationPropertyName = binding.destination[1];
cb.sourcePropertyName = binding.source;
cb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(cb);
else
{
if (destObject)
{
cb.destination = destObject;
_strand.addBead(cb);
}
else
{
deferredBindings[binding.destination[0]] = cb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
else if (fieldWatcher.eventNames is String)
{
sb = new SimpleBinding();
sb.destinationPropertyName = binding.destination[1];
sb.eventName = fieldWatcher.eventNames as String;
sb.sourcePropertyName = binding.source;
sb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(sb);
else
{
if (destObject)
{
sb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
}
else
{
makeGenericBinding(binding, i, watchers);
}
}
}
private function makeGenericBinding(binding:Object, index:int, watchers:Object):void
{
var gb:GenericBinding = new GenericBinding();
gb.setDocument(_strand);
gb.destinationData = binding.destination;
gb.destinationFunction = binding.destFunc;
gb.source = binding.source;
setupWatchers(gb, index, watchers.watchers, null);
}
private function setupWatchers(gb:GenericBinding, index:int, watchers:Array, parentWatcher:WatcherBase):void
{
var n:int = watchers.length;
for (var i:int = 0; i < n; i++)
{
var watcher:Object = watchers[i];
var isValidWatcher:Boolean = false;
if (typeof(watcher.bindings) == "number")
isValidWatcher = (watcher.bindings == index);
else
isValidWatcher = (watcher.bindings.indexOf(index) != -1);
if (isValidWatcher)
{
var type:String = watcher.type;
switch (type)
{
case "property":
{
var pw:PropertyWatcher = new PropertyWatcher(this,
watcher.propertyName,
watcher.eventNames,
watcher.getterFunction);
watcher.watcher = pw;
if (parentWatcher)
pw.parentChanged(parentWatcher.value);
else
pw.parentChanged(_strand);
if (parentWatcher)
parentWatcher.addChild(pw);
if (watcher.children == null)
pw.addBinding(gb);
break;
}
}
if (watcher.children)
{
setupWatchers(gb, index, watcher.children.watchers, watcher.watcher);
}
}
}
}
private function decodeWatcher(bindingData:Array):Object
{
var watcherMap:Object = {};
var watchers:Array = [];
var n:int = bindingData.length;
var index:int = 0;
var watcherData:Object;
// FalconJX adds an extra null to the data so make sure
// we have enough data for a complete watcher otherwise
// say we are done
while (index < n - 2)
{
var watcherIndex:int = bindingData[index++];
var type:int = bindingData[index++];
switch (type)
{
case 0:
{
watcherData = { type: "function" };
watcherData.functionName = bindingData[index++];
watcherData.paramFunction = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
break;
}
case 1:
{
watcherData = { type: "static" };
watcherData.propertyName = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherData.getterFunction = bindingData[index++];
watcherData.parentObj = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
case 2:
{
watcherData = { type: "property" };
watcherData.propertyName = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherData.getterFunction = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
case 3:
{
watcherData = { type: "xml" };
watcherData.propertyName = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
}
watcherData.children = bindingData[index++];
if (watcherData.children != null)
{
watcherData.children = decodeWatcher(watcherData.children);
}
watcherData.index = watcherIndex;
watchers.push(watcherData);
}
return { watchers: watchers, watcherMap: watcherMap };
}
private var deferredBindings:Object = {};
private function deferredBindingsHandler(event:Event):void
{
for (var p:String in deferredBindings)
{
if (_strand[p] != null)
{
var destination:IStrand = _strand[p] as IStrand;
destination.addBead(deferredBindings[p]);
delete deferredBindings[p];
}
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.binding.ConstantBinding;
import org.apache.flex.binding.GenericBinding;
import org.apache.flex.binding.PropertyWatcher;
import org.apache.flex.binding.SimpleBinding;
import org.apache.flex.binding.WatcherBase;
import org.apache.flex.core.IBead;
import org.apache.flex.core.IStrand;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The ContainerDataBinding class implements databinding for
* Container instances. Different classes can have
* different databinding implementation that optimize for
* the different lifecycles. For example, an item renderer
* databinding implementation can wait to execute databindings
* until the data property is set.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ContainerDataBinding extends DataBindingBase implements IBead
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ContainerDataBinding()
{
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("initBindings", initCompleteHandler);
}
private function initCompleteHandler(event:Event):void
{
var fieldWatcher:Object;
var sb:SimpleBinding;
var cb:ConstantBinding;
if (!("_bindings" in _strand))
return;
var bindingData:Array = _strand["_bindings"];
var n:int = bindingData[0];
var bindings:Array = [];
var i:int;
var index:int = 1;
for (i = 0; i < n; i++)
{
var binding:Object = {};
binding.source = bindingData[index++];
binding.destFunc = bindingData[index++];
binding.destination = bindingData[index++];
bindings.push(binding);
}
var watchers:Object = decodeWatcher(bindingData.slice(index));
for (i = 0; i < n; i++)
{
binding = bindings[i];
if (binding.source is Array)
{
if (binding.source[0] in _strand)
{
if (binding.source.length == 2 && binding.destination.length == 2)
{
// simple component.property binding
var destObject:Object;
var destination:IStrand;
// can be simplebinding or constantbinding
var compWatcher:Object = watchers.watcherMap[binding.source[0]];
fieldWatcher = compWatcher.children.watcherMap[binding.source[1]];
if (fieldWatcher.eventNames is String)
{
sb = new SimpleBinding();
sb.destinationPropertyName = binding.destination[1];
sb.eventName = fieldWatcher.eventNames as String;
sb.sourceID = binding.source[0];
sb.sourcePropertyName = binding.source[1];
sb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(sb);
else
{
if (destObject)
{
sb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
else if (fieldWatcher.eventNames == null)
{
cb = new ConstantBinding();
cb.destinationPropertyName = binding.destination[1];
cb.sourceID = binding.source[0];
cb.sourcePropertyName = binding.source[1];
cb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(cb);
else
{
if (destObject)
{
cb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
}
}
}
else if (binding.source is String && binding.destination is Array)
{
fieldWatcher = watchers.watcherMap[binding.source];
if (fieldWatcher == null)
{
cb = new ConstantBinding();
cb.destinationPropertyName = binding.destination[1];
cb.sourcePropertyName = binding.source;
cb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(cb);
else
{
if (destObject)
{
cb.destination = destObject;
_strand.addBead(cb);
}
else
{
deferredBindings[binding.destination[0]] = cb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
else if (fieldWatcher.eventNames is String)
{
sb = new SimpleBinding();
sb.destinationPropertyName = binding.destination[1];
sb.eventName = fieldWatcher.eventNames as String;
sb.sourcePropertyName = binding.source;
sb.setDocument(_strand);
destObject = getProperty(_strand, binding.destination[0]);
destination = destObject as IStrand;
if (destination)
destination.addBead(sb);
else
{
if (destObject)
{
sb.destination = destObject;
_strand.addBead(sb);
}
else
{
deferredBindings[binding.destination[0]] = sb;
IEventDispatcher(_strand).addEventListener("valueChange", deferredBindingsHandler);
}
}
}
}
else
{
makeGenericBinding(binding, i, watchers);
}
}
}
private function makeGenericBinding(binding:Object, index:int, watchers:Object):void
{
var gb:GenericBinding = new GenericBinding();
gb.setDocument(_strand);
gb.destinationData = binding.destination;
gb.destinationFunction = binding.destFunc;
gb.source = binding.source;
if (watchers.watchers.length)
setupWatchers(gb, index, watchers.watchers, null);
else
{
// should be a constant expression.
// the value doesn't matter as GenericBinding
// should get the value from the source
gb.valueChanged(null);
}
}
private function setupWatchers(gb:GenericBinding, index:int, watchers:Array, parentWatcher:WatcherBase):void
{
var n:int = watchers.length;
for (var i:int = 0; i < n; i++)
{
var watcher:Object = watchers[i];
var isValidWatcher:Boolean = false;
if (typeof(watcher.bindings) == "number")
isValidWatcher = (watcher.bindings == index);
else
isValidWatcher = (watcher.bindings.indexOf(index) != -1);
if (isValidWatcher)
{
var type:String = watcher.type;
switch (type)
{
case "property":
{
var pw:PropertyWatcher = new PropertyWatcher(this,
watcher.propertyName,
watcher.eventNames,
watcher.getterFunction);
watcher.watcher = pw;
if (parentWatcher)
pw.parentChanged(parentWatcher.value);
else
pw.parentChanged(_strand);
if (parentWatcher)
parentWatcher.addChild(pw);
if (watcher.children == null)
pw.addBinding(gb);
break;
}
}
if (watcher.children)
{
setupWatchers(gb, index, watcher.children.watchers, watcher.watcher);
}
}
}
}
private function decodeWatcher(bindingData:Array):Object
{
var watcherMap:Object = {};
var watchers:Array = [];
var n:int = bindingData.length;
var index:int = 0;
var watcherData:Object;
// FalconJX adds an extra null to the data so make sure
// we have enough data for a complete watcher otherwise
// say we are done
while (index < n - 2)
{
var watcherIndex:int = bindingData[index++];
var type:int = bindingData[index++];
switch (type)
{
case 0:
{
watcherData = { type: "function" };
watcherData.functionName = bindingData[index++];
watcherData.paramFunction = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
break;
}
case 1:
{
watcherData = { type: "static" };
watcherData.propertyName = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherData.getterFunction = bindingData[index++];
watcherData.parentObj = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
case 2:
{
watcherData = { type: "property" };
watcherData.propertyName = bindingData[index++];
watcherData.eventNames = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherData.getterFunction = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
case 3:
{
watcherData = { type: "xml" };
watcherData.propertyName = bindingData[index++];
watcherData.bindings = bindingData[index++];
watcherMap[watcherData.propertyName] = watcherData;
break;
}
}
watcherData.children = bindingData[index++];
if (watcherData.children != null)
{
watcherData.children = decodeWatcher(watcherData.children);
}
watcherData.index = watcherIndex;
watchers.push(watcherData);
}
return { watchers: watchers, watcherMap: watcherMap };
}
private var deferredBindings:Object = {};
private function deferredBindingsHandler(event:Event):void
{
for (var p:String in deferredBindings)
{
if (_strand[p] != null)
{
var destination:IStrand = _strand[p] as IStrand;
destination.addBead(deferredBindings[p]);
delete deferredBindings[p];
}
}
}
}
}
|
handle generic constant binding
|
handle generic constant binding
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
bfe012bd7e492e95062c6086bd23e1b5093a4233
|
src/avm1lib/AS2Globals.as
|
src/avm1lib/AS2Globals.as
|
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
* Copyright 2013 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package avm1lib {
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.external.ExternalInterface;
import flash.geom.ColorTransform;
import flash.geom.Rectangle;
import flash.media.Sound;
import flash.media.SoundMixer;
import flash.net.SharedObject;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import flash.system.Capabilities;
import flash.system.fscommand;
import flash.text.TextFormat;
import flash.ui.ContextMenu;
import flash.ui.ContextMenuItem;
import flash.utils.clearInterval;
import flash.utils.clearTimeout;
import flash.utils.getTimer;
[native(cls="AS2Globals")]
public dynamic class AS2Globals {
// TODO: change this when entering a domain.
public static var instance;
public var _global;
public var flash:Object;
public function AS2Globals() {
AS2Globals.instance = this;
this._global = this;
this.flash = createFlashObject();
}
private function createFlashObject():Object {
return {
_MovieClip: AS2MovieClip,
display: {},
external: {
ExternalInterface: ExternalInterface
},
filters: {},
geom: {},
text: {}
};
}
public function $asfunction(link) {
notImplemented('AS2Globals.$asfunction');
}
public native function ASSetPropFlags(obj, children, flags, allowFalse);
public function call(frame) {
var nativeTarget = AS2Utils.resolveTarget();
nativeTarget._callFrame(frame);
}
public function chr(number) {
return String.fromCharCode(number);
}
public var clearInterval:Function = clearInterval;
public var clearTimeout:Function = clearTimeout;
public function duplicateMovieClip(target, newname, depth) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget.duplicateMovieClip(newname, depth);
}
public var fscommand:Function = fscommand;
public native function escape(str: String): String;
public native function unescape(str: String): String;
public function getAS2Property(target, index) {
var nativeTarget = AS2Utils.resolveTarget(target);
return nativeTarget[PropertiesIndexMap[index]];
}
public var getTimer:Function = getTimer;
public function getURL(url, target, method) {
var request = new URLRequest(url);
if (method) {
request.method = method;
}
if (typeof target === 'string' && target.indexOf('_level') === 0) {
loadMovieNum(url, +target.substr(6), method);
return;
}
navigateToURL(request, target);
}
public function getVersion() {
return Capabilities.version;
}
private native function _addToPendingScripts(subject:Object, fn:Function, args:Array = null);
public function gotoAndPlay(scene, frame) {
var nativeTarget = AS2Utils.resolveTarget();
if (arguments.length < 2) {
_addToPendingScripts(nativeTarget, nativeTarget.gotoAndPlay, [arguments[0]]);
} else {
_addToPendingScripts(nativeTarget, nativeTarget.gotoAndPlay, [arguments[1], arguments[0]]); // scene and frame are swapped for AS3
}
}
public function gotoAndStop(scene, frame) {
var nativeTarget = AS2Utils.resolveTarget();
if (arguments.length < 2) {
_addToPendingScripts(nativeTarget, nativeTarget.gotoAndStop, [arguments[0]]);
} else {
_addToPendingScripts(nativeTarget, nativeTarget.gotoAndStop, [arguments[1], arguments[0]]); // scene and frame are swapped for AS3
}
}
public function gotoLabel(label) {
var nativeTarget = AS2Utils.resolveTarget();
_addToPendingScripts(nativeTarget, function (subject, label) {
subject._gotoLabel(label);
}, [nativeTarget, label]);
}
public function ifFrameLoaded(scene, frame) {
// ignoring scene parameter ?
var nativeTarget = AS2Utils.resolveTarget();
var frameNum = arguments.length < 2 ? arguments[0] : arguments[1];
var framesLoaded = nativeTarget._framesloaded;
return frameNum < framesLoaded;
}
public function int(value: *): * {
return value | 0;
}
public function length(expression: Object): Number {
return ('' + expression).length; // ASCII Only?
}
public function loadMovie(url: String, target: Object, method: String): void {
// some swfs are using loadMovie to call fscommmand
if (url && url.toLowerCase().indexOf('fscommand:') === 0) {
this.fscommand(url.substring('fscommand:'.length), target);
return;
}
var levelStr: String;
var loadLevel: Boolean = typeof target === 'string' && target.indexOf('_level') === 0 &&
int(levelStr = target.charAt(6)) == levelStr;
var loader:Loader = new Loader();
if (loadLevel) {
_setLevel(int(levelStr), loader);
var request: URLRequest = new URLRequest(url);
if (method) {
request.method = method;
}
loader.load(request);
} else {
var nativeTarget: flash.display.MovieClip = AS2Utils.resolveTarget(target);
nativeTarget.loadMovie(url, method);
}
}
private native function _setLevel(level:uint, loader:Loader);
public function loadMovieNum(url, level, method) {
// some swfs are using loadMovieNum to call fscommmand
if (url && url.toLowerCase().indexOf('fscommand:') === 0) {
return this.fscommand(url.substring('fscommand:'.length));
}
var loader:Loader = new Loader();
_setLevel(level, loader);
var request = new URLRequest(url);
if (method) {
request.method = method;
}
loader.load(request);
}
public function loadVariables(url: String, target: Object, method: String = ''): void {
var nativeTarget = AS2Utils.resolveTarget(target);
var request = new URLRequest(url);
if (method) {
request.method = method;
}
var loader: URLLoader = new URLLoader(request);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
function completeHandler(event: Event): void {
loader.removeEventListener(Event.COMPLETE, completeHandler);
for (var key: String in loader.data) {
nativeTarget[key] = loader.data[key];
}
}
loader.addEventListener(Event.COMPLETE, completeHandler);
}
public function mbchr(number) {
return String.fromCharCode(number);
}
public function mblength(expression) {
return ('' + expression).length;
}
public function mbord(character) {
return ('' + character).charCodeAt(0);
}
public function mbsubstring(value, index, count) {
if (index !== (0 | index) || count !== (0 | count)) {
// index or count are not integers, the result is the empty string.
return '';
}
return ('' + value).substr(index, count);
}
public function nextFrame() {
var nativeTarget = AS2Utils.resolveTarget();
_addToPendingScripts(nativeTarget, nativeTarget.nextFrame);
}
public function nextScene() {
var nativeTarget = AS2Utils.resolveTarget();
_addToPendingScripts(nativeTarget, nativeTarget.nextScene);
}
public function ord(character) {
return ('' + character).charCodeAt(0); // ASCII only?
}
public function play() {
var nativeTarget = AS2Utils.resolveTarget();
nativeTarget.play();
}
public function prevFrame() {
var nativeTarget = AS2Utils.resolveTarget();
_addToPendingScripts(nativeTarget, nativeTarget.prevFrame);
}
public function prevScene() {
var nativeTarget = AS2Utils.resolveTarget();
_addToPendingScripts(nativeTarget, nativeTarget.prevScene);
}
public function print(target, boundingBox) {
// flash.printing.PrintJob
notImplemented('AS2Globals.print');
}
public function printAsBitmap(target, boundingBox) {
notImplemented('AS2Globals.printAsBitmap');
}
public function printAsBitmapNum(level, boundingBox) {
notImplemented('AS2Globals.printAsBitmapNum');
}
public function printNum(level, bondingBox) {
notImplemented('AS2Globals.printNum');
}
public function random(value) {
return 0 | (Math.random() * (0 | value));
}
public function removeMovieClip(target) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget.removeMovieClip();
}
public function setInterval(): * {
// AVM1 setInterval silently swallows everything that vaguely looks like an error.
if (arguments.length < 2) {
return undefined;
}
var args: Array = [];
if (typeof arguments[0] === 'function') {
args = arguments;
} else {
if (arguments.length < 3) {
return undefined;
}
var obj: Object = arguments[0];
var funName: * = arguments[1];
if (!(obj && typeof obj === 'object' && typeof funName === 'string')) {
return undefined;
}
args[0] = function (): void {
obj[funName].apply(obj, arguments);
};
for (var i: uint = 2; i < arguments.length; i++) {
args.push(arguments[i]);
}
}
// Unconditionally coerce interval to int, as one would do.
args[1] |= 0;
return flash.utils.setInterval.apply(null, args);
}
public function setAS2Property(target, index, value) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget[PropertiesIndexMap[index]] = value;
}
public function setTimeout() {
// AVM1 setTimeout silently swallows most things that vaguely look like errors.
if (arguments.length < 2 || typeof arguments[0] !== 'function')
{
return undefined;
}
// Unconditionally coerce interval to int, as one would do.
arguments[1] |= 0;
return flash.utils.setTimeout.apply(null, arguments);
}
public function showRedrawRegions(enable, color) {
// flash.profiler.showRedrawRegions.apply(null, arguments);
notImplemented('AS2Globals.showRedrawRegions');
}
public function startDrag(target, lock, left, top, right, bottom) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget.startDrag(lock, arguments.length < 3 ? null :
new flash.geom.Rectangle(left, top, right - left, bottom - top));
}
public function stop() {
var nativeTarget = AS2Utils.resolveTarget();
nativeTarget.stop();
}
public function stopAllSounds() {
SoundMixer.stopAll();
}
public function stopDrag(target) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget.stopDrag();
}
public function substring(value, index, count) {
return mbsubstring(value, index, count); // ASCII Only?
}
public function targetPath(target) {
var nativeTarget = AS2Utils.resolveTarget(target);
return nativeTarget._target;
}
public function toggleHighQuality() {
// flash.display.Stage.quality
notImplemented('AS2Globals.toggleHighQuality');
}
public native function trace(expression);
public function unloadMovie(target) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget.unloadMovie();
}
public function unloadMovieNum(level) {
var nativeTarget = AS2Utils.resolveLevel(level);
nativeTarget.unloadMovie();
}
public function updateAfterEvent() {
// flash.events.TimerEvent.updateAfterEvent
notImplemented('AS2Globals.updateAfterEvent');
}
// built-ins
public var NaN:Number = NaN;
public var Infinity:Number = Number.POSITIVE_INFINITY;
public var isFinite:Function = isFinite;
public var isNaN:Function = isNaN;
public var parseFloat:Function = parseFloat;
public var parseInt:Function = parseInt;
public var undefined:* = undefined;
public var MovieClip:Class = AS2MovieClip;
public var AsBroadcaster:Class = AS2Broadcaster;
public var System:Class = AS2System;
public var Stage:Class = AS2Stage;
public var Button:Class = AS2Button;
public var TextField:Class = AS2TextField;
public var Color:Class = AS2Color;
public var Key:Class = AS2Key;
public var Mouse:Class = AS2Mouse;
public var MovieClipLoader:Class = AS2MovieClipLoader;
public var Sound:Class = AS2Sound;
public var SharedObject:Class = SharedObject;
public var ContextMenu:Class = ContextMenu;
public var ContextMenuItem:Class = ContextMenuItem;
public var ColorTransform:Class = ColorTransform;
public var Point:Class = flash.geom.Point;
public var Rectangle:Class = Rectangle;
public var TextFormat:Class = TextFormat;
private static native function _addInternalClasses(proto:Object):void;
{
// Initializing all global objects/classes
var classes = [Object, Function, Array, Number, Math, Boolean, Date, RegExp, String];
_addInternalClasses(prototype);
}
}
}
var PropertiesIndexMap:Array = [
'_x', '_y', '_xscale', '_yscale', '_currentframe', '_totalframes', '_alpha',
'_visible', '_width', '_height', '_rotation', '_target', '_framesloaded',
'_name', '_droptarget', '_url', '_highquality', '_focusrect',
'_soundbuftime', '_quality', '_xmouse', '_ymouse'
];
|
/* -*- Mode: js; js-indent-level: 2; indent-tabs-mode: nil; tab-width: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/*
* Copyright 2013 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package avm1lib {
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.external.ExternalInterface;
import flash.geom.ColorTransform;
import flash.geom.Rectangle;
import flash.media.Sound;
import flash.media.SoundMixer;
import flash.net.SharedObject;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.navigateToURL;
import flash.system.Capabilities;
import flash.system.fscommand;
import flash.text.TextFormat;
import flash.ui.ContextMenu;
import flash.ui.ContextMenuItem;
import flash.utils.clearInterval;
import flash.utils.clearTimeout;
import flash.utils.getTimer;
[native(cls="AS2Globals")]
public dynamic class AS2Globals {
// TODO: change this when entering a domain.
public static var instance;
public var _global;
public var flash:Object;
public function AS2Globals() {
AS2Globals.instance = this;
this._global = this;
this.flash = createFlashObject();
}
private function createFlashObject():Object {
return {
_MovieClip: AS2MovieClip,
display: {},
external: {
ExternalInterface: ExternalInterface
},
filters: {},
geom: {},
text: {}
};
}
public function $asfunction(link) {
notImplemented('AS2Globals.$asfunction');
}
public native function ASSetPropFlags(obj, children, flags, allowFalse);
public function call(frame) {
var nativeTarget = AS2Utils.resolveTarget();
nativeTarget._callFrame(frame);
}
public function chr(number) {
return String.fromCharCode(number);
}
public var clearInterval:Function = flash.utils.clearInterval;
public var clearTimeout:Function = flash.utils.clearTimeout;
public function duplicateMovieClip(target, newname, depth) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget.duplicateMovieClip(newname, depth);
}
public var fscommand:Function = flash.system.fscommand;
public native function escape(str: String): String;
public native function unescape(str: String): String;
public function getAS2Property(target, index) {
var nativeTarget = AS2Utils.resolveTarget(target);
return nativeTarget[PropertiesIndexMap[index]];
}
public var getTimer:Function = flash.utils.getTimer;
public function getURL(url, target, method) {
var request = new URLRequest(url);
if (method) {
request.method = method;
}
if (typeof target === 'string' && target.indexOf('_level') === 0) {
loadMovieNum(url, +target.substr(6), method);
return;
}
navigateToURL(request, target);
}
public function getVersion() {
return Capabilities.version;
}
private native function _addToPendingScripts(subject:Object, fn:Function, args:Array = null);
public function gotoAndPlay(scene, frame) {
var nativeTarget = AS2Utils.resolveTarget();
if (arguments.length < 2) {
_addToPendingScripts(nativeTarget, nativeTarget.gotoAndPlay, [arguments[0]]);
} else {
_addToPendingScripts(nativeTarget, nativeTarget.gotoAndPlay, [arguments[1], arguments[0]]); // scene and frame are swapped for AS3
}
}
public function gotoAndStop(scene, frame) {
var nativeTarget = AS2Utils.resolveTarget();
if (arguments.length < 2) {
_addToPendingScripts(nativeTarget, nativeTarget.gotoAndStop, [arguments[0]]);
} else {
_addToPendingScripts(nativeTarget, nativeTarget.gotoAndStop, [arguments[1], arguments[0]]); // scene and frame are swapped for AS3
}
}
public function gotoLabel(label) {
var nativeTarget = AS2Utils.resolveTarget();
_addToPendingScripts(nativeTarget, function (subject, label) {
subject._gotoLabel(label);
}, [nativeTarget, label]);
}
public function ifFrameLoaded(scene, frame) {
// ignoring scene parameter ?
var nativeTarget = AS2Utils.resolveTarget();
var frameNum = arguments.length < 2 ? arguments[0] : arguments[1];
var framesLoaded = nativeTarget._framesloaded;
return frameNum < framesLoaded;
}
public function int(value: *): * {
return value | 0;
}
public function length(expression: Object): Number {
return ('' + expression).length; // ASCII Only?
}
public function loadMovie(url: String, target: Object, method: String): void {
// some swfs are using loadMovie to call fscommmand
if (url && url.toLowerCase().indexOf('fscommand:') === 0) {
this.fscommand(url.substring('fscommand:'.length), target);
return;
}
var levelStr: String;
var loadLevel: Boolean = typeof target === 'string' && target.indexOf('_level') === 0 &&
int(levelStr = target.charAt(6)) == levelStr;
var loader:Loader = new Loader();
if (loadLevel) {
_setLevel(int(levelStr), loader);
var request: URLRequest = new URLRequest(url);
if (method) {
request.method = method;
}
loader.load(request);
} else {
var nativeTarget: flash.display.MovieClip = AS2Utils.resolveTarget(target);
nativeTarget.loadMovie(url, method);
}
}
private native function _setLevel(level:uint, loader:Loader);
public function loadMovieNum(url, level, method) {
// some swfs are using loadMovieNum to call fscommmand
if (url && url.toLowerCase().indexOf('fscommand:') === 0) {
return this.fscommand(url.substring('fscommand:'.length));
}
var loader:Loader = new Loader();
_setLevel(level, loader);
var request = new URLRequest(url);
if (method) {
request.method = method;
}
loader.load(request);
}
public function loadVariables(url: String, target: Object, method: String = ''): void {
var nativeTarget = AS2Utils.resolveTarget(target);
var request = new URLRequest(url);
if (method) {
request.method = method;
}
var loader: URLLoader = new URLLoader(request);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
function completeHandler(event: Event): void {
loader.removeEventListener(Event.COMPLETE, completeHandler);
for (var key: String in loader.data) {
nativeTarget[key] = loader.data[key];
}
}
loader.addEventListener(Event.COMPLETE, completeHandler);
}
public function mbchr(number) {
return String.fromCharCode(number);
}
public function mblength(expression) {
return ('' + expression).length;
}
public function mbord(character) {
return ('' + character).charCodeAt(0);
}
public function mbsubstring(value, index, count) {
if (index !== (0 | index) || count !== (0 | count)) {
// index or count are not integers, the result is the empty string.
return '';
}
return ('' + value).substr(index, count);
}
public function nextFrame() {
var nativeTarget = AS2Utils.resolveTarget();
_addToPendingScripts(nativeTarget, nativeTarget.nextFrame);
}
public function nextScene() {
var nativeTarget = AS2Utils.resolveTarget();
_addToPendingScripts(nativeTarget, nativeTarget.nextScene);
}
public function ord(character) {
return ('' + character).charCodeAt(0); // ASCII only?
}
public function play() {
var nativeTarget = AS2Utils.resolveTarget();
nativeTarget.play();
}
public function prevFrame() {
var nativeTarget = AS2Utils.resolveTarget();
_addToPendingScripts(nativeTarget, nativeTarget.prevFrame);
}
public function prevScene() {
var nativeTarget = AS2Utils.resolveTarget();
_addToPendingScripts(nativeTarget, nativeTarget.prevScene);
}
public function print(target, boundingBox) {
// flash.printing.PrintJob
notImplemented('AS2Globals.print');
}
public function printAsBitmap(target, boundingBox) {
notImplemented('AS2Globals.printAsBitmap');
}
public function printAsBitmapNum(level, boundingBox) {
notImplemented('AS2Globals.printAsBitmapNum');
}
public function printNum(level, bondingBox) {
notImplemented('AS2Globals.printNum');
}
public function random(value) {
return 0 | (Math.random() * (0 | value));
}
public function removeMovieClip(target) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget.removeMovieClip();
}
public function setInterval(): * {
// AVM1 setInterval silently swallows everything that vaguely looks like an error.
if (arguments.length < 2) {
return undefined;
}
var args: Array = [];
if (typeof arguments[0] === 'function') {
args = arguments;
} else {
if (arguments.length < 3) {
return undefined;
}
var obj: Object = arguments[0];
var funName: * = arguments[1];
if (!(obj && typeof obj === 'object' && typeof funName === 'string')) {
return undefined;
}
args[0] = function (): void {
obj[funName].apply(obj, arguments);
};
for (var i: uint = 2; i < arguments.length; i++) {
args.push(arguments[i]);
}
}
// Unconditionally coerce interval to int, as one would do.
args[1] |= 0;
return flash.utils.setInterval.apply(null, args);
}
public function setAS2Property(target, index, value) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget[PropertiesIndexMap[index]] = value;
}
public function setTimeout() {
// AVM1 setTimeout silently swallows most things that vaguely look like errors.
if (arguments.length < 2 || typeof arguments[0] !== 'function')
{
return undefined;
}
// Unconditionally coerce interval to int, as one would do.
arguments[1] |= 0;
return flash.utils.setTimeout.apply(null, arguments);
}
public function showRedrawRegions(enable, color) {
// flash.profiler.showRedrawRegions.apply(null, arguments);
notImplemented('AS2Globals.showRedrawRegions');
}
public function startDrag(target, lock, left, top, right, bottom) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget.startDrag(lock, arguments.length < 3 ? null :
new flash.geom.Rectangle(left, top, right - left, bottom - top));
}
public function stop() {
var nativeTarget = AS2Utils.resolveTarget();
nativeTarget.stop();
}
public function stopAllSounds() {
SoundMixer.stopAll();
}
public function stopDrag(target) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget.stopDrag();
}
public function substring(value, index, count) {
return mbsubstring(value, index, count); // ASCII Only?
}
public function targetPath(target) {
var nativeTarget = AS2Utils.resolveTarget(target);
return nativeTarget._target;
}
public function toggleHighQuality() {
// flash.display.Stage.quality
notImplemented('AS2Globals.toggleHighQuality');
}
public native function trace(expression);
public function unloadMovie(target) {
var nativeTarget = AS2Utils.resolveTarget(target);
nativeTarget.unloadMovie();
}
public function unloadMovieNum(level) {
var nativeTarget = AS2Utils.resolveLevel(level);
nativeTarget.unloadMovie();
}
public function updateAfterEvent() {
// flash.events.TimerEvent.updateAfterEvent
notImplemented('AS2Globals.updateAfterEvent');
}
// built-ins
public var NaN:Number = Number.NaN;
public var Infinity:Number = Number.POSITIVE_INFINITY;
[native("isFinite")]
public native function isFinite(n:Number = void 0):Boolean;
[native("isNaN")]
public native function isNaN(n:Number = void 0):Boolean;
[native("parseFloat")]
public native function parseFloat(str:String = "NaN"):Number;
[native("parseInt")]
public native function parseInt(s:String = "NaN", radix = 0):Number;
public var undefined:* = undefined;
public var MovieClip:Class = AS2MovieClip;
public var AsBroadcaster:Class = AS2Broadcaster;
public var System:Class = AS2System;
public var Stage:Class = AS2Stage;
public var Button:Class = AS2Button;
public var TextField:Class = AS2TextField;
public var Color:Class = AS2Color;
public var Key:Class = AS2Key;
public var Mouse:Class = AS2Mouse;
public var MovieClipLoader:Class = AS2MovieClipLoader;
public var Sound:Class = AS2Sound;
public var SharedObject:Class = SharedObject;
public var ContextMenu:Class = ContextMenu;
public var ContextMenuItem:Class = ContextMenuItem;
public var ColorTransform:Class = ColorTransform;
public var Point:Class = flash.geom.Point;
public var Rectangle:Class = Rectangle;
public var TextFormat:Class = TextFormat;
private static native function _addInternalClasses(proto:Object):void;
{
// Initializing all global objects/classes
var classes = [Object, Function, Array, Number, Math, Boolean, Date, RegExp, String];
_addInternalClasses(prototype);
}
}
}
var PropertiesIndexMap:Array = [
'_x', '_y', '_xscale', '_yscale', '_currentframe', '_totalframes', '_alpha',
'_visible', '_width', '_height', '_rotation', '_target', '_framesloaded',
'_name', '_droptarget', '_url', '_highquality', '_focusrect',
'_soundbuftime', '_quality', '_xmouse', '_ymouse'
];
|
Fix self references to variable definitions in AS3 code.
|
Fix self references to variable definitions in AS3 code.
|
ActionScript
|
apache-2.0
|
tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,mbebenita/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,yurydelendik/shumway,mozilla/shumway,mbebenita/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,mozilla/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway
|
1bff70d6e71b898504e9d76cc28a296b87a2afc2
|
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 flash.display.Stage;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.URLLoader;
import flash.net.URLStream;
import org.mangui.hls.controller.AudioTrackController;
import org.mangui.hls.controller.LevelController;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.loader.AltAudioLevelLoader;
import org.mangui.hls.loader.LevelLoader;
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.model.Level;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.stream.HLSNetStream;
import org.mangui.hls.stream.StreamBuffer;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that manages the streaming process. **/
public class HLS extends EventDispatcher {
private var _levelLoader : LevelLoader;
private var _altAudioLevelLoader : AltAudioLevelLoader;
private var _audioTrackController : AudioTrackController;
private var _levelController : LevelController;
private var _streamBuffer : StreamBuffer;
/** HLS NetStream **/
private var _hlsNetStream : HLSNetStream;
/** HLS URLStream/URLLoader **/
private var _hlsURLStream : Class;
private var _hlsURLLoader : Class;
private var _client : Object = {};
private var _stage : Stage;
/* level handling */
private var _level : int;
/* overrided quality_manual_level level */
private var _manual_level : int = -1;
/** Create and connect all components. **/
public function HLS() {
var connection : NetConnection = new NetConnection();
connection.connect(null);
_levelLoader = new LevelLoader(this);
_altAudioLevelLoader = new AltAudioLevelLoader(this);
_audioTrackController = new AudioTrackController(this);
_levelController = new LevelController(this);
_streamBuffer = new StreamBuffer(this, _audioTrackController, _levelController);
_hlsURLStream = URLStream as Class;
_hlsURLLoader = URLLoader as Class;
// default loader
_hlsNetStream = new HLSNetStream(connection, this, _streamBuffer);
this.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
};
/** 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);
};
private function _levelSwitchHandler(event : HLSEvent) : void {
_level = event.level;
};
public function dispose() : void {
this.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
_levelLoader.dispose();
_altAudioLevelLoader.dispose();
_audioTrackController.dispose();
_levelController.dispose();
_hlsNetStream.dispose_();
_streamBuffer.dispose();
_levelLoader = null;
_altAudioLevelLoader = null;
_audioTrackController = null;
_levelController = null;
_hlsNetStream = null;
_client = null;
_stage = null;
_hlsNetStream = null;
}
/** Return index of first quality level referenced in Manifest **/
public function get firstlevel() : int {
return _levelController.firstlevel;
};
/** Return the quality level used when starting a fresh playback **/
public function get startlevel() : int {
return _levelController.startlevel;
};
/** Return the quality level used after a seek operation **/
public function get seeklevel() : int {
return _levelController.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 _level;
};
/* set quality level for next loaded fragment (-1 for automatic level selection) */
public function set level(level : int) : void {
_manual_level = level;
};
/* check if we are in automatic level selection mode */
public function get autolevel() : Boolean {
return (_manual_level == -1);
};
/* return manual level */
public function get manuallevel() : int {
return _manual_level;
};
/** Return a Vector of quality level **/
public function get levels() : Vector.<Level> {
return _levelLoader.levels;
};
/** Return the current playback position. **/
public function get position() : Number {
return _streamBuffer.position;
};
/** 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 _levelLoader.type;
};
/** Load and parse a new HLS URL **/
public function load(url : String) : void {
_level = 0;
_hlsNetStream.close();
_levelLoader.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 current back buffer Length **/
public function get backBufferLength() : Number {
return _hlsNetStream.backBufferLength;
};
/** 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 _levelLoader.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;
}
/* set URL stream loader */
public function set URLloader(urlloader : Class) : void {
_hlsURLLoader = urlloader;
}
/* retrieve URL stream loader */
public function get URLloader() : Class {
return _hlsURLLoader;
}
}
}
|
/* 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 flash.display.Stage;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.URLLoader;
import flash.net.URLStream;
import org.mangui.hls.controller.AudioTrackController;
import org.mangui.hls.controller.LevelController;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.loader.AltAudioLevelLoader;
import org.mangui.hls.loader.LevelLoader;
import org.mangui.hls.model.AudioTrack;
import org.mangui.hls.model.Level;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.stream.HLSNetStream;
import org.mangui.hls.stream.StreamBuffer;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that manages the streaming process. **/
public class HLS extends EventDispatcher {
private var _levelLoader : LevelLoader;
private var _altAudioLevelLoader : AltAudioLevelLoader;
private var _audioTrackController : AudioTrackController;
private var _levelController : LevelController;
private var _streamBuffer : StreamBuffer;
/** HLS NetStream **/
private var _hlsNetStream : HLSNetStream;
/** HLS URLStream/URLLoader **/
private var _hlsURLStream : Class;
private var _hlsURLLoader : Class;
private var _client : Object = {};
private var _stage : Stage;
/* level handling */
private var _level : int;
/* overrided quality_manual_level level */
private var _manual_level : int = -1;
/** Create and connect all components. **/
public function HLS() {
_levelLoader = new LevelLoader(this);
_altAudioLevelLoader = new AltAudioLevelLoader(this);
_audioTrackController = new AudioTrackController(this);
_levelController = new LevelController(this);
_streamBuffer = new StreamBuffer(this, _audioTrackController, _levelController);
_hlsURLStream = URLStream as Class;
_hlsURLLoader = URLLoader as Class;
// default loader
var connection : NetConnection = new NetConnection();
connection.connect(null);
_hlsNetStream = new HLSNetStream(connection, this, _streamBuffer);
this.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
};
/** 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);
};
private function _levelSwitchHandler(event : HLSEvent) : void {
_level = event.level;
};
public function dispose() : void {
this.removeEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
_levelLoader.dispose();
_altAudioLevelLoader.dispose();
_audioTrackController.dispose();
_levelController.dispose();
_hlsNetStream.dispose_();
_streamBuffer.dispose();
_levelLoader = null;
_altAudioLevelLoader = null;
_audioTrackController = null;
_levelController = null;
_hlsNetStream = null;
_client = null;
_stage = null;
_hlsNetStream = null;
}
/** Return index of first quality level referenced in Manifest **/
public function get firstlevel() : int {
return _levelController.firstlevel;
};
/** Return the quality level used when starting a fresh playback **/
public function get startlevel() : int {
return _levelController.startlevel;
};
/** Return the quality level used after a seek operation **/
public function get seeklevel() : int {
return _levelController.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 _level;
};
/* set quality level for next loaded fragment (-1 for automatic level selection) */
public function set level(level : int) : void {
_manual_level = level;
};
/* check if we are in automatic level selection mode */
public function get autolevel() : Boolean {
return (_manual_level == -1);
};
/* return manual level */
public function get manuallevel() : int {
return _manual_level;
};
/** Return a Vector of quality level **/
public function get levels() : Vector.<Level> {
return _levelLoader.levels;
};
/** Return the current playback position. **/
public function get position() : Number {
return _streamBuffer.position;
};
/** 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 _levelLoader.type;
};
/** Load and parse a new HLS URL **/
public function load(url : String) : void {
_level = 0;
_hlsNetStream.close();
_levelLoader.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 current back buffer Length **/
public function get backBufferLength() : Number {
return _hlsNetStream.backBufferLength;
};
/** 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 _levelLoader.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;
}
/* set URL stream loader */
public function set URLloader(urlloader : Class) : void {
_hlsURLLoader = urlloader;
}
/* retrieve URL stream loader */
public function get URLloader() : Class {
return _hlsURLLoader;
}
}
}
|
reorder code for sake of clarity
|
reorder code for sake of clarity
|
ActionScript
|
mpl-2.0
|
neilrackett/flashls,Peer5/flashls,Peer5/flashls,Corey600/flashls,tedconf/flashls,hola/flashls,suuhas/flashls,suuhas/flashls,dighan/flashls,Boxie5/flashls,loungelogic/flashls,fixedmachine/flashls,neilrackett/flashls,suuhas/flashls,Peer5/flashls,Peer5/flashls,thdtjsdn/flashls,dighan/flashls,suuhas/flashls,aevange/flashls,NicolasSiver/flashls,fixedmachine/flashls,aevange/flashls,codex-corp/flashls,JulianPena/flashls,Boxie5/flashls,loungelogic/flashls,tedconf/flashls,aevange/flashls,Corey600/flashls,thdtjsdn/flashls,mangui/flashls,aevange/flashls,clappr/flashls,hola/flashls,jlacivita/flashls,jlacivita/flashls,mangui/flashls,vidible/vdb-flashls,codex-corp/flashls,JulianPena/flashls,vidible/vdb-flashls,NicolasSiver/flashls,clappr/flashls
|
f65a3569b8ff348e4a31bd82b9df53a8c43bbae1
|
src/aerys/minko/render/shader/compiler/allocation/ContiguousAllocation.as
|
src/aerys/minko/render/shader/compiler/allocation/ContiguousAllocation.as
|
package aerys.minko.render.shader.compiler.allocation
{
import aerys.minko.render.shader.compiler.register.Components;
/**
* @private
* @author Romain Gilliotte
*
*/
public class ContiguousAllocation implements IAllocation
{
private var _subAllocations : Vector.<SimpleAllocation>;
private var _offsets : Vector.<uint>;
public function get type() : uint
{
return _subAllocations[0].type;
}
public function get registerId() : uint
{
return _subAllocations[0].registerId;
}
public function get registerOffset() : uint
{
return offset % 4;
}
// public function get writeMask() : uint
// {
//
// }
public function get aligned() : Boolean
{
return false;
}
public function get offset() : uint
{
return _subAllocations[0].offset - _offsets[0];
}
public function get maxSize() : uint
{
var numArgs : uint = _subAllocations.length;
var maxSize : uint = 0;
for (var argId : uint = 0; argId < numArgs; ++argId)
{
var currentSize : uint = _offsets[argId] + _subAllocations[argId].maxSize;
if (currentSize > maxSize)
maxSize = currentSize;
}
return maxSize;
}
public function get subAllocations() : Vector.<SimpleAllocation>
{
return _subAllocations;
}
public function set offset(v : uint) : void
{
var numArgs : uint = _subAllocations.length;
for (var argId : uint = 0; argId < numArgs; ++argId)
_subAllocations[argId].offset = v + _offsets[argId];
}
public function ContiguousAllocation(subAllocations : Vector.<SimpleAllocation>,
offsets : Vector.<uint>)
{
_subAllocations = subAllocations;
_offsets = offsets;
}
public function getReadSwizzle(readingOpWriteOffset : uint,
readingOpComponents : uint) : uint
{
var components : uint;
components = readingOpComponents;
components = Components.applyWriteOffset(components, readingOpWriteOffset);
components = Components.applyReadOffset(components, registerOffset);
if (components == Components.stringToComponent('____'))
throw new Error();
return Components.generateReadSwizzle(components);
}
public function extendLifeTime(operationId : uint) : void
{
for each (var sub : SimpleAllocation in _subAllocations)
sub.extendLifeTime(operationId);
}
public function overlapsWith(other : IAllocation, readOnly : Boolean) : Boolean
{
if (other is SimpleAllocation)
{
return other.overlapsWith(this, readOnly);
}
else if (other is ContiguousAllocation)
{
var contiOther : ContiguousAllocation = ContiguousAllocation(other);
for each (var sub1 : SimpleAllocation in _subAllocations)
for each (var sub2 : SimpleAllocation in contiOther.subAllocations)
if (sub1.overlapsWith(sub2, readOnly))
return true;
return false;
}
else
throw new Error('Unknown allocation type.');
}
public function toString() : String
{
var result : String;
result = 'Contiguous\n';
for each (var subAlloc : SimpleAllocation in _subAllocations)
result += "\t" + subAlloc.toString() + "\n";
return result;
}
}
}
|
package aerys.minko.render.shader.compiler.allocation
{
import aerys.minko.render.shader.compiler.register.Components;
/**
* @private
* @author Romain Gilliotte
*
*/
public class ContiguousAllocation implements IAllocation
{
private var _subAllocations : Vector.<SimpleAllocation>;
private var _offsets : Vector.<uint>;
public function get type() : uint
{
return _subAllocations[0].type;
}
public function get registerId() : uint
{
return _subAllocations[0].registerId;
}
public function get registerOffset() : uint
{
return offset % 4;
}
public function get aligned() : Boolean
{
return false;
}
public function get offset() : uint
{
return _subAllocations[0].offset - _offsets[0];
}
public function get maxSize() : uint
{
var numArgs : uint = _subAllocations.length;
var maxSize : uint = 0;
for (var argId : uint = 0; argId < numArgs; ++argId)
{
var currentSize : uint = _offsets[argId] + _subAllocations[argId].maxSize;
if (currentSize > maxSize)
maxSize = currentSize;
}
return maxSize;
}
public function get subAllocations() : Vector.<SimpleAllocation>
{
return _subAllocations;
}
public function set offset(v : uint) : void
{
var numArgs : uint = _subAllocations.length;
for (var argId : uint = 0; argId < numArgs; ++argId)
_subAllocations[argId].offset = v + _offsets[argId];
}
public function ContiguousAllocation(subAllocations : Vector.<SimpleAllocation>,
offsets : Vector.<uint>)
{
_subAllocations = subAllocations;
_offsets = offsets;
}
public function getReadSwizzle(readingOpWriteOffset : uint,
readingOpComponents : uint) : uint
{
var components : uint;
components = readingOpComponents;
components = Components.applyWriteOffset(components, readingOpWriteOffset);
components = Components.applyReadOffset(components, registerOffset);
if (components == Components.stringToComponent('____'))
throw new Error();
return Components.generateReadSwizzle(components);
}
public function extendLifeTime(operationId : uint) : void
{
for each (var sub : SimpleAllocation in _subAllocations)
sub.extendLifeTime(operationId);
}
public function overlapsWith(other : IAllocation, readOnly : Boolean) : Boolean
{
if (other is SimpleAllocation)
{
return other.overlapsWith(this, readOnly);
}
else if (other is ContiguousAllocation)
{
var contiOther : ContiguousAllocation = ContiguousAllocation(other);
for each (var sub1 : SimpleAllocation in _subAllocations)
for each (var sub2 : SimpleAllocation in contiOther.subAllocations)
if (sub1.overlapsWith(sub2, readOnly))
return true;
return false;
}
else
throw new Error('Unknown allocation type.');
}
public function toString() : String
{
var result : String;
result = 'Contiguous\n';
for each (var subAlloc : SimpleAllocation in _subAllocations)
result += "\t" + subAlloc.toString() + "\n";
return result;
}
}
}
|
Remove dead code
|
Remove dead code
|
ActionScript
|
mit
|
aerys/minko-as3
|
e3b1f20e756a784063e83aa512033a5a046abd97
|
frameworks/projects/mobiletheme/src/spark/skins/ios7/VScrollBarSkin.as
|
frameworks/projects/mobiletheme/src/spark/skins/ios7/VScrollBarSkin.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.skins.ios7
{
import mx.core.DPIClassification;
import mx.core.mx_internal;
import spark.components.Button;
import spark.components.VScrollBar;
import spark.skins.mobile.supportClasses.MobileSkin;
use namespace mx_internal;
/**
* ActionScript-based skin for VScrollBar components in mobile applications.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class VScrollBarSkin extends MobileSkin
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
public function VScrollBarSkin()
{
super();
minHeight = 20;
thumbSkinClass = VScrollBarThumbSkin;
var paddingRight:int;
var paddingVertical:int;
// Depending on density set our measured width
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
minWidth = 24;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_640DPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_640DPI;
break;
}
case DPIClassification.DPI_480:
{
minWidth = 18;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_480DPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_480DPI;
break;
}
case DPIClassification.DPI_320:
{
minWidth = 12;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_320DPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_320DPI;
break;
}
case DPIClassification.DPI_240:
{
minWidth = 9;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_240DPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_240DPI;
break;
}
case DPIClassification.DPI_120:
{
minWidth = 9;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_120DPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_120DPI;
break;
}
default:
{
// default DPI_160
minWidth = 6;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_DEFAULTDPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_DEFAULTDPI;
break;
}
}
// The minimum height is set such that, at it's smallest size, the thumb appears
// as high as it is wide.
minThumbHeight = (minWidth - paddingRight) + (paddingVertical * 2);
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @copy spark.skins.spark.ApplicationSkin#hostComponent
*/
public var hostComponent:VScrollBar;
/**
* Minimum height for the thumb
*/
protected var minThumbHeight:Number;
/**
* Skin to use for the thumb Button skin part
*/
protected var thumbSkinClass:Class;
//--------------------------------------------------------------------------
//
// Skin parts
//
//--------------------------------------------------------------------------
/**
* VScrollbar track skin part
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public var track:Button;
/**
* VScrollbar thumb skin part
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public var thumb:Button;
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function createChildren():void
{
// Create our skin parts if necessary: track and thumb.
if (!track)
{
// We don't want a visible track so we set the skin to MobileSkin
track = new Button();
track.setStyle("skinClass", spark.skins.mobile.supportClasses.MobileSkin);
track.width = minWidth;
track.height = minHeight;
addChild(track);
}
if (!thumb)
{
thumb = new Button();
thumb.minHeight = minThumbHeight;
thumb.setStyle("skinClass", thumbSkinClass);
thumb.width = minWidth;
thumb.height = minWidth;
addChild(thumb);
}
}
/**
* @private
*/
override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void
{
super.layoutContents(unscaledWidth, unscaledHeight);
setElementSize(track, unscaledWidth, unscaledHeight);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package spark.skins.ios7
{
import mx.core.DPIClassification;
import mx.core.mx_internal;
import spark.components.Button;
import spark.components.VScrollBar;
import spark.skins.mobile.supportClasses.MobileSkin;
use namespace mx_internal;
/**
* ActionScript-based skin for VScrollBar components in mobile applications.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class VScrollBarSkin extends MobileSkin
{
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*
*/
public function VScrollBarSkin()
{
super();
minHeight = 20;
thumbSkinClass = VScrollBarThumbSkin;
var paddingRight:int;
var paddingVertical:int;
// Depending on density set our measured width
switch (applicationDPI)
{
case DPIClassification.DPI_640:
{
minWidth = 24;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_640DPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_640DPI;
break;
}
case DPIClassification.DPI_480:
{
minWidth = 16;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_480DPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_480DPI;
break;
}
case DPIClassification.DPI_320:
{
minWidth = 12;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_320DPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_320DPI;
break;
}
case DPIClassification.DPI_240:
{
minWidth = 8;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_240DPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_240DPI;
break;
}
case DPIClassification.DPI_120:
{
minWidth = 4;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_120DPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_120DPI;
break;
}
default:
{
// default DPI_160
minWidth = 6;
paddingRight = VScrollBarThumbSkin.PADDING_RIGHT_DEFAULTDPI;
paddingVertical = VScrollBarThumbSkin.PADDING_VERTICAL_DEFAULTDPI;
break;
}
}
// The minimum height is set such that, at it's smallest size, the thumb appears
// as high as it is wide.
minThumbHeight = (minWidth - paddingRight) + (paddingVertical * 2);
}
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
/**
* @copy spark.skins.spark.ApplicationSkin#hostComponent
*/
public var hostComponent:VScrollBar;
/**
* Minimum height for the thumb
*/
protected var minThumbHeight:Number;
/**
* Skin to use for the thumb Button skin part
*/
protected var thumbSkinClass:Class;
//--------------------------------------------------------------------------
//
// Skin parts
//
//--------------------------------------------------------------------------
/**
* VScrollbar track skin part
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public var track:Button;
/**
* VScrollbar thumb skin part
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public var thumb:Button;
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
/**
* @private
*/
override protected function createChildren():void
{
// Create our skin parts if necessary: track and thumb.
if (!track)
{
// We don't want a visible track so we set the skin to MobileSkin
track = new Button();
track.setStyle("skinClass", spark.skins.mobile.supportClasses.MobileSkin);
track.width = minWidth;
track.height = minHeight;
addChild(track);
}
if (!thumb)
{
thumb = new Button();
thumb.minHeight = minThumbHeight;
thumb.setStyle("skinClass", thumbSkinClass);
thumb.width = minWidth;
thumb.height = minWidth;
addChild(thumb);
}
}
/**
* @private
*/
override protected function layoutContents(unscaledWidth:Number, unscaledHeight:Number):void
{
super.layoutContents(unscaledWidth, unscaledHeight);
setElementSize(track, unscaledWidth, unscaledHeight);
}
}
}
|
Tweak VScrollBarkSkin to make sure it looks good in all DPIs
|
Tweak VScrollBarkSkin to make sure it looks good in all DPIs
|
ActionScript
|
apache-2.0
|
apache/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,shyamalschandra/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk
|
73452ea968fe5052e44dacdbd00c31c1e4c56cd5
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/IStyleableObject.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/IStyleableObject.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 org.apache.flex.events.IEventDispatcher;
/**
* The IStyleableObject interface is the interface for
* objects that support style properties.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public interface IStyleableObject extends IEventDispatcher
{
/**
* Get the className(s) that will be used to
* choose class selectors in most CSS style
* implementations. This property is called
* styleName in the Flex SDK.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
function get className():String;
/**
* Get the object containing styles
* for this object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
function get style():Object;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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 org.apache.flex.events.IEventDispatcher;
/**
* The IStyleableObject interface is the interface for
* objects that support style properties.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public interface IStyleableObject extends IEventDispatcher
{
/**
* Get the className(s) that will be used to
* choose class selectors in most CSS style
* implementations. This property is called
* styleName in the Flex SDK.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
function get className():String;
function set className(value:String):void;
/**
* Get the object containing styles
* for this object.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
function get style():Object;
}
}
|
allow writing of className via the interface
|
allow writing of className via the interface
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
2f3fd2ee67bfa754ea84af3cc87172a15925fbb0
|
test/AllTests.as
|
test/AllTests.as
|
package
{
/**
* This file has been automatically created using
* #!/usr/bin/ruby script/generate suite
* If you modify it and run this script, your
* modifications will be lost!
*/
import as3spec.*;
import com.gigya.WildfireTest;
import ras3r.controls.TextTest;
import ras3r.reaction_view.helpers.ImageHelperTest;
import ras3r.reaction_view.helpers.TextFieldHelperTest;
public class AllTests extends Suite
{
public function AllTests ()
{
add(com.gigya.WildfireTest);
add(ras3r.controls.TextTest);
add(ras3r.reaction_view.helpers.ImageHelperTest);
add(ras3r.reaction_view.helpers.TextFieldHelperTest);
}
}
}
|
package
{
/**
* This file has been automatically created using
* #!/usr/bin/ruby script/generate suite
* If you modify it and run this script, your
* modifications will be lost!
*/
import as3spec.*;
import com.gigya.WildfireTest;
import ras3r.HashTest;
import ras3r.reaction_view.helpers.BoxHelperTest;
import ras3r.reaction_view.helpers.ComboBoxHelperTest;
import ras3r.reaction_view.helpers.ImageHelperTest;
import ras3r.reaction_view.helpers.TextFieldHelperTest;
import ras3r.reaction_view.helpers.TextInputHelperTest;
import ras3r.ReactionControllerTest;
import ras3r.ReactionViewTest;
import ras3r.reactive_resource.ResponseTest;
public class AllTests extends Suite
{
public function AllTests ()
{
add(com.gigya.WildfireTest);
add(ras3r.HashTest);
add(ras3r.reaction_view.helpers.BoxHelperTest);
add(ras3r.reaction_view.helpers.ComboBoxHelperTest);
add(ras3r.reaction_view.helpers.ImageHelperTest);
add(ras3r.reaction_view.helpers.TextFieldHelperTest);
add(ras3r.reaction_view.helpers.TextInputHelperTest);
add(ras3r.ReactionControllerTest);
add(ras3r.ReactionViewTest);
add(ras3r.reactive_resource.ResponseTest);
}
}
}
|
reset test suite
|
reset test suite
|
ActionScript
|
mit
|
f1337/metafas3,f1337/metafas3
|
09607ce618998f098daf204f4dfb54f3a79408c3
|
HLSPlugin/src/org/denivip/osmf/utils/Utils.as
|
HLSPlugin/src/org/denivip/osmf/utils/Utils.as
|
package org.denivip.osmf.utils
{
import org.osmf.utils.URL;
public class Utils
{
public static function createFullUrl(rootUrl:String, url:String):String{
if(url.search(/(ftp|file|https?):\/\/\/?/) == 0)
return url;
// other manipulations :)
if(url.charAt(0) == '/'){
return URL.getRootUrl(rootUrl) + url;
}
if(rootUrl.lastIndexOf('/') != rootUrl.length)
rootUrl += '/';
return rootUrl + url;
}
}
}
|
package org.denivip.osmf.utils
{
import org.osmf.utils.URL;
public class Utils
{
public static function createFullUrl(rootUrl:String, url:String):String {
if(url.search(/(ftp|file|https?):\/\/\/?/) == 0)
return url;
// other manipulations :)
if(url.charAt(0) == '/'){
return URL.getRootUrl(rootUrl) + url;
}
if(rootUrl.lastIndexOf('/') != rootUrl.length - 1)
rootUrl += '/';
return rootUrl + url;
}
}
}
|
Fix issue where check for final slash was comparing zero-based index with length
|
Fix issue where check for final slash was comparing zero-based index with length
|
ActionScript
|
isc
|
mruse/osmf-hls-plugin,denivip/osmf-hls-plugin,mruse/osmf-hls-plugin,denivip/osmf-hls-plugin
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.