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
|
---|---|---|---|---|---|---|---|---|---|
db641703e5ec6d726a1b29af63215781ef2ef2e6
|
exporter/src/main/as/flump/xfl/XflLayer.as
|
exporter/src/main/as/flump/xfl/XflLayer.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flump.mold.LayerMold;
import com.threerings.util.XmlUtil;
public class XflLayer
{
use namespace xflns;
public static function parse (lib :XflLibrary, baseLocation :String, xml :XML, flipbook :Boolean) :LayerMold {
const layer :LayerMold = new LayerMold();
layer.name = XmlUtil.getStringAttr(xml, "name");
layer.flipbook = flipbook;
layer.location = baseLocation + ":" + layer.name
for each (var frameEl :XML in xml.frames.DOMFrame) {
layer.keyframes.push(XflKeyframe.parse(lib, layer.location, frameEl, flipbook));
}
if (layer.keyframes.length == 0) lib.addError(layer, ParseError.INFO, "No keyframes on layer");
return layer;
}
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
import com.threerings.util.XmlUtil;
public class XflLayer
{
use namespace xflns;
public static function parse (lib :XflLibrary, baseLocation :String, xml :XML, flipbook :Boolean) :LayerMold {
const layer :LayerMold = new LayerMold();
layer.name = XmlUtil.getStringAttr(xml, "name");
layer.flipbook = flipbook;
layer.location = baseLocation + ":" + layer.name
for each (var frameEl :XML in xml.frames.DOMFrame) {
layer.keyframes.push(XflKeyframe.parse(lib, layer.location, frameEl, flipbook));
}
if (layer.keyframes.length == 0) lib.addError(layer, ParseError.INFO, "No keyframes on layer");
// normalize rotations, so that we always rotate the shortest distance between
// two angles (we don't want to rotate more than Math.PI)
// TODO: support keyframes with rotations >= TWO_PI
for (var ii :int = 0; ii < layer.keyframes.length - 1; ++ii) {
var kf :KeyframeMold = layer.keyframes[ii];
var nextKf :KeyframeMold = layer.keyframes[ii+1];
if (kf.rotation + Math.PI < nextKf.rotation) {
nextKf.rotation -= Math.PI * 2;
} else if (kf.rotation - Math.PI > nextKf.rotation) {
nextKf.rotation += Math.PI * 2;
}
}
return layer;
}
}
}
|
normalize keyframe rotations
|
normalize keyframe rotations
We want to rotate the shortest distance between two angles (i.e.
rotation <= PI)
|
ActionScript
|
mit
|
mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,funkypandagame/flump
|
fc57086925a0ca7a7e2bd9e10d3d3d8c75ff8c84
|
collect-flex/collect-flex-client/src/generated/flex/org/openforis/collect/model/proxy/RecordProxy.as
|
collect-flex/collect-flex-client/src/generated/flex/org/openforis/collect/model/proxy/RecordProxy.as
|
/**
* Generated by Gas3 v2.2.0 (Granite Data Services).
*
* NOTE: this file is only generated if it does not exist. You may safely put
* your custom code here.
*/
package org.openforis.collect.model.proxy {
import mx.collections.ArrayCollection;
import mx.collections.IList;
import org.granite.collections.IMap;
import org.openforis.collect.remoting.service.UpdateResponse;
[Bindable]
[RemoteClass(alias="org.openforis.collect.model.proxy.RecordProxy")]
public class RecordProxy extends RecordProxyBase {
private var _updated:Boolean = false;
private var _saved:Boolean = false;
private var validationResults:ValidationResultsProxy;
public function getNode(id:int):NodeProxy {
if(id == rootEntity.id) {
return rootEntity;
} else {
return rootEntity.getNode(id);
}
}
public function update(responses:IList):void {
for each (var response:UpdateResponse in responses) {
processResponse(response);
}
_updated = true;
}
private function processResponse(response:UpdateResponse):void {
var node:NodeProxy, oldNode:NodeProxy, parent:EntityProxy;
if(response.createdNode != null) {
node = response.createdNode;
parent = getNode(node.parentId) as EntityProxy;
parent.addChild(node);
}
if(response.deletedNodeId > 0) {
node = getNode(response.deletedNodeId);
if(node != null) {
parent = getNode(node.parentId) as EntityProxy;
parent.removeChild(node);
}
} else {
node = getNode(response.nodeId);
if(node is AttributeProxy) {
var a:AttributeProxy = AttributeProxy(node);
if(response.validationResults != null) {
a.validationResults = response.validationResults;
}
if(response.updatedFieldValues != null) {
var fieldIdxs:ArrayCollection = response.updatedFieldValues.keySet;
for each (var i:int in fieldIdxs) {
var f:FieldProxy = a.getField(i);
f.value = response.updatedFieldValues.get(i);
}
}
} else if(node is EntityProxy) {
var e:EntityProxy = EntityProxy(node);
if(response.maxCountValidation != null && response.maxCountValidation.length > 0) {
e.updateChildrenMaxCountValiditationMap(response.maxCountValidation);
}
if(response.minCountValidation != null && response.minCountValidation.length > 0) {
e.updateChildrenMinCountValiditationMap(response.minCountValidation);
}
if(response.relevant != null && response.relevant.length > 0) {
e.updateChildrenRelevanceMap(response.relevant);
}
if(response.required != null && response.required.length > 0) {
e.updateChildrenRequiredMap(response.required);
}
}
}
}
public function get updated():Boolean {
return _updated;
}
public function get saved():Boolean {
return _saved;
}
public function set saved(value:Boolean):void {
_saved = value;
}
}
}
|
/**
* Generated by Gas3 v2.2.0 (Granite Data Services).
*
* NOTE: this file is only generated if it does not exist. You may safely put
* your custom code here.
*/
package org.openforis.collect.model.proxy {
import mx.collections.ArrayCollection;
import mx.collections.IList;
import org.granite.collections.IMap;
import org.openforis.collect.remoting.service.UpdateResponse;
[Bindable]
[RemoteClass(alias="org.openforis.collect.model.proxy.RecordProxy")]
public class RecordProxy extends RecordProxyBase {
private var _updated:Boolean = false;
private var _saved:Boolean = false;
private var validationResults:ValidationResultsProxy;
public function getNode(id:int):NodeProxy {
if(id == rootEntity.id) {
return rootEntity;
} else {
return rootEntity.getNode(id);
}
}
public function update(responses:IList):void {
for each (var response:UpdateResponse in responses) {
processResponse(response);
}
_updated = true;
}
private function processResponse(response:UpdateResponse):void {
var node:NodeProxy, oldNode:NodeProxy, parent:EntityProxy;
if(response.createdNode != null) {
node = response.createdNode;
parent = getNode(node.parentId) as EntityProxy;
parent.addChild(node);
}
if(response.deletedNodeId > 0) {
node = getNode(response.deletedNodeId);
if(node != null) {
parent = getNode(node.parentId) as EntityProxy;
parent.removeChild(node);
}
} else {
node = getNode(response.nodeId);
if(node is AttributeProxy) {
var a:AttributeProxy = AttributeProxy(node);
if(response.validationResults != null) {
a.validationResults = response.validationResults;
}
if(response.updatedFieldValues != null) {
var fieldIdxs:ArrayCollection = response.updatedFieldValues.keySet;
for each (var i:int in fieldIdxs) {
var f:FieldProxy = a.getField(i);
f.value = response.updatedFieldValues.get(i);
}
parent = getNode(node.parentId) as EntityProxy;
parent.updateKeyText();
}
} else if(node is EntityProxy) {
var e:EntityProxy = EntityProxy(node);
if(response.maxCountValidation != null && response.maxCountValidation.length > 0) {
e.updateChildrenMaxCountValiditationMap(response.maxCountValidation);
}
if(response.minCountValidation != null && response.minCountValidation.length > 0) {
e.updateChildrenMinCountValiditationMap(response.minCountValidation);
}
if(response.relevant != null && response.relevant.length > 0) {
e.updateChildrenRelevanceMap(response.relevant);
}
if(response.required != null && response.required.length > 0) {
e.updateChildrenRequiredMap(response.required);
}
}
}
}
public function get updated():Boolean {
return _updated;
}
public function get saved():Boolean {
return _saved;
}
public function set saved(value:Boolean):void {
_saved = value;
}
}
}
|
Update rootEntityKey label when updating a key attribute
|
Update rootEntityKey label when updating a key attribute
|
ActionScript
|
mit
|
openforis/collect,openforis/collect,openforis/collect,openforis/collect
|
f76dcbebcfb20b19e43c4fc66489fb7bfd30d1ce
|
src/flails/request/HTTPClient.as
|
src/flails/request/HTTPClient.as
|
/**
* Copyright (c) 2009 Lance Carlson
* See LICENSE for full license information.
*/
/*
Client does not handle status codes over 200 because of flash and URLLoader. Therefore, all validation
errors or NotFound errors need to be sent back with a 200 status code. Whenever an exception is raised,
an IOError is fired which is automatically handled by the framework to Alert that there was a problem.
Check this for details:
http://stackoverflow.com/questions/188887/how-to-access-as3-urlloader-return-data-on-ioerrorevent
*/
package flails.request {
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLVariables;
import mx.rpc.events.ResultEvent;
import flails.request.Filter;
import flails.request.PathBuilder;
import flails.request.RequestPipe;
//import com.adobe.serialization.json.*;
public class HTTPClient extends EventDispatcher implements RequestPipe {
private var loader:URLLoader = new URLLoader();
private var request:URLRequest = new URLRequest();
private var errorHandler:Function;
private var pathBuilder:PathBuilder;
private var filter:Filter;
private var config:RequestConfig;
// Dispatched after all the received data is decoded and placed in the data property of the URLLoader object. The received data may be accessed once this event has been dispatched.
public const COMPLETE:String = "complete";
// Dispatched when the download operation commences following a call to the URLLoader.load() method.
public const OPEN:String = "open";
// Dispatched when data is received as the download operation progresses.
public const PROGRESS:String = "progress";
// Dispatched if a call to URLLoader.load() attempts to access data over HTTP and the current Flash Player environment is able to detect and return the status code for the request.
public const HTTP_STATUS:String = "httpStatus";
// Dispatched if a call to URLLoader.load() results in a fatal error that terminates the download.
public const IO_ERROR:String = "ioError";
// Dispatched if a call to URLLoader.load() attempts to load data from a server outside the security sandbox.
public const SECURITY_ERROR:String = "securityError";
public function HTTPClient(pathBuilder:PathBuilder, filter:Filter, config:RequestConfig) {
this.pathBuilder = pathBuilder;
this.filter = filter;
this.config = config;
}
public function index(data:Object = null, ... parentIds):void {
trace("entered index");
configureRequest(data, "GET");
doGet(pathBuilder.index(parentIds));
}
public function show(id:Object = null, data:Object = null, ... parentIds):void {
configureRequest(data, "GET");
doGet(pathBuilder.show(id, parentIds));
}
public function create(data:Object = null, ... parentIds):void {
configureRequest(data, "POST");
doPost(pathBuilder.create(parentIds));
}
public function update(id:Object = null, data:Object = null, ... parentIds):void {
configureRequest(data, "PUT");
doPost(pathBuilder.update(id, parentIds));
}
public function destroy(id:Object, data:Object = null, ... parentIds):void {
configureRequest(data, "DELETE");
doPost(pathBuilder.destroy(id, parentIds));
}
private function configureRequest(params:Object, method:String):void {
trace("configuring...")
var variables:URLVariables = new URLVariables();
// TODO: This is rails specific. Move it somewhere more appropriate
if (method == "PUT" || method == "DELETE") {
variables["_method"] = method.toLowerCase();
}
trace("Adding " + config.extraParams.length + " extra variables");
for each (var p:RequestParam in config.extraParams) {
trace("adding extra var " + p.name + " with value " + p.value);
variables[p.name] = p.value;
}
// replace this with filter.dump(params). Make ARSON filter take care of the resource[param] concatenation
paramsToVariables(variables, params);
request.data = variables;
}
private function paramsToVariables(variables:URLVariables, params:Object, prefix:String = null):void {
for (var param:String in params) {
var name:String;
if (prefix) {
name = prefix + "[" + param + "]";
} else {
name = param;
}
trace("setting variable " + name);
if (!(params[param] is String) && !(params[param] is Number)) {
trace("param " + param + " is an object (" + params[param].constructor + ")");
paramsToVariables(variables, params[param], name);
} else {
trace("value for param" + param + " is " + params[param]);
variables[name] = params[param];
}
}
}
private function onComplete(event:Event):void {
var response:URLLoader = URLLoader(event.target);
if (response.data.replace(" ", "").length != 0) {
dispatchEvent(new ResultEvent("result", false, false, filter.load(response.data)));
} else {
dispatchEvent(new ResultEvent("result"));
}
}
private function addHeader(name:String, value:String):void {
request.requestHeaders.push(new URLRequestHeader(name, value));
}
public function doGet(url:String):void {
trace("entering doGet");
// TODO: This should be set by the filter
addHeader("Content-Type", "application/json");
trace("setting url " + config.baseUrl + url);
request.url = config.baseUrl + url;
loader.addEventListener("complete", onComplete);
loader.load(request);
}
public function doPost(url:String):void {
trace("entering doPost");
addHeader("Content-Type", "application/x-www-form-urlencoded");
request.method = "POST";
trace("setting url " + config.baseUrl + url);
request.url = config.baseUrl + url;
loader.addEventListener("complete", onComplete);
loader.load(request);
}
}
}
|
/**
* Copyright (c) 2009 Lance Carlson
* See LICENSE for full license information.
*/
/*
Client does not handle status codes over 200 because of flash and URLLoader. Therefore, all validation
errors or NotFound errors need to be sent back with a 200 status code. Whenever an exception is raised,
an IOError is fired which is automatically handled by the framework to Alert that there was a problem.
Check this for details:
http://stackoverflow.com/questions/188887/how-to-access-as3-urlloader-return-data-on-ioerrorevent
*/
package flails.request {
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLVariables;
import mx.rpc.events.ResultEvent;
import flails.request.Filter;
import flails.request.PathBuilder;
import flails.request.RequestPipe;
//import com.adobe.serialization.json.*;
public class HTTPClient extends EventDispatcher implements RequestPipe {
private var loader:URLLoader = new URLLoader();
private var request:URLRequest = new URLRequest();
private var errorHandler:Function;
private var pathBuilder:PathBuilder;
private var filter:Filter;
private var config:RequestConfig;
// Dispatched after all the received data is decoded and placed in the data property of the URLLoader object. The received data may be accessed once this event has been dispatched.
public const COMPLETE:String = "complete";
// Dispatched when the download operation commences following a call to the URLLoader.load() method.
public const OPEN:String = "open";
// Dispatched when data is received as the download operation progresses.
public const PROGRESS:String = "progress";
// Dispatched if a call to URLLoader.load() attempts to access data over HTTP and the current Flash Player environment is able to detect and return the status code for the request.
public const HTTP_STATUS:String = "httpStatus";
// Dispatched if a call to URLLoader.load() results in a fatal error that terminates the download.
public const IO_ERROR:String = "ioError";
// Dispatched if a call to URLLoader.load() attempts to load data from a server outside the security sandbox.
public const SECURITY_ERROR:String = "securityError";
public function HTTPClient(pathBuilder:PathBuilder, filter:Filter, config:RequestConfig) {
this.pathBuilder = pathBuilder;
this.filter = filter;
this.config = config;
}
public function index(data:Object = null, ... parentIds):void {
trace("entered index");
configureRequest(data, "GET");
doGet(pathBuilder.index(parentIds));
}
public function show(id:Object = null, data:Object = null, ... parentIds):void {
configureRequest(data, "GET");
doGet(pathBuilder.show(id, parentIds));
}
public function create(data:Object = null, ... parentIds):void {
configureRequest(data, "POST");
doPost(pathBuilder.create(parentIds));
}
public function update(id:Object = null, data:Object = null, ... parentIds):void {
configureRequest(data, "PUT");
doPost(pathBuilder.update(id, parentIds));
}
public function destroy(id:Object, data:Object = null, ... parentIds):void {
configureRequest(data, "DELETE");
doPost(pathBuilder.destroy(id, parentIds));
}
private function configureRequest(params:Object, method:String):void {
trace("configuring...")
var variables:URLVariables = new URLVariables();
// TODO: This is rails specific. Move it somewhere more appropriate
if (method == "PUT" || method == "DELETE") {
variables["_method"] = method.toLowerCase();
}
trace("Adding " + config.extraParams.length + " extra variables");
for each (var p:RequestParam in config.extraParams) {
trace("adding extra var " + p.name + " with value " + p.value);
variables[p.name] = p.value;
}
// replace this with filter.dump(params). Make ARSON filter take care of the resource[param] concatenation
paramsToVariables(variables, params);
request.data = variables;
}
private function paramsToVariables(variables:URLVariables, params:Object, prefix:String = null):void {
if (params is Array) {
for (var i:int = 0; i < params.length; i++) {
if (!(params[i] is String) && !(params[i] is Number)) {
trace("param " + i + " is an object (" + params[i].constructor + ")");
paramsToVariables(variables, params[i], prefix + "[" + i + "]");
} else {
trace("value for param" + i + " is " + params[param]);
variables[prefix + "[" + i + "]"] = params[i];
}
}
} else {
for (var param:String in params) {
var name:String;
if (prefix) {
name = prefix + "[" + param + "]";
} else {
name = param;
}
trace("setting variable " + name);
if (!(params[param] is String) && !(params[param] is Number)) {
trace("param " + param + " is an object (" + params[param].constructor + ")");
paramsToVariables(variables, params[param], name);
} else {
trace("value for param" + param + " is " + params[param]);
variables[name] = params[param];
}
}
}
}
private function onComplete(event:Event):void {
var response:URLLoader = URLLoader(event.target);
if (response.data.replace(" ", "").length != 0) {
dispatchEvent(new ResultEvent("result", false, false, filter.load(response.data)));
} else {
dispatchEvent(new ResultEvent("result"));
}
}
private function addHeader(name:String, value:String):void {
request.requestHeaders.push(new URLRequestHeader(name, value));
}
public function doGet(url:String):void {
trace("entering doGet");
// TODO: This should be set by the filter
addHeader("Content-Type", "application/json");
trace("setting url " + config.baseUrl + url);
request.url = config.baseUrl + url;
loader.addEventListener("complete", onComplete);
loader.load(request);
}
public function doPost(url:String):void {
trace("entering doPost");
addHeader("Content-Type", "application/x-www-form-urlencoded");
request.method = "POST";
trace("setting url " + config.baseUrl + url);
request.url = config.baseUrl + url;
loader.addEventListener("complete", onComplete);
loader.load(request);
}
}
}
|
Send arrays in the parameters.
|
Send arrays in the parameters.
|
ActionScript
|
mit
|
lancecarlson/flails,lancecarlson/flails
|
dd635327043d40cf626bed5171fdd843ca68b833
|
src/org/mangui/hls/demux/Nalu.as
|
src/org/mangui/hls/demux/Nalu.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import org.mangui.hls.HLSSettings;
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the H264 video format. **/
public class Nalu {
/** H264 NAL unit names. **/
private static const NAMES : Array = ['Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data'// 12
];
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> {
var units : Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start : int;
var unit_type : int;
var unit_header : int;
// Loop through data to find NAL startcodes.
var window : uint = 0;
nalu.position = position;
while (nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if ((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
// Match three-byte startcodes
} else if ((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if (unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
CONFIG::LOGGING {
if (HLSSettings.logDebug2) {
if (units.length) {
var txt : String = "AVC: ";
for (var i : int = 0; i < units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0, txt.length - 2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
}
nalu.position = position;
return units;
};
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the H264 video format. **/
public class Nalu {
/** H264 NAL unit names. **/
private static const NAMES : Array = ['Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data'// 12
];
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> {
var units : Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start : int;
var unit_type : int;
var unit_header : int;
// Loop through data to find NAL startcodes.
var window : uint = 0;
nalu.position = position;
while (nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if ((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
// Match three-byte startcodes
} else if ((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if (unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
CONFIG::LOGGING {
if (HLSSettings.logDebug2) {
if (units.length) {
var txt : String = "AVC: ";
for (var i : int = 0; i < units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0, txt.length - 2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
}
nalu.position = position;
return units;
};
}
}
|
Move `HLSSettings` import into logging block.
|
Move `HLSSettings` import into logging block.
This was breaking release builds for me.
|
ActionScript
|
mpl-2.0
|
stevemayhew/flashls,stevemayhew/flashls,stevemayhew/flashls,stevemayhew/flashls
|
7961f9edd8f78988d976f9cd14aa3591cdf19c94
|
src/org/mangui/hls/demux/Nalu.as
|
src/org/mangui/hls/demux/Nalu.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import org.mangui.hls.HLSSettings;
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the H264 video format. **/
public class Nalu {
/** H264 NAL unit names. **/
private static const NAMES : Array = ['Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data'// 12
];
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> {
var units : Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start : int;
var unit_type : int;
var unit_header : int;
// Loop through data to find NAL startcodes.
var window : uint = 0;
nalu.position = position;
while (nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if ((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
// Match three-byte startcodes
} else if ((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if (unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
CONFIG::LOGGING {
if (HLSSettings.logDebug2) {
if (units.length) {
var txt : String = "AVC: ";
for (var i : int = 0; i < units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0, txt.length - 2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
}
nalu.position = position;
return units;
};
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls.demux {
import flash.utils.ByteArray;
CONFIG::LOGGING {
import org.mangui.hls.HLSSettings;
import org.mangui.hls.utils.Log;
}
/** Constants and utilities for the H264 video format. **/
public class Nalu {
/** H264 NAL unit names. **/
private static const NAMES : Array = ['Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data'// 12
];
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu : ByteArray, position : uint) : Vector.<VideoFrame> {
var units : Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start : int;
var unit_type : int;
var unit_header : int;
// Loop through data to find NAL startcodes.
var window : uint = 0;
nalu.position = position;
while (nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if ((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
// Match three-byte startcodes
} else if ((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if (unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if (unit_type == 1 || unit_type == 5) {
break;
}
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if (unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
CONFIG::LOGGING {
if (HLSSettings.logDebug2) {
if (units.length) {
var txt : String = "AVC: ";
for (var i : int = 0; i < units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0, txt.length - 2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
}
nalu.position = position;
return units;
};
}
}
|
Move `HLSSettings` import into logging block.
|
Move `HLSSettings` import into logging block.
This was breaking release builds for me.
|
ActionScript
|
mpl-2.0
|
ryanhefner/flashls,ryanhefner/flashls,ryanhefner/flashls,ryanhefner/flashls
|
faa3315d7d902ffd944034cbd59054c423f2c7e1
|
src/as/com/threerings/flex/FlexUtil.as
|
src/as/com/threerings/flex/FlexUtil.as
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flex {
import flash.display.DisplayObject;
import mx.controls.Label;
import mx.controls.Spacer;
import mx.controls.Text;
import mx.core.Container;
import mx.core.UIComponent;
import mx.containers.HBox;
import mx.containers.VBox;
/**
* Flex-related utility methods.
*/
public class FlexUtil
{
/**
* Creates a label with the supplied text, and optionally applies a style class and tooltip
* to it.
*/
public static function createLabel (
text :String, style :String = null, toolTip :String = null) :Label
{
var label :Label = new Label();
label.text = text;
label.styleName = style;
label.toolTip = toolTip;
return label;
}
/**
* Create an uneditable/unselectable multiline Text widget with the specified text and width.
*/
public static function createText (text :String, width :int, style :String = null) :Text
{
var t :Text = new Text();
t.styleName = style;
t.width = width;
t.selectable = false;
t.text = text;
return t;
}
/**
* Create an uneditable/unselectable multiline Text widget with 100% width.
*/
public static function createWideText (text :String, style :String = null) :Text
{
var t :Text = new Text();
t.styleName = style;
t.percentWidth = 100;
t.selectable = false;
t.text = text;
return t;
}
/**
* How hard would it have been for them make Spacer accept two optional arguments?
*/
public static function createSpacer (width :int = 0, height :int = 0) :Spacer
{
var spacer :Spacer = new Spacer();
spacer.width = width;
spacer.height = height;
return spacer;
}
/**
* Return a count of how many visible (includeInLayout=true) children
* are in the specified container.
*/
public static function countLayoutChildren (container :Container) :int
{
var layoutChildren :int = container.numChildren;
for each (var child :Object in container.getChildren()) {
if ((child is UIComponent) && !UIComponent(child).includeInLayout) {
layoutChildren--;
}
}
return layoutChildren;
}
/**
* In flex the 'visible' property controls visibility separate from whether
* the component takes up space in the layout, which is controlled by 'includeInLayout'.
* We usually want to set them together, so this does that for us.
* @return the new visible setting.
*/
public static function setVisible (component :UIComponent, visible :Boolean) :Boolean
{
component.visible = visible;
component.includeInLayout = visible;
return visible;
}
/**
* Creates a new container of the given class and adds the given children to it.
*/
public static function createContainer (clazz :Class, ...children) :Container
{
var container :Container = new clazz() as Container;
for each (var comp :UIComponent in children) {
container.addChild(comp);
}
return container;
}
/**
* Creates a new HBox container and adds the given children to it.
*/
public static function createHBox (...children) :Container
{
children.unshift(HBox);
return createContainer.apply(null, children);
}
/**
* Creates a new VBox container and adds the given children to it.
*/
public static function createVBox (...children) :Container
{
children.unshift(VBox);
return createContainer.apply(null, children);
}
/**
* Creates a simple UIComponent that wraps a display object.
*/
public static function wrap (obj :DisplayObject) :FlexWrapper
{
return new FlexWrapper(obj);
}
/**
* Creates a simple UIComponent that wraps a display object and inherits its size.
*/
public static function wrapSized (obj :DisplayObject) :FlexWrapper
{
return new FlexWrapper(obj, true);
}
}
}
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flex {
import flash.display.DisplayObject;
import mx.controls.Label;
import mx.controls.Spacer;
import mx.controls.Text;
import mx.core.Container;
import mx.core.UIComponent;
import mx.containers.HBox;
import mx.containers.VBox;
/**
* Flex-related utility methods.
*/
public class FlexUtil
{
/**
* Creates a label with the supplied text, and optionally applies a style class and tooltip
* to it.
*/
public static function createLabel (
text :String, style :String = null, toolTip :String = null) :Label
{
var label :Label = new Label();
label.text = text;
label.styleName = style;
label.toolTip = toolTip;
return label;
}
/**
* Create an uneditable/unselectable multiline Text widget with the specified text and width.
*/
public static function createText (text :String, width :int, style :String = null) :Text
{
var t :Text = new Text();
t.styleName = style;
t.width = width;
t.selectable = false;
t.text = text;
return t;
}
/**
* Create an uneditable/unselectable multiline Text widget with 100% width.
*/
public static function createWideText (text :String, style :String = null) :Text
{
var t :Text = new Text();
t.styleName = style;
t.percentWidth = 100;
t.selectable = false;
t.text = text;
return t;
}
/**
* How hard would it have been for them make Spacer accept two optional arguments?
*/
public static function createSpacer (width :int = 0, height :int = 0) :Spacer
{
var spacer :Spacer = new Spacer();
spacer.width = width;
spacer.height = height;
return spacer;
}
/**
* Return a count of how many visible (includeInLayout=true) children
* are in the specified container.
*/
public static function countLayoutChildren (container :Container) :int
{
var layoutChildren :int = container.numChildren;
for each (var child :Object in container.getChildren()) {
if ((child is UIComponent) && !UIComponent(child).includeInLayout) {
layoutChildren--;
}
}
return layoutChildren;
}
/**
* In flex the 'visible' property controls visibility separate from whether
* the component takes up space in the layout, which is controlled by 'includeInLayout'.
* We usually want to set them together, so this does that for us.
* @return the new visible setting.
*/
public static function setVisible (component :UIComponent, visible :Boolean) :Boolean
{
component.visible = visible;
component.includeInLayout = visible;
return visible;
}
/**
* Creates a new container of the given class and adds the given children to it.
*/
public static function createContainer (clazz :Class, ...children) :Container
{
var container :Container = new clazz() as Container;
for each (var comp :UIComponent in children) {
container.addChild(comp);
}
return container;
}
/**
* Creates a new HBox container and adds the given children to it.
*/
public static function createHBox (...children) :HBox
{
children.unshift(HBox);
return createContainer.apply(null, children) as HBox;
}
/**
* Creates a new VBox container and adds the given children to it.
*/
public static function createVBox (...children) :VBox
{
children.unshift(VBox);
return createContainer.apply(null, children) as VBox;
}
/**
* Creates a simple UIComponent that wraps a display object.
*/
public static function wrap (obj :DisplayObject) :FlexWrapper
{
return new FlexWrapper(obj);
}
/**
* Creates a simple UIComponent that wraps a display object and inherits its size.
*/
public static function wrapSized (obj :DisplayObject) :FlexWrapper
{
return new FlexWrapper(obj, true);
}
}
}
|
Return the most derived type for the box versions instead of Container. copy&paste error.
|
Return the most derived type for the box versions instead of Container. copy&paste error.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@860 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
0154bd512a1c0322d9d5202df5086499ecd4804f
|
src/org/mangui/chromeless/ChromelessPlayer.as
|
src/org/mangui/chromeless/ChromelessPlayer.as
|
package org.mangui.chromeless {
import flash.net.URLStream;
import org.mangui.hls.model.Level;
import org.mangui.hls.*;
import org.mangui.hls.utils.*;
import flash.display.*;
import flash.events.*;
import flash.external.ExternalInterface;
import flash.geom.Rectangle;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.media.StageVideo;
import flash.media.StageVideoAvailability;
import flash.utils.setTimeout;
// import com.sociodox.theminer.*;
public class ChromelessPlayer extends Sprite {
/** reference to the framework. **/
protected var _hls : HLS;
/** Sheet to place on top of the video. **/
protected var _sheet : Sprite;
/** Reference to the stage video element. **/
protected var _stageVideo : StageVideo = null;
/** Reference to the video element. **/
protected var _video : Video = null;
/** Video size **/
protected var _videoWidth : int = 0;
protected var _videoHeight : int = 0;
/** current media position */
protected var _media_position : Number;
protected var _duration : Number;
/** URL autoload feature */
protected var _autoLoad : Boolean = false;
/** Initialization. **/
public function ChromelessPlayer() {
_setupStage();
_setupSheet();
_setupExternalGetters();
_setupExternalCallers();
setTimeout(_pingJavascript, 50);
};
private function _setupExternalGetters():void {
ExternalInterface.addCallback("getLevel", _getLevel);
ExternalInterface.addCallback("getLevels", _getLevels);
ExternalInterface.addCallback("getAutoLevel", _getAutoLevel);
ExternalInterface.addCallback("getMetrics", _getMetrics);
ExternalInterface.addCallback("getDuration", _getDuration);
ExternalInterface.addCallback("getPosition", _getPosition);
ExternalInterface.addCallback("getPlaybackState", _getPlaybackState);
ExternalInterface.addCallback("getSeekState", _getSeekState);
ExternalInterface.addCallback("getType", _getType);
ExternalInterface.addCallback("getmaxBufferLength", _getmaxBufferLength);
ExternalInterface.addCallback("getminBufferLength", _getminBufferLength);
ExternalInterface.addCallback("getlowBufferLength", _getlowBufferLength);
ExternalInterface.addCallback("getbufferLength", _getbufferLength);
ExternalInterface.addCallback("getLogDebug", _getLogDebug);
ExternalInterface.addCallback("getLogDebug2", _getLogDebug2);
ExternalInterface.addCallback("getCapLeveltoStage", _getCapLeveltoStage);
ExternalInterface.addCallback("getflushLiveURLCache", _getflushLiveURLCache);
ExternalInterface.addCallback("getstartFromLevel", _getstartFromLevel);
ExternalInterface.addCallback("getseekFromLowestLevel", _getseekFromLevel);
ExternalInterface.addCallback("getJSURLStream", _getJSURLStream);
ExternalInterface.addCallback("getPlayerVersion", _getPlayerVersion);
ExternalInterface.addCallback("getAudioTrackList", _getAudioTrackList);
ExternalInterface.addCallback("getAudioTrackId", _getAudioTrackId);
};
private function _setupExternalCallers():void {
ExternalInterface.addCallback("playerLoad", _load);
ExternalInterface.addCallback("playerPlay", _play);
ExternalInterface.addCallback("playerPause", _pause);
ExternalInterface.addCallback("playerResume", _resume);
ExternalInterface.addCallback("playerSeek", _seek);
ExternalInterface.addCallback("playerStop", _stop);
ExternalInterface.addCallback("playerVolume", _volume);
ExternalInterface.addCallback("playerSetLevel", _setLevel);
ExternalInterface.addCallback("playerSmoothSetLevel", _smoothSetLevel);
ExternalInterface.addCallback("playerSetmaxBufferLength", _setmaxBufferLength);
ExternalInterface.addCallback("playerSetminBufferLength", _setminBufferLength);
ExternalInterface.addCallback("playerSetlowBufferLength", _setlowBufferLength);
ExternalInterface.addCallback("playerSetflushLiveURLCache", _setflushLiveURLCache);
ExternalInterface.addCallback("playerSetstartFromLevel", _setstartFromLevel);
ExternalInterface.addCallback("playerSetseekFromLevel", _setseekFromLevel);
ExternalInterface.addCallback("playerSetLogDebug", _setLogDebug);
ExternalInterface.addCallback("playerSetLogDebug2", _setLogDebug2);
ExternalInterface.addCallback("playerCapLeveltoStage", _setCapLeveltoStage);
ExternalInterface.addCallback("playerSetAudioTrack", _setAudioTrack);
ExternalInterface.addCallback("playerSetJSURLStream", _setJSURLStream);
};
private function _setupStage():void {
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState);
stage.addEventListener(Event.RESIZE, _onStageResize);
}
private function _setupSheet():void {
// Draw sheet for catching clicks
_sheet = new Sprite();
_sheet.graphics.beginFill(0x000000, 0);
_sheet.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
_sheet.addEventListener(MouseEvent.CLICK, _clickHandler);
_sheet.buttonMode = true;
addChild(_sheet);
}
/** Notify javascript the framework is ready. **/
protected function _pingJavascript() : void {
ExternalInterface.call("onHLSReady", ExternalInterface.objectID);
};
/** Forward events from the framework. **/
protected function _completeHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onComplete");
}
};
protected function _errorHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
var hlsError : HLSError = event.error;
ExternalInterface.call("onError", hlsError.code, hlsError.url, hlsError.msg);
}
};
protected function _fragmentHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onFragment", event.metrics.bandwidth, event.metrics.level, stage.stageWidth);
}
};
protected function _manifestHandler(event : HLSEvent) : void {
_duration = event.levels[_hls.startlevel].duration;
if (_autoLoad) {
_play();
}
if (ExternalInterface.available) {
ExternalInterface.call("onManifest", _duration);
}
};
protected function _mediaTimeHandler(event : HLSEvent) : void {
_duration = event.mediatime.duration;
_media_position = event.mediatime.position;
if (ExternalInterface.available) {
ExternalInterface.call("onPosition", event.mediatime.position, event.mediatime.duration, event.mediatime.live_sliding,event.mediatime.buffer, event.mediatime.program_date);
}
var videoWidth : int = _video ? _video.videoWidth : _stageVideo.videoWidth;
var videoHeight : int = _video ? _video.videoHeight : _stageVideo.videoHeight;
if (videoWidth && videoHeight) {
var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight;
if (changed) {
_videoHeight = videoHeight;
_videoWidth = videoWidth;
_resize();
if (ExternalInterface.available) {
ExternalInterface.call("onVideoSize", _videoWidth, _videoHeight);
}
}
}
};
protected function _stateHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onState", event.state);
}
};
protected function _levelSwitchHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onSwitch", event.level);
}
};
protected function _audioTracksListChange(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onAudioTracksListChange", _getAudioTrackList());
}
}
protected function _audioTrackChange(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onAudioTrackChange", event.audioTrack);
}
}
/** Javascript getters. **/
protected function _getLevel() : int {
return _hls.level;
};
protected function _getLevels() : Vector.<Level> {
return _hls.levels;
};
protected function _getAutoLevel() : Boolean {
return _hls.autolevel;
};
protected function _getMetrics() : Object {
return _hls.metrics;
};
protected function _getDuration() : Number {
return _duration;
};
protected function _getPosition() : Number {
return _hls.position;
};
protected function _getPlaybackState() : String {
return _hls.playbackState;
};
protected function _getSeekState() : String {
return _hls.seekState;
};
protected function _getType() : String {
return _hls.type;
};
protected function _getbufferLength() : Number {
return _hls.bufferLength;
};
protected function _getmaxBufferLength() : Number {
return HLSSettings.maxBufferLength;
};
protected function _getminBufferLength() : Number {
return HLSSettings.minBufferLength;
};
protected function _getlowBufferLength() : Number {
return HLSSettings.lowBufferLength;
};
protected function _getflushLiveURLCache() : Boolean {
return HLSSettings.flushLiveURLCache;
};
protected function _getstartFromLevel() : int {
return HLSSettings.startFromLevel;
};
protected function _getseekFromLevel() : int {
return HLSSettings.seekFromLevel;
};
protected function _getLogDebug() : Boolean {
return HLSSettings.logDebug;
};
protected function _getLogDebug2() : Boolean {
return HLSSettings.logDebug2;
};
protected function _getCapLeveltoStage() : Boolean {
return HLSSettings.capLevelToStage;
};
protected function _getJSURLStream() : Boolean {
return (_hls.URLstream is JSURLStream);
};
protected function _getPlayerVersion() : Number {
return 2;
};
protected function _getAudioTrackList() : Array {
var list : Array = [];
var vec : Vector.<HLSAudioTrack> = _hls.audioTracks;
for (var i : Object in vec) {
list.push(vec[i]);
}
return list;
};
protected function _getAudioTrackId() : int {
return _hls.audioTrack;
};
/** Javascript calls. **/
protected function _load(url : String) : void {
_hls.load(url);
};
protected function _play() : void {
_hls.stream.play();
};
protected function _pause() : void {
_hls.stream.pause();
};
protected function _resume() : void {
_hls.stream.resume();
};
protected function _seek(position : Number) : void {
_hls.stream.seek(position);
};
protected function _stop() : void {
_hls.stream.close();
};
protected function _volume(percent : Number) : void {
_hls.stream.soundTransform = new SoundTransform(percent / 100);
};
protected function _setLevel(level : int) : void {
_smoothSetLevel(level);
if (!isNaN(_media_position) && level != -1) {
_hls.stream.seek(_media_position);
}
};
protected function _smoothSetLevel(level : int) : void {
if (level != _hls.level) {
_hls.level = level;
}
};
protected function _setmaxBufferLength(new_len : Number) : void {
HLSSettings.maxBufferLength = new_len;
};
protected function _setminBufferLength(new_len : Number) : void {
HLSSettings.minBufferLength = new_len;
};
protected function _setlowBufferLength(new_len : Number) : void {
HLSSettings.lowBufferLength = new_len;
};
protected function _setflushLiveURLCache(flushLiveURLCache : Boolean) : void {
HLSSettings.flushLiveURLCache = flushLiveURLCache;
};
protected function _setstartFromLevel(startFromLevel : int) : void {
HLSSettings.startFromLevel = startFromLevel;
};
protected function _setseekFromLevel(seekFromLevel : int) : void {
HLSSettings.seekFromLevel = seekFromLevel;
};
protected function _setLogDebug(debug : Boolean) : void {
HLSSettings.logDebug = debug;
};
protected function _setLogDebug2(debug2 : Boolean) : void {
HLSSettings.logDebug2 = debug2;
};
protected function _setCapLeveltoStage(value : Boolean) : void {
HLSSettings.capLevelToStage = value;
};
protected function _setJSURLStream(jsURLstream : Boolean) : void {
if (jsURLstream) {
_hls.URLstream = JSURLStream as Class;
} else {
_hls.URLstream = URLStream as Class;
}
};
protected function _setAudioTrack(val : int) : void {
if (val == _hls.audioTrack) return;
_hls.audioTrack = val;
if (!isNaN(_media_position)) {
_hls.stream.seek(_media_position);
}
};
/** Mouse click handler. **/
protected function _clickHandler(event : MouseEvent) : void {
if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState == StageDisplayState.FULL_SCREEN) {
stage.displayState = StageDisplayState.NORMAL;
} else {
stage.displayState = StageDisplayState.FULL_SCREEN;
}
};
/** StageVideo detector. **/
protected function _onStageVideoState(event : StageVideoAvailabilityEvent) : void {
var available : Boolean = (event.availability == StageVideoAvailability.AVAILABLE);
_hls = new HLS();
_hls.stage = stage;
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler);
_hls.addEventListener(HLSEvent.ERROR, _errorHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler);
_hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
_hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTracksListChange);
_hls.addEventListener(HLSEvent.AUDIO_TRACK_CHANGE, _audioTrackChange);
if (available && stage.stageVideos.length > 0) {
_stageVideo = stage.stageVideos[0];
_stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
_stageVideo.attachNetStream(_hls.stream);
} else {
_video = new Video(stage.stageWidth, stage.stageHeight);
addChild(_video);
_video.smoothing = true;
_video.attachNetStream(_hls.stream);
}
stage.removeEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState);
var autoLoadUrl : String = root.loaderInfo.parameters.url as String;
if (autoLoadUrl != null) {
_autoLoad = true;
_load(autoLoadUrl);
}
};
protected function _onStageResize(event : Event) : void {
stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
_sheet.width = stage.stageWidth;
_sheet.height = stage.stageHeight;
_resize();
};
protected function _resize() : void {
var rect : Rectangle;
rect = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, stage.stageWidth, stage.stageHeight);
// resize video
if (_video) {
_video.width = rect.width;
_video.height = rect.height;
_video.x = rect.x;
_video.y = rect.y;
} else if (_stageVideo) {
_stageVideo.viewPort = rect;
}
}
}
}
|
package org.mangui.chromeless {
import flash.net.URLStream;
import org.mangui.hls.model.Level;
import org.mangui.hls.*;
import org.mangui.hls.utils.*;
import flash.display.*;
import flash.events.*;
import flash.external.ExternalInterface;
import flash.geom.Rectangle;
import flash.media.Video;
import flash.media.SoundTransform;
import flash.media.StageVideo;
import flash.media.StageVideoAvailability;
import flash.utils.setTimeout;
// import com.sociodox.theminer.*;
public class ChromelessPlayer extends Sprite {
/** reference to the framework. **/
protected var _hls : HLS;
/** Sheet to place on top of the video. **/
protected var _sheet : Sprite;
/** Reference to the stage video element. **/
protected var _stageVideo : StageVideo = null;
/** Reference to the video element. **/
protected var _video : Video = null;
/** Video size **/
protected var _videoWidth : int = 0;
protected var _videoHeight : int = 0;
/** current media position */
protected var _media_position : Number;
protected var _duration : Number;
/** URL autoload feature */
protected var _autoLoad : Boolean = false;
/** Initialization. **/
public function ChromelessPlayer() {
_setupStage();
_setupSheet();
_setupExternalGetters();
_setupExternalCallers();
setTimeout(_pingJavascript, 50);
};
protected function _setupExternalGetters():void {
ExternalInterface.addCallback("getLevel", _getLevel);
ExternalInterface.addCallback("getLevels", _getLevels);
ExternalInterface.addCallback("getAutoLevel", _getAutoLevel);
ExternalInterface.addCallback("getMetrics", _getMetrics);
ExternalInterface.addCallback("getDuration", _getDuration);
ExternalInterface.addCallback("getPosition", _getPosition);
ExternalInterface.addCallback("getPlaybackState", _getPlaybackState);
ExternalInterface.addCallback("getSeekState", _getSeekState);
ExternalInterface.addCallback("getType", _getType);
ExternalInterface.addCallback("getmaxBufferLength", _getmaxBufferLength);
ExternalInterface.addCallback("getminBufferLength", _getminBufferLength);
ExternalInterface.addCallback("getlowBufferLength", _getlowBufferLength);
ExternalInterface.addCallback("getbufferLength", _getbufferLength);
ExternalInterface.addCallback("getLogDebug", _getLogDebug);
ExternalInterface.addCallback("getLogDebug2", _getLogDebug2);
ExternalInterface.addCallback("getCapLeveltoStage", _getCapLeveltoStage);
ExternalInterface.addCallback("getflushLiveURLCache", _getflushLiveURLCache);
ExternalInterface.addCallback("getstartFromLevel", _getstartFromLevel);
ExternalInterface.addCallback("getseekFromLowestLevel", _getseekFromLevel);
ExternalInterface.addCallback("getJSURLStream", _getJSURLStream);
ExternalInterface.addCallback("getPlayerVersion", _getPlayerVersion);
ExternalInterface.addCallback("getAudioTrackList", _getAudioTrackList);
ExternalInterface.addCallback("getAudioTrackId", _getAudioTrackId);
};
protected function _setupExternalCallers():void {
ExternalInterface.addCallback("playerLoad", _load);
ExternalInterface.addCallback("playerPlay", _play);
ExternalInterface.addCallback("playerPause", _pause);
ExternalInterface.addCallback("playerResume", _resume);
ExternalInterface.addCallback("playerSeek", _seek);
ExternalInterface.addCallback("playerStop", _stop);
ExternalInterface.addCallback("playerVolume", _volume);
ExternalInterface.addCallback("playerSetLevel", _setLevel);
ExternalInterface.addCallback("playerSmoothSetLevel", _smoothSetLevel);
ExternalInterface.addCallback("playerSetmaxBufferLength", _setmaxBufferLength);
ExternalInterface.addCallback("playerSetminBufferLength", _setminBufferLength);
ExternalInterface.addCallback("playerSetlowBufferLength", _setlowBufferLength);
ExternalInterface.addCallback("playerSetflushLiveURLCache", _setflushLiveURLCache);
ExternalInterface.addCallback("playerSetstartFromLevel", _setstartFromLevel);
ExternalInterface.addCallback("playerSetseekFromLevel", _setseekFromLevel);
ExternalInterface.addCallback("playerSetLogDebug", _setLogDebug);
ExternalInterface.addCallback("playerSetLogDebug2", _setLogDebug2);
ExternalInterface.addCallback("playerCapLeveltoStage", _setCapLeveltoStage);
ExternalInterface.addCallback("playerSetAudioTrack", _setAudioTrack);
ExternalInterface.addCallback("playerSetJSURLStream", _setJSURLStream);
};
protected function _setupStage():void {
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState);
stage.addEventListener(Event.RESIZE, _onStageResize);
}
protected function _setupSheet():void {
// Draw sheet for catching clicks
_sheet = new Sprite();
_sheet.graphics.beginFill(0x000000, 0);
_sheet.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
_sheet.addEventListener(MouseEvent.CLICK, _clickHandler);
_sheet.buttonMode = true;
addChild(_sheet);
}
/** Notify javascript the framework is ready. **/
protected function _pingJavascript() : void {
ExternalInterface.call("onHLSReady", ExternalInterface.objectID);
};
/** Forward events from the framework. **/
protected function _completeHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onComplete");
}
};
protected function _errorHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
var hlsError : HLSError = event.error;
ExternalInterface.call("onError", hlsError.code, hlsError.url, hlsError.msg);
}
};
protected function _fragmentHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onFragment", event.metrics.bandwidth, event.metrics.level, stage.stageWidth);
}
};
protected function _manifestHandler(event : HLSEvent) : void {
_duration = event.levels[_hls.startlevel].duration;
if (_autoLoad) {
_play();
}
if (ExternalInterface.available) {
ExternalInterface.call("onManifest", _duration);
}
};
protected function _mediaTimeHandler(event : HLSEvent) : void {
_duration = event.mediatime.duration;
_media_position = event.mediatime.position;
if (ExternalInterface.available) {
ExternalInterface.call("onPosition", event.mediatime.position, event.mediatime.duration, event.mediatime.live_sliding,event.mediatime.buffer, event.mediatime.program_date);
}
var videoWidth : int = _video ? _video.videoWidth : _stageVideo.videoWidth;
var videoHeight : int = _video ? _video.videoHeight : _stageVideo.videoHeight;
if (videoWidth && videoHeight) {
var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight;
if (changed) {
_videoHeight = videoHeight;
_videoWidth = videoWidth;
_resize();
if (ExternalInterface.available) {
ExternalInterface.call("onVideoSize", _videoWidth, _videoHeight);
}
}
}
};
protected function _stateHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onState", event.state);
}
};
protected function _levelSwitchHandler(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onSwitch", event.level);
}
};
protected function _audioTracksListChange(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onAudioTracksListChange", _getAudioTrackList());
}
}
protected function _audioTrackChange(event : HLSEvent) : void {
if (ExternalInterface.available) {
ExternalInterface.call("onAudioTrackChange", event.audioTrack);
}
}
/** Javascript getters. **/
protected function _getLevel() : int {
return _hls.level;
};
protected function _getLevels() : Vector.<Level> {
return _hls.levels;
};
protected function _getAutoLevel() : Boolean {
return _hls.autolevel;
};
protected function _getMetrics() : Object {
return _hls.metrics;
};
protected function _getDuration() : Number {
return _duration;
};
protected function _getPosition() : Number {
return _hls.position;
};
protected function _getPlaybackState() : String {
return _hls.playbackState;
};
protected function _getSeekState() : String {
return _hls.seekState;
};
protected function _getType() : String {
return _hls.type;
};
protected function _getbufferLength() : Number {
return _hls.bufferLength;
};
protected function _getmaxBufferLength() : Number {
return HLSSettings.maxBufferLength;
};
protected function _getminBufferLength() : Number {
return HLSSettings.minBufferLength;
};
protected function _getlowBufferLength() : Number {
return HLSSettings.lowBufferLength;
};
protected function _getflushLiveURLCache() : Boolean {
return HLSSettings.flushLiveURLCache;
};
protected function _getstartFromLevel() : int {
return HLSSettings.startFromLevel;
};
protected function _getseekFromLevel() : int {
return HLSSettings.seekFromLevel;
};
protected function _getLogDebug() : Boolean {
return HLSSettings.logDebug;
};
protected function _getLogDebug2() : Boolean {
return HLSSettings.logDebug2;
};
protected function _getCapLeveltoStage() : Boolean {
return HLSSettings.capLevelToStage;
};
protected function _getJSURLStream() : Boolean {
return (_hls.URLstream is JSURLStream);
};
protected function _getPlayerVersion() : Number {
return 2;
};
protected function _getAudioTrackList() : Array {
var list : Array = [];
var vec : Vector.<HLSAudioTrack> = _hls.audioTracks;
for (var i : Object in vec) {
list.push(vec[i]);
}
return list;
};
protected function _getAudioTrackId() : int {
return _hls.audioTrack;
};
/** Javascript calls. **/
protected function _load(url : String) : void {
_hls.load(url);
};
protected function _play() : void {
_hls.stream.play();
};
protected function _pause() : void {
_hls.stream.pause();
};
protected function _resume() : void {
_hls.stream.resume();
};
protected function _seek(position : Number) : void {
_hls.stream.seek(position);
};
protected function _stop() : void {
_hls.stream.close();
};
protected function _volume(percent : Number) : void {
_hls.stream.soundTransform = new SoundTransform(percent / 100);
};
protected function _setLevel(level : int) : void {
_smoothSetLevel(level);
if (!isNaN(_media_position) && level != -1) {
_hls.stream.seek(_media_position);
}
};
protected function _smoothSetLevel(level : int) : void {
if (level != _hls.level) {
_hls.level = level;
}
};
protected function _setmaxBufferLength(new_len : Number) : void {
HLSSettings.maxBufferLength = new_len;
};
protected function _setminBufferLength(new_len : Number) : void {
HLSSettings.minBufferLength = new_len;
};
protected function _setlowBufferLength(new_len : Number) : void {
HLSSettings.lowBufferLength = new_len;
};
protected function _setflushLiveURLCache(flushLiveURLCache : Boolean) : void {
HLSSettings.flushLiveURLCache = flushLiveURLCache;
};
protected function _setstartFromLevel(startFromLevel : int) : void {
HLSSettings.startFromLevel = startFromLevel;
};
protected function _setseekFromLevel(seekFromLevel : int) : void {
HLSSettings.seekFromLevel = seekFromLevel;
};
protected function _setLogDebug(debug : Boolean) : void {
HLSSettings.logDebug = debug;
};
protected function _setLogDebug2(debug2 : Boolean) : void {
HLSSettings.logDebug2 = debug2;
};
protected function _setCapLeveltoStage(value : Boolean) : void {
HLSSettings.capLevelToStage = value;
};
protected function _setJSURLStream(jsURLstream : Boolean) : void {
if (jsURLstream) {
_hls.URLstream = JSURLStream as Class;
} else {
_hls.URLstream = URLStream as Class;
}
};
protected function _setAudioTrack(val : int) : void {
if (val == _hls.audioTrack) return;
_hls.audioTrack = val;
if (!isNaN(_media_position)) {
_hls.stream.seek(_media_position);
}
};
/** Mouse click handler. **/
protected function _clickHandler(event : MouseEvent) : void {
if (stage.displayState == StageDisplayState.FULL_SCREEN_INTERACTIVE || stage.displayState == StageDisplayState.FULL_SCREEN) {
stage.displayState = StageDisplayState.NORMAL;
} else {
stage.displayState = StageDisplayState.FULL_SCREEN;
}
};
/** StageVideo detector. **/
protected function _onStageVideoState(event : StageVideoAvailabilityEvent) : void {
var available : Boolean = (event.availability == StageVideoAvailability.AVAILABLE);
_hls = new HLS();
_hls.stage = stage;
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler);
_hls.addEventListener(HLSEvent.ERROR, _errorHandler);
_hls.addEventListener(HLSEvent.FRAGMENT_LOADED, _fragmentHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler);
_hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.addEventListener(HLSEvent.LEVEL_SWITCH, _levelSwitchHandler);
_hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, _audioTracksListChange);
_hls.addEventListener(HLSEvent.AUDIO_TRACK_CHANGE, _audioTrackChange);
if (available && stage.stageVideos.length > 0) {
_stageVideo = stage.stageVideos[0];
_stageVideo.viewPort = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
_stageVideo.attachNetStream(_hls.stream);
} else {
_video = new Video(stage.stageWidth, stage.stageHeight);
addChild(_video);
_video.smoothing = true;
_video.attachNetStream(_hls.stream);
}
stage.removeEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, _onStageVideoState);
var autoLoadUrl : String = root.loaderInfo.parameters.url as String;
if (autoLoadUrl != null) {
_autoLoad = true;
_load(autoLoadUrl);
}
};
protected function _onStageResize(event : Event) : void {
stage.fullScreenSourceRect = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
_sheet.width = stage.stageWidth;
_sheet.height = stage.stageHeight;
_resize();
};
protected function _resize() : void {
var rect : Rectangle;
rect = ScaleVideo.resizeRectangle(_videoWidth, _videoHeight, stage.stageWidth, stage.stageHeight);
// resize video
if (_video) {
_video.width = rect.width;
_video.height = rect.height;
_video.x = rect.x;
_video.y = rect.y;
} else if (_stageVideo) {
_stageVideo.viewPort = rect;
}
}
}
}
|
change setup functions to protected
|
ChromelessPlayer: change setup functions to protected
|
ActionScript
|
mpl-2.0
|
loungelogic/flashls,suuhas/flashls,School-Improvement-Network/flashls,dighan/flashls,Corey600/flashls,codex-corp/flashls,JulianPena/flashls,dighan/flashls,neilrackett/flashls,Peer5/flashls,NicolasSiver/flashls,ryanhefner/flashls,viktorot/flashls,Boxie5/flashls,fixedmachine/flashls,stevemayhew/flashls,Peer5/flashls,vidible/vdb-flashls,neilrackett/flashls,thdtjsdn/flashls,aevange/flashls,Peer5/flashls,School-Improvement-Network/flashls,tedconf/flashls,Peer5/flashls,jlacivita/flashls,ryanhefner/flashls,School-Improvement-Network/flashls,mangui/flashls,ryanhefner/flashls,ryanhefner/flashls,clappr/flashls,thdtjsdn/flashls,viktorot/flashls,suuhas/flashls,viktorot/flashls,codex-corp/flashls,Boxie5/flashls,aevange/flashls,hola/flashls,vidible/vdb-flashls,mangui/flashls,tedconf/flashls,JulianPena/flashls,loungelogic/flashls,clappr/flashls,suuhas/flashls,Corey600/flashls,NicolasSiver/flashls,stevemayhew/flashls,suuhas/flashls,hola/flashls,aevange/flashls,stevemayhew/flashls,aevange/flashls,stevemayhew/flashls,fixedmachine/flashls,jlacivita/flashls
|
96fce057c2e44fd45542d781dbcd4dd04b6d7234
|
src/org/mangui/HLS/muxing/AVC.as
|
src/org/mangui/HLS/muxing/AVC.as
|
package org.mangui.HLS.muxing {
import flash.utils.ByteArray;
import org.mangui.HLS.utils.Log;
/** Constants and utilities for the H264 video format. **/
public class AVC {
/** H264 NAL unit names. **/
private static const NAMES:Array = [
'Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data' // 12
];
/** H264 profiles. **/
private static const PROFILES:Object = {
'66': 'H264 Baseline',
'77': 'H264 Main',
'100': 'H264 High'
};
/** Get Avcc header from AVC stream
See ISO 14496-15, 5.2.4.1 for the description of AVCDecoderConfigurationRecord
**/
public static function getAVCC(nalu:ByteArray,position:Number=0):ByteArray {
// Find SPS and PPS units in AVC stream.
var units:Vector.<VideoFrame> = AVC.getNALU(nalu,position);
var sps:Number = -1;
var pps:Number = -1;
for(var i:Number = 0; i< units.length; i++) {
if(units[i].type == 7 && sps == -1) {
sps = i;
} else if (units[i].type == 8 && pps == -1) {
pps = i;
}
}
// Throw errors if units not found.
if(sps == -1) {
throw new Error("No SPS NAL unit found in this stream.");
} else if (pps == -1) {
throw new Error("No PPS NAL unit found in this stream.");
}
// Write startbyte
var avcc:ByteArray = new ByteArray();
avcc.writeByte(0x01);
// Write profile, compatibility and level.
avcc.writeBytes(nalu,units[sps].start+1, 3);
// reserved (6 bits), NALU length size - 1 (2 bits)
avcc.writeByte(0xFC | 3);
// reserved (3 bits), num of SPS (5 bits)
avcc.writeByte(0xE0 | 1);
// 2 bytes for length of SPS
avcc.writeShort(units[sps].length);
// data of SPS
avcc.writeBytes(nalu,units[sps].start,units[sps].length);
// Number of PPS
avcc.writeByte(0x01);
// 2 bytes for length of PPS
avcc.writeShort(units[pps].length);
// data of PPS
avcc.writeBytes(nalu,units[pps].start,units[pps].length);
// Grab profile/level
avcc.position = 1;
var prf:Number = avcc.readByte();
avcc.position = 3;
var lvl:Number = avcc.readByte();
Log.debug("AVC: "+PROFILES[prf]+' level '+lvl);
avcc.position = 0;
return avcc;
};
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu:ByteArray,position:Number=0):Vector.<VideoFrame> {
var units:Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start:Number;
var unit_type:Number;
var unit_header:Number;
// Loop through data to find NAL startcodes.
var window:uint = 0;
nalu.position = position;
while(nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if(unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if(unit_type == 1 || unit_type == 5) { break; }
// Match three-byte startcodes
} else if((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if(unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if(unit_type == 1 || unit_type == 5) { break; }
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if(unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
if(Log.LOG_DEBUG2_ENABLED) {
if(units.length) {
var txt:String = "AVC: ";
for(var i:Number=0; i<units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug(txt.substr(0,txt.length-2) + " slices");
} else {
Log.debug('AVC: no NALU slices found');
}
}
nalu.position = position;
return units;
};
}
}
|
package org.mangui.HLS.muxing {
import flash.utils.ByteArray;
import org.mangui.HLS.utils.Log;
/** Constants and utilities for the H264 video format. **/
public class AVC {
/** H264 NAL unit names. **/
private static const NAMES:Array = [
'Unspecified', // 0
'NDR', // 1
'Partition A', // 2
'Partition B', // 3
'Partition C', // 4
'IDR', // 5
'SEI', // 6
'SPS', // 7
'PPS', // 8
'AUD', // 9
'End of Sequence', // 10
'End of Stream', // 11
'Filler Data' // 12
];
/** H264 profiles. **/
private static const PROFILES:Object = {
'66': 'H264 Baseline',
'77': 'H264 Main',
'100': 'H264 High'
};
/** Get Avcc header from AVC stream
See ISO 14496-15, 5.2.4.1 for the description of AVCDecoderConfigurationRecord
**/
public static function getAVCC(nalu:ByteArray,position:Number=0):ByteArray {
// Find SPS and PPS units in AVC stream.
var units:Vector.<VideoFrame> = AVC.getNALU(nalu,position);
var sps:Number = -1;
var pps:Number = -1;
for(var i:Number = 0; i< units.length; i++) {
if(units[i].type == 7 && sps == -1) {
sps = i;
} else if (units[i].type == 8 && pps == -1) {
pps = i;
}
}
// Throw errors if units not found.
if(sps == -1) {
throw new Error("No SPS NAL unit found in this stream.");
} else if (pps == -1) {
throw new Error("No PPS NAL unit found in this stream.");
}
// Write startbyte
var avcc:ByteArray = new ByteArray();
avcc.writeByte(0x01);
// Write profile, compatibility and level.
avcc.writeBytes(nalu,units[sps].start+1, 3);
// reserved (6 bits), NALU length size - 1 (2 bits)
avcc.writeByte(0xFC | 3);
// reserved (3 bits), num of SPS (5 bits)
avcc.writeByte(0xE0 | 1);
// 2 bytes for length of SPS
avcc.writeShort(units[sps].length);
// data of SPS
avcc.writeBytes(nalu,units[sps].start,units[sps].length);
// Number of PPS
avcc.writeByte(0x01);
// 2 bytes for length of PPS
avcc.writeShort(units[pps].length);
// data of PPS
avcc.writeBytes(nalu,units[pps].start,units[pps].length);
// Grab profile/level
avcc.position = 1;
var prf:Number = avcc.readByte();
avcc.position = 3;
var lvl:Number = avcc.readByte();
Log.debug("AVC: "+PROFILES[prf]+' level '+lvl);
avcc.position = 0;
return avcc;
};
/** Return an array with NAL delimiter indexes. **/
public static function getNALU(nalu:ByteArray,position:Number=0):Vector.<VideoFrame> {
var units:Vector.<VideoFrame> = new Vector.<VideoFrame>();
var unit_start:Number;
var unit_type:Number;
var unit_header:Number;
// Loop through data to find NAL startcodes.
var window:uint = 0;
nalu.position = position;
while(nalu.bytesAvailable > 4) {
window = nalu.readUnsignedInt();
// Match four-byte startcodes
if((window & 0xFFFFFFFF) == 0x01) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if(unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
unit_header = 4;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if(unit_type == 1 || unit_type == 5) { break; }
// Match three-byte startcodes
} else if((window & 0xFFFFFF00) == 0x100) {
// push previous NAL unit if new start delimiter found, dont push unit with type = 0
if(unit_start && unit_type) {
units.push(new VideoFrame(unit_header, nalu.position - 4 - unit_start, unit_start, unit_type));
}
nalu.position--;
unit_header = 3;
unit_start = nalu.position;
unit_type = nalu.readByte() & 0x1F;
// NDR or IDR NAL unit
if(unit_type == 1 || unit_type == 5) { break; }
} else {
nalu.position -= 3;
}
}
// Append the last NAL to the array.
if(unit_start) {
units.push(new VideoFrame(unit_header, nalu.length - unit_start, unit_start, unit_type));
}
// Reset position and return results.
if(Log.LOG_DEBUG2_ENABLED) {
if(units.length) {
var txt:String = "AVC: ";
for(var i:Number=0; i<units.length; i++) {
txt += NAMES[units[i].type] + ", ";
}
Log.debug2(txt.substr(0,txt.length-2) + " slices");
} else {
Log.debug2('AVC: no NALU slices found');
}
}
nalu.position = position;
return units;
};
}
}
|
adjust log level
|
adjust log level
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
0e3eab2630ae7ae9c3ac2f898848464bd2dda15f
|
src/aerys/minko/type/math/Vector4.as
|
src/aerys/minko/type/math/Vector4.as
|
package aerys.minko.type.math
{
import aerys.minko.ns.minko_math;
import aerys.minko.type.Factory;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.IWatchable;
import flash.geom.Vector3D;
public class Vector4 implements IWatchable
{
use namespace minko_math;
public static const X_AXIS : Vector4 = new Vector4(1., 0., 0.);
public static const Y_AXIS : Vector4 = new Vector4(0., 1., 0.);
public static const Z_AXIS : Vector4 = new Vector4(0., 0., 1.);
public static const ZERO : Vector4 = new Vector4(0., 0., 0., 0.);
public static const ONE : Vector4 = new Vector4(1., 1., 1., 1.);
private static const FACTORY : Factory = Factory.getFactory(Vector4);
private static const UPDATE_NONE : uint = 0;
private static const UPDATE_LENGTH : uint = 1;
private static const UPDATE_LENGTH_SQ : uint = 2;
private static const UPDATE_ALL : uint = UPDATE_LENGTH | UPDATE_LENGTH_SQ;
private static const DATA_DESCRIPTOR : Object = {
'x' : 'x',
'y' : 'y',
'z' : 'z',
'w' : 'w'
}
minko_math var _vector : Vector3D = new Vector3D();
private var _update : uint = 0;
private var _length : Number = 0.;
private var _lengthSq : Number = 0.;
private var _locked : Boolean = false;
private var _changed : Signal = new Signal('Vector4.changed');
public function get x() : Number
{
return _vector.x;
}
public function set x(value : Number) : void
{
if (value != _vector.x)
{
_vector.x = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this, "x");
}
}
public function get y() : Number
{
return _vector.y;
}
public function set y(value : Number) : void
{
if (value != _vector.y)
{
_vector.y = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this, "y");
}
}
public function get z() : Number
{
return _vector.z;
}
public function set z(value : Number) : void
{
if (value != _vector.z)
{
_vector.z = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this, "z");
}
}
public function get w() : Number
{
return _vector.w;
}
public function set w(value : Number) : void
{
if (value != _vector.w)
{
_vector.w = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this, "w");
}
}
public function get lengthSquared() : Number
{
if (_update & UPDATE_LENGTH_SQ)
{
_update ^= UPDATE_LENGTH_SQ;
_lengthSq = _vector.x * _vector.x + _vector.y * _vector.y
+ _vector.z * _vector.z;
}
return _lengthSq;
}
public function get length() : Number
{
if (_update & UPDATE_LENGTH)
{
_update ^= UPDATE_LENGTH;
_length = Math.sqrt(lengthSquared);
}
return _length;
}
public function get locked() : Boolean
{
return _locked;
}
public function get changed() : Signal
{
return _changed;
}
public function Vector4(x : Number = 0.,
y : Number = 0.,
z : Number = 0.,
w : Number = 1)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
}
public static function add(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out = copy(u, out);
return out.add(v);
}
public static function subtract(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out = copy(u, out);
return out.subtract(v);
}
public static function dotProduct(u : Vector4, v : Vector4) : Number
{
return u._vector.dotProduct(v._vector);
}
public static function crossProduct(u : Vector4, v : Vector4) : Vector4
{
return new Vector4(
u._vector.y * v._vector.z - v._vector.y * u._vector.z,
u._vector.z * v._vector.x - v._vector.z * u._vector.x,
u._vector.x * v._vector.y - v._vector.x * u._vector.y
);
}
public function compareTo(v : Vector4, allFour : Boolean = false) : Boolean
{
return _vector.x == v._vector.x
&& _vector.y == v._vector.y
&& _vector.z == v._vector.z
&& (!allFour || (_vector.w == v._vector.w));
}
public static function distance(u : Vector4, v : Vector4) : Number
{
return Vector3D.distance(u._vector, v._vector);
}
public static function copy(source : Vector4, target : Vector4 = null) : Vector4
{
target ||= FACTORY.create() as Vector4;
target.set(source.x, source.y, source.z, source.w);
return target;
}
public function add(vector : Vector4) : Vector4
{
_vector.incrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this, null);
return this;
}
public function subtract(vector : Vector4) : Vector4
{
_vector.decrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this, null);
return this;
}
public function scaleBy(scale : Number) : Vector4
{
_vector.scaleBy(scale);
_update = UPDATE_ALL;
_changed.execute(this, null);
return this;
}
public function project() : Vector4
{
_vector.x /= _vector.w;
_vector.y /= _vector.w;
_vector.z /= _vector.w;
_update = UPDATE_ALL;
_changed.execute(this, null);
return this;
}
public function normalize() : Vector4
{
var l : Number = length;
if (l != 0.)
{
_vector.x /= l;
_vector.y /= l;
_vector.z /= l;
_length = 1.;
_lengthSq = 1.;
_update = UPDATE_NONE;
_changed.execute(this, null);
}
return this;
}
public function crossProduct(vector : Vector4) : Vector4
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
_vector.x = y * vector._vector.z - vector._vector.y * z;
_vector.y = z * vector._vector.x - vector._vector.z * x;
_vector.z = x * vector._vector.y - vector._vector.x * y;
_update = UPDATE_ALL;
_changed.execute(this, null);
return this;
}
public function getVector3D() : Vector3D
{
return _vector.clone();
}
public function set(x : Number,
y : Number,
z : Number,
w : Number = 1.) : Vector4
{
if (x != _vector.x || y != _vector.y || z != _vector.z || w != _vector.w)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this, null);
}
return this;
}
public function toString() : String
{
return "(" + _vector.x + ", " + _vector.y + ", " + _vector.z + ", "
+ _vector.w + ")";
}
public static function scale(v : Vector4, s : Number, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out._vector.x = v._vector.x;
out._vector.y = v._vector.y;
out._vector.z = v._vector.z;
out._vector.w = v._vector.w;
return out;
}
public function toVector3D(out : Vector3D = null) : Vector3D
{
if (!out)
return _vector.clone();
out.x = _vector.x;
out.y = _vector.y;
out.z = _vector.z;
out.w = _vector.w;
return out;
}
public static function normalize(v : Vector4, out : Vector4 = null) : Vector4
{
out = copy(v, out);
return out.normalize();
}
public function lock() : void
{
_locked = true;
}
public function unlock() : void
{
_locked = false;
_changed.execute(this, null);
}
}
}
|
package aerys.minko.type.math
{
import aerys.minko.ns.minko_math;
import aerys.minko.type.Factory;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.IWatchable;
import flash.geom.Vector3D;
public class Vector4 implements IWatchable
{
use namespace minko_math;
public static const X_AXIS : Vector4 = new Vector4(1., 0., 0.);
public static const Y_AXIS : Vector4 = new Vector4(0., 1., 0.);
public static const Z_AXIS : Vector4 = new Vector4(0., 0., 1.);
public static const ZERO : Vector4 = new Vector4(0., 0., 0., 0.);
public static const ONE : Vector4 = new Vector4(1., 1., 1., 1.);
private static const FACTORY : Factory = Factory.getFactory(Vector4);
private static const UPDATE_NONE : uint = 0;
private static const UPDATE_LENGTH : uint = 1;
private static const UPDATE_LENGTH_SQ : uint = 2;
private static const UPDATE_ALL : uint = UPDATE_LENGTH | UPDATE_LENGTH_SQ;
private static const DATA_DESCRIPTOR : Object = {
'x' : 'x',
'y' : 'y',
'z' : 'z',
'w' : 'w'
}
minko_math var _vector : Vector3D = new Vector3D();
private var _update : uint = 0;
private var _length : Number = 0.;
private var _lengthSq : Number = 0.;
private var _locked : Boolean = false;
private var _changed : Signal = new Signal('Vector4.changed');
public function get x() : Number
{
return _vector.x;
}
public function set x(value : Number) : void
{
if (value != _vector.x)
{
_vector.x = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this, "x");
}
}
public function get y() : Number
{
return _vector.y;
}
public function set y(value : Number) : void
{
if (value != _vector.y)
{
_vector.y = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this, "y");
}
}
public function get z() : Number
{
return _vector.z;
}
public function set z(value : Number) : void
{
if (value != _vector.z)
{
_vector.z = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this, "z");
}
}
public function get w() : Number
{
return _vector.w;
}
public function set w(value : Number) : void
{
if (value != _vector.w)
{
_vector.w = value;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this, "w");
}
}
public function get lengthSquared() : Number
{
if (_update & UPDATE_LENGTH_SQ)
{
_update ^= UPDATE_LENGTH_SQ;
_lengthSq = _vector.x * _vector.x + _vector.y * _vector.y
+ _vector.z * _vector.z;
}
return _lengthSq;
}
public function get length() : Number
{
if (_update & UPDATE_LENGTH)
{
_update ^= UPDATE_LENGTH;
_length = Math.sqrt(lengthSquared);
}
return _length;
}
public function get locked() : Boolean
{
return _locked;
}
public function get changed() : Signal
{
return _changed;
}
public function Vector4(x : Number = 0.,
y : Number = 0.,
z : Number = 0.,
w : Number = 1)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
}
public static function add(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out = copy(u, out);
return out.add(v);
}
public static function subtract(u : Vector4,
v : Vector4,
out : Vector4 = null) : Vector4
{
out = copy(u, out);
return out.subtract(v);
}
public static function dotProduct(u : Vector4, v : Vector4) : Number
{
return u._vector.dotProduct(v._vector);
}
public static function crossProduct(u : Vector4, v : Vector4) : Vector4
{
return new Vector4(
u._vector.y * v._vector.z - v._vector.y * u._vector.z,
u._vector.z * v._vector.x - v._vector.z * u._vector.x,
u._vector.x * v._vector.y - v._vector.x * u._vector.y
);
}
public function compareTo(v : Vector4, allFour : Boolean = false) : Boolean
{
return _vector.x == v._vector.x
&& _vector.y == v._vector.y
&& _vector.z == v._vector.z
&& (!allFour || (_vector.w == v._vector.w));
}
public static function distance(u : Vector4, v : Vector4) : Number
{
return Vector3D.distance(u._vector, v._vector);
}
public static function copy(source : Vector4, target : Vector4 = null) : Vector4
{
target ||= FACTORY.create() as Vector4;
target.set(source.x, source.y, source.z, source.w);
return target;
}
public function add(vector : Vector4) : Vector4
{
_vector.incrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this, null);
return this;
}
public function subtract(vector : Vector4) : Vector4
{
_vector.decrementBy(vector._vector);
_update = UPDATE_ALL;
_changed.execute(this, null);
return this;
}
public function scaleBy(scale : Number) : Vector4
{
_vector.scaleBy(scale);
_update = UPDATE_ALL;
_changed.execute(this, null);
return this;
}
public function project() : Vector4
{
_vector.x /= _vector.w;
_vector.y /= _vector.w;
_vector.z /= _vector.w;
_update = UPDATE_ALL;
_changed.execute(this, null);
return this;
}
public function normalize() : Vector4
{
var l : Number = length;
if (l != 0.)
{
_vector.x /= l;
_vector.y /= l;
_vector.z /= l;
_length = 1.;
_lengthSq = 1.;
_update = UPDATE_NONE;
_changed.execute(this, null);
}
return this;
}
public function crossProduct(vector : Vector4) : Vector4
{
var x : Number = _vector.x;
var y : Number = _vector.y;
var z : Number = _vector.z;
_vector.x = y * vector._vector.z - vector._vector.y * z;
_vector.y = z * vector._vector.x - vector._vector.z * x;
_vector.z = x * vector._vector.y - vector._vector.x * y;
_update = UPDATE_ALL;
_changed.execute(this, null);
return this;
}
public function getVector3D() : Vector3D
{
return _vector.clone();
}
public function set(x : Number,
y : Number,
z : Number,
w : Number = 1.) : Vector4
{
if (x != _vector.x || y != _vector.y || z != _vector.z || w != _vector.w)
{
_vector.x = x;
_vector.y = y;
_vector.z = z;
_vector.w = w;
_update = UPDATE_ALL;
if (!_locked)
_changed.execute(this, null);
}
return this;
}
public function toString() : String
{
return "(" + _vector.x + ", " + _vector.y + ", " + _vector.z + ", "
+ _vector.w + ")";
}
public static function scale(v : Vector4, s : Number, out : Vector4 = null) : Vector4
{
out ||= FACTORY.create() as Vector4;
out._vector.x = v._vector.x;
out._vector.y = v._vector.y;
out._vector.z = v._vector.z;
out._vector.w = v._vector.w;
return out;
}
public function toVector3D(out : Vector3D = null) : Vector3D
{
if (!out)
return _vector.clone();
out.x = _vector.x;
out.y = _vector.y;
out.z = _vector.z;
out.w = _vector.w;
return out;
}
public static function normalize(v : Vector4, out : Vector4 = null) : Vector4
{
out = copy(v, out);
return out.normalize();
}
public function lock() : void
{
_locked = true;
}
public function unlock() : void
{
_locked = false;
_changed.execute(this, null);
}
public function clone() : Vector4
{
return new Vector4(_vector.x, _vector.y, _vector.z, _vector.w);
}
}
}
|
Add clone on vector4
|
Add clone on vector4
|
ActionScript
|
mit
|
aerys/minko-as3
|
07d80765474aa34ad2a06bef517da81c1dfc201b
|
unittests/TestDisjunctiveSyllogism.as
|
unittests/TestDisjunctiveSyllogism.as
|
package unittests
{
public class TestDisjunctiveSyllogism
{
import logic.DisjunctiveSyllogism;
import mx.controls.Alert;
import org.flexunit.Assert;
private var djs:DisjunctiveSyllogism;
private var djsReverse:DisjunctiveSyllogism;
[Before]
public function setUp():void
{
/*
* reversePos apparently differentiates between Basic Claim and Reason 1.
* ~~ Printing all reasons in NotPFalse
* It is not the case that Reason 1
* Reason 2
* ~~ Printing all reasons in Reverse NotPFalse
* It is not the case that Basic Claim
* Reason 2
*/
//DisjunctiveSyllogism(claimText:String, reasonText:Array, reversePos:Boolean,inferenceText:String="", inferencePresent:Boolean=false)
djsReverse = new DisjunctiveSyllogism("Basic Claim", ["Reason 1", "Reason 2"], true, "Either Foo or Bar, and Baz unless Quux", false);
djs = new DisjunctiveSyllogism("Basic Claim", ["Reason 1", "Reason 2"], false, "Either Foo or Bar, and Baz unless Quux", false);
}
[After]
public function tearDown():void
{
}
[BeforeClass]
public static function setUpBeforeClass():void
{
}
[AfterClass]
public static function tearDownAfterClass():void
{
}
//Copied from the superclass tests
[Test]
public function testConstructorClaim():void{
Assert.assertEquals("Basic Claim", djs.getClaim());
}
[Test]
public function testConstructorReason():void{
Assert.assertEquals("Reason 1", djs.getReason()[0]);
}
//New tests for this subclass's particular functions
//Not asserting anything because it's currently pointless
[Test(order=1)]
public function testNotPTrue():void{
djs.notP(true);
trace("~~ Printing all reasons in NotPTrue");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.notP(true);
trace("~~ Printing all reasons in Reverse NotPTrue");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=2)]
public function testNotPFalse():void{
djs.notP(false);
trace("~~ Printing all reasons in NotPFalse");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.notP(false);
trace("~~ Printing all reasons in Reverse NotPFalse");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=3)]
public function testNotQTrue():void{
djs.notQ(true);
trace("~~ Printing all reasons in NotQTrue");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.notQ(true);
trace("~~ Printing all reasons in Reverse NotQTrue");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=4)]
public function testNotQFalse():void{
djs.notQ(false);
trace("~~ Printing all reasons in NotQFalse");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.notQ(false);
trace("~~ Printing all reasons in Reverse NotQFalse");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=5)]
public function testAlternatePTrue():void{
djs.alternateP(true);
trace("~~ Printing all reasons in AlternatePTrue");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.alternateP(true);
trace("~~ Printing all reasons in Reverse AlternatePTrue");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=6)]
public function testAlternatePFalse():void{
djs.alternateP(false);
trace("~~ Printing all reasons in AlternatePFalse");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.alternateP(false);
trace("~~ Printing all reasons in Reverse AlternatePFalse");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=7)]
public function testAlternateQTrue():void{
djs.alternateQ(true);
trace("~~ Printing all reasons in AlternateQTrue");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.alternateQ(true);
trace("~~ Printing all reasons in Reverse AlternateQTrue");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=8)]
public function testAlternateQFalse():void{
djs.alternateQ(false);
trace("~~ Printing all reasons in AlternateQFalse");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.alternateQ(false);
trace("~~ Printing all reasons in Reverse AlternateQFalse");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
}
}
|
package unittests
{
public class TestDisjunctiveSyllogism
{
import logic.DisjunctiveSyllogism;
import org.flexunit.Assert;
private var djs:DisjunctiveSyllogism;
private var djsReverse:DisjunctiveSyllogism;
[Before]
public function setUp():void
{
/*
* reversePos apparently differentiates between Basic Claim and Reason 1.
* ~~ Printing all reasons in NotPFalse
* It is not the case that Reason 1
* Reason 2
* ~~ Printing all reasons in Reverse NotPFalse
* It is not the case that Basic Claim
* Reason 2
*/
//DisjunctiveSyllogism(claimText:String, reasonText:Array, reversePos:Boolean,inferenceText:String="", inferencePresent:Boolean=false)
djsReverse = new DisjunctiveSyllogism("Basic Claim", ["Reason 1", "Reason 2"], true, "Either Foo or Bar, and Baz unless Quux", false);
djs = new DisjunctiveSyllogism("Basic Claim", ["Reason 1", "Reason 2"], false, "Either Foo or Bar, and Baz unless Quux", false);
}
[After]
public function tearDown():void
{
}
[BeforeClass]
public static function setUpBeforeClass():void
{
}
[AfterClass]
public static function tearDownAfterClass():void
{
}
//Copied from the superclass tests
[Test]
public function testConstructorClaim():void{
Assert.assertEquals("Basic Claim", djs.getClaim());
}
[Test]
public function testConstructorReason():void{
Assert.assertEquals("Reason 1", djs.getReason()[0]);
}
//New tests for this subclass's particular functions
//Not asserting anything because it's currently pointless
[Test(order=1)]
public function testNotPTrue():void{
djs.notP(true);
trace("~~ Printing all reasons in NotPTrue");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.notP(true);
trace("~~ Printing all reasons in Reverse NotPTrue");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=2)]
public function testNotPFalse():void{
djs.notP(false);
trace("~~ Printing all reasons in NotPFalse");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.notP(false);
trace("~~ Printing all reasons in Reverse NotPFalse");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=3)]
public function testNotQTrue():void{
djs.notQ(true);
trace("~~ Printing all reasons in NotQTrue");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.notQ(true);
trace("~~ Printing all reasons in Reverse NotQTrue");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=4)]
public function testNotQFalse():void{
djs.notQ(false);
trace("~~ Printing all reasons in NotQFalse");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.notQ(false);
trace("~~ Printing all reasons in Reverse NotQFalse");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=5)]
public function testAlternatePTrue():void{
djs.alternateP(true);
trace("~~ Printing all reasons in AlternatePTrue");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.alternateP(true);
trace("~~ Printing all reasons in Reverse AlternatePTrue");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=6)]
public function testAlternatePFalse():void{
djs.alternateP(false);
trace("~~ Printing all reasons in AlternatePFalse");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.alternateP(false);
trace("~~ Printing all reasons in Reverse AlternatePFalse");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=7)]
public function testAlternateQTrue():void{
djs.alternateQ(true);
trace("~~ Printing all reasons in AlternateQTrue");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.alternateQ(true);
trace("~~ Printing all reasons in Reverse AlternateQTrue");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
[Test(order=8)]
public function testAlternateQFalse():void{
djs.alternateQ(false);
trace("~~ Printing all reasons in AlternateQFalse");
for each (var reason:String in djs.getReason()){
trace(reason);
}
djsReverse.alternateQ(false);
trace("~~ Printing all reasons in Reverse AlternateQFalse");
for each (reason in djsReverse.getReason()){
trace(reason);
}
}
}
}
|
Remove needless import.
|
Remove needless import.
|
ActionScript
|
agpl-3.0
|
mbjornas3/AGORA,MichaelHoffmann/AGORA,mbjornas3/AGORA,MichaelHoffmann/AGORA,MichaelHoffmann/AGORA
|
2badaec232dd582d5187f1136a4be2173f165e38
|
src/org/robotlegs/base/CommandMap.as
|
src/org/robotlegs/base/CommandMap.as
|
/*
* Copyright (c) 2009 the original author or authors
*
* Permission is hereby granted to use, modify, and distribute this file
* in accordance with the terms of the license agreement accompanying it.
*/
package org.robotlegs.base
{
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.utils.Dictionary;
import flash.utils.describeType;
import org.robotlegs.core.ICommandMap;
import org.robotlegs.core.IInjector;
import org.robotlegs.core.IReflector;
/**
* An abstract <code>ICommandMap</code> implementation
*/
public class CommandMap implements ICommandMap
{
/**
* The <code>IEventDispatcher</code> to listen to
*/
protected var eventDispatcher:IEventDispatcher;
/**
* The <code>IInjector</code> to inject with
*/
protected var injector:IInjector;
/**
* The <code>IReflector</code> to reflect with
*/
protected var reflector:IReflector;
/**
* Internal
*
* TODO: This needs to be documented
*/
protected var eventTypeMap:Dictionary;
/**
* Internal
*
* Collection of command classes that have been verified to implement an <code>execute</code> method
*/
protected var verifiedCommandClasses:Dictionary;
protected var detainedCommands:Dictionary;
//---------------------------------------------------------------------
// Constructor
//---------------------------------------------------------------------
/**
* Creates a new <code>CommandMap</code> object
*
* @param eventDispatcher The <code>IEventDispatcher</code> to listen to
* @param injector An <code>IInjector</code> to use for this context
* @param reflector An <code>IReflector</code> to use for this context
*/
public function CommandMap(eventDispatcher:IEventDispatcher, injector:IInjector, reflector:IReflector)
{
this.eventDispatcher = eventDispatcher;
this.injector = injector;
this.reflector = reflector;
this.eventTypeMap = new Dictionary(false);
this.verifiedCommandClasses = new Dictionary(false);
this.detainedCommands = new Dictionary(false);
}
//---------------------------------------------------------------------
// API
//---------------------------------------------------------------------
/**
* @inheritDoc
*/
public function mapEvent(eventType:String, commandClass:Class, eventClass:Class = null, oneshot:Boolean = false):void
{
verifyCommandClass(commandClass);
eventClass = eventClass || Event;
var eventClassMap:Dictionary = eventTypeMap[eventType] ||= new Dictionary(false);
var callbacksByCommandClass:Dictionary = eventClassMap[eventClass] ||= new Dictionary(false);
if (callbacksByCommandClass[commandClass] != null)
{
throw new ContextError(ContextError.E_COMMANDMAP_OVR + ' - eventType (' + eventType + ') and Command (' + commandClass + ')');
}
var callback:Function = function(event:Event):void
{
routeEventToCommand(event, commandClass, oneshot, eventClass);
};
eventDispatcher.addEventListener(eventType, callback, false, 0, true);
callbacksByCommandClass[commandClass] = callback;
}
/**
* @inheritDoc
*/
public function unmapEvent(eventType:String, commandClass:Class, eventClass:Class = null):void
{
var eventClassMap:Dictionary = eventTypeMap[eventType];
if (eventClassMap == null) return;
var callbacksByCommandClass:Dictionary = eventClassMap[eventClass || Event];
if (callbacksByCommandClass == null) return;
var callback:Function = callbacksByCommandClass[commandClass];
if (callback == null) return;
eventDispatcher.removeEventListener(eventType, callback, false);
delete callbacksByCommandClass[commandClass];
}
/**
* @inheritDoc
*/
public function unmapEvents():void
{
for (var eventType:String in eventTypeMap)
{
var eventClassMap:Dictionary = eventTypeMap[eventType];
for each (var callbacksByCommandClass:Dictionary in eventClassMap)
{
for each ( var callback:Function in callbacksByCommandClass)
{
eventDispatcher.removeEventListener(eventType, callback, false);
}
}
}
eventTypeMap = new Dictionary(false);
}
/**
* @inheritDoc
*/
public function hasEventCommand(eventType:String, commandClass:Class, eventClass:Class = null):Boolean
{
var eventClassMap:Dictionary = eventTypeMap[eventType];
if (eventClassMap == null) return false;
var callbacksByCommandClass:Dictionary = eventClassMap[eventClass || Event];
if (callbacksByCommandClass == null) return false;
return callbacksByCommandClass[commandClass] != null;
}
/**
* @inheritDoc
*/
public function execute(commandClass:Class, payload:Object = null, payloadClass:Class = null, named:String = ''):void
{
verifyCommandClass(commandClass);
if (payload != null || payloadClass != null)
{
payloadClass ||= reflector.getClass(payload);
if (payload is Event && payloadClass != Event)
injector.mapValue(Event, payload, named);
injector.mapValue(payloadClass, payload, named);
}
var command:Object = injector.instantiate(commandClass);
if (payload !== null || payloadClass != null)
{
if (payload is Event && payloadClass != Event)
injector.unmap(Event, named);
injector.unmap(payloadClass, named);
}
command.execute();
}
/**
* @inheritDoc
*/
public function detain(command:Object):void
{
detainedCommands[command] = true;
}
/**
* @inheritDoc
*/
public function release(command:Object):void
{
if (detainedCommands[command])
delete detainedCommands[command];
}
//---------------------------------------------------------------------
// Internal
//---------------------------------------------------------------------
/**
* @throws org.robotlegs.base::ContextError
*/
protected function verifyCommandClass(commandClass:Class):void
{
if (!verifiedCommandClasses[commandClass])
{
verifiedCommandClasses[commandClass] = describeType(commandClass).factory.method.(@name == "execute").length();
if (!verifiedCommandClasses[commandClass])
throw new ContextError(ContextError.E_COMMANDMAP_NOIMPL + ' - ' + commandClass);
}
}
/**
* Event Handler
*
* @param event The <code>Event</code>
* @param commandClass The Class to construct and execute
* @param oneshot Should this command mapping be removed after execution?
* @return <code>true</code> if the event was routed to a Command and the Command was executed,
* <code>false</code> otherwise
*/
protected function routeEventToCommand(event:Event, commandClass:Class, oneshot:Boolean, originalEventClass:Class):Boolean
{
if (!(event is originalEventClass)) return false;
execute(commandClass, event);
if (oneshot) unmapEvent(event.type, commandClass, originalEventClass);
return true;
}
}
}
|
/*
* Copyright (c) 2009 the original author or authors
*
* Permission is hereby granted to use, modify, and distribute this file
* in accordance with the terms of the license agreement accompanying it.
*/
package org.robotlegs.base
{
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.utils.Dictionary;
import flash.utils.describeType;
import org.robotlegs.core.ICommandMap;
import org.robotlegs.core.IInjector;
import org.robotlegs.core.IReflector;
/**
* An abstract <code>ICommandMap</code> implementation
*/
public class CommandMap implements ICommandMap
{
/**
* The <code>IEventDispatcher</code> to listen to
*/
protected var eventDispatcher:IEventDispatcher;
/**
* The <code>IInjector</code> to inject with
*/
protected var injector:IInjector;
/**
* The <code>IReflector</code> to reflect with
*/
protected var reflector:IReflector;
/**
* Internal
*
* TODO: This needs to be documented
*/
protected var eventTypeMap:Dictionary;
/**
* Internal
*
* Collection of command classes that have been verified to implement an <code>execute</code> method
*/
protected var verifiedCommandClasses:Dictionary;
protected var detainedCommands:Dictionary;
//---------------------------------------------------------------------
// Constructor
//---------------------------------------------------------------------
/**
* Creates a new <code>CommandMap</code> object
*
* @param eventDispatcher The <code>IEventDispatcher</code> to listen to
* @param injector An <code>IInjector</code> to use for this context
* @param reflector An <code>IReflector</code> to use for this context
*/
public function CommandMap(eventDispatcher:IEventDispatcher, injector:IInjector, reflector:IReflector)
{
this.eventDispatcher = eventDispatcher;
this.injector = injector;
this.reflector = reflector;
this.eventTypeMap = new Dictionary(false);
this.verifiedCommandClasses = new Dictionary(false);
this.detainedCommands = new Dictionary(false);
}
//---------------------------------------------------------------------
// API
//---------------------------------------------------------------------
/**
* @inheritDoc
*/
public function mapEvent(eventType:String, commandClass:Class, eventClass:Class = null, oneshot:Boolean = false):void
{
verifyCommandClass(commandClass);
eventClass = eventClass || Event;
var eventClassMap:Dictionary = eventTypeMap[eventType] ||= new Dictionary(false);
var callbacksByCommandClass:Dictionary = eventClassMap[eventClass] ||= new Dictionary(false);
if (callbacksByCommandClass[commandClass] != null)
{
throw new ContextError(ContextError.E_COMMANDMAP_OVR + ' - eventType (' + eventType + ') and Command (' + commandClass + ')');
}
var callback:Function = function(event:Event):void
{
routeEventToCommand(event, commandClass, oneshot, eventClass);
};
eventDispatcher.addEventListener(eventType, callback, false, 0, true);
callbacksByCommandClass[commandClass] = callback;
}
/**
* @inheritDoc
*/
public function unmapEvent(eventType:String, commandClass:Class, eventClass:Class = null):void
{
var eventClassMap:Dictionary = eventTypeMap[eventType];
if (eventClassMap == null) return;
var callbacksByCommandClass:Dictionary = eventClassMap[eventClass || Event];
if (callbacksByCommandClass == null) return;
var callback:Function = callbacksByCommandClass[commandClass];
if (callback == null) return;
eventDispatcher.removeEventListener(eventType, callback, false);
delete callbacksByCommandClass[commandClass];
}
/**
* @inheritDoc
*/
public function unmapEvents():void
{
for (var eventType:String in eventTypeMap)
{
var eventClassMap:Dictionary = eventTypeMap[eventType];
for each (var callbacksByCommandClass:Dictionary in eventClassMap)
{
for each ( var callback:Function in callbacksByCommandClass)
{
eventDispatcher.removeEventListener(eventType, callback, false);
}
}
}
eventTypeMap = new Dictionary(false);
}
/**
* @inheritDoc
*/
public function hasEventCommand(eventType:String, commandClass:Class, eventClass:Class = null):Boolean
{
var eventClassMap:Dictionary = eventTypeMap[eventType];
if (eventClassMap == null) return false;
var callbacksByCommandClass:Dictionary = eventClassMap[eventClass || Event];
if (callbacksByCommandClass == null) return false;
return callbacksByCommandClass[commandClass] != null;
}
/**
* @inheritDoc
*/
public function execute(commandClass:Class, payload:Object = null, payloadClass:Class = null, named:String = ''):void
{
verifyCommandClass(commandClass);
if (payload != null || payloadClass != null)
{
payloadClass ||= reflector.getClass(payload);
if (payload is Event && payloadClass != Event)
injector.mapValue(Event, payload);
injector.mapValue(payloadClass, payload, named);
}
var command:Object = injector.instantiate(commandClass);
if (payload !== null || payloadClass != null)
{
if (payload is Event && payloadClass != Event)
injector.unmap(Event);
injector.unmap(payloadClass, named);
}
command.execute();
}
/**
* @inheritDoc
*/
public function detain(command:Object):void
{
detainedCommands[command] = true;
}
/**
* @inheritDoc
*/
public function release(command:Object):void
{
if (detainedCommands[command])
delete detainedCommands[command];
}
//---------------------------------------------------------------------
// Internal
//---------------------------------------------------------------------
/**
* @throws org.robotlegs.base::ContextError
*/
protected function verifyCommandClass(commandClass:Class):void
{
if (!verifiedCommandClasses[commandClass])
{
verifiedCommandClasses[commandClass] = describeType(commandClass).factory.method.(@name == "execute").length();
if (!verifiedCommandClasses[commandClass])
throw new ContextError(ContextError.E_COMMANDMAP_NOIMPL + ' - ' + commandClass);
}
}
/**
* Event Handler
*
* @param event The <code>Event</code>
* @param commandClass The Class to construct and execute
* @param oneshot Should this command mapping be removed after execution?
* @return <code>true</code> if the event was routed to a Command and the Command was executed,
* <code>false</code> otherwise
*/
protected function routeEventToCommand(event:Event, commandClass:Class, oneshot:Boolean, originalEventClass:Class):Boolean
{
if (!(event is originalEventClass)) return false;
execute(commandClass, event);
if (oneshot) unmapEvent(event.type, commandClass, originalEventClass);
return true;
}
}
}
|
Fix unnecessarily name injecting during abstract Event "mapValue"
|
Fix unnecessarily name injecting during abstract Event "mapValue"
|
ActionScript
|
mit
|
robotlegs/robotlegs-framework,eric-stanley/robotlegs-framework,robotlegs/robotlegs-framework,eric-stanley/robotlegs-framework
|
df1b8a3ceebad83b3494cd55232c6e6bfce113ed
|
src/aerys/minko/scene/visitor/data/CameraData.as
|
src/aerys/minko/scene/visitor/data/CameraData.as
|
package aerys.minko.scene.visitor.data
{
import aerys.minko.type.math.Frustum;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
public class CameraData implements IWorldData
{
public static const POSITION : String = 'position';
public static const LOOK_AT : String = 'lookAt';
public static const UP : String = 'up';
public static const RATIO : String = 'ratio';
public static const FOV : String = 'fov';
public static const Z_NEAR : String = 'zNear';
public static const Z_FAR : String = 'zFar';
public static const Z_FAR_PARTS : String = 'zFarParts';
public static const VIEW : String = 'view';
public static const PROJECTION : String = 'projection';
public static const LOCAL_POSITION : String = 'localPosition';
public static const LOCAL_LOOK_AT : String = 'localLookAt';
public static const DIRECTION : String = 'direction';
public static const LOCAL_DIRECTION : String = 'localDirection';
public static const FRUSTUM : String = 'frustum';
// local data provider
protected var _styleStack : StyleStack;
protected var _localData : LocalData;
// data available on initialisation
protected var _position : Vector4;
protected var _lookAt : Vector4;
protected var _up : Vector4;
protected var _ratio : Number;
protected var _fov : Number;
protected var _zNear : Number;
protected var _zFar : Number;
// computed data
protected var _zFarParts : Vector4;
protected var _zFarParts_invalidated : Boolean;
protected var _view : Matrix4x4;
protected var _view_positionVersion : uint;
protected var _view_lookAtVersion : uint;
protected var _view_upVersion : uint;
protected var _projection : Matrix4x4;
protected var _projection_invalidated : Boolean;
protected var _localPosition : Vector4;
protected var _localPosition_positionVersion : uint;
protected var _localLookAt : Vector4;
protected var _localLookAt_lookAtVersion : uint;
protected var _frustum : Frustum;
protected var _frustum_projectionVersion : uint;
public function get position() : Vector4
{
return _position;
}
public function get lookAt() : Vector4
{
return _lookAt;
}
public function get up() : Vector4
{
return _up;
}
public function get fieldOfView() : Number
{
return _fov;
}
public function get zNear() : Number
{
return _zNear;
}
public function get zFar() : Number
{
return _zFar;
}
public function get zFarParts() : Vector4
{
if (_zFarParts_invalidated)
{
_zFarParts = new Vector4(0, 0.25 * _zFar, 0.5 * _zFar, 0.75 * _zFar);
_zFarParts_invalidated = false;
}
return _zFarParts;
}
public function get view() : Matrix4x4
{
if (_view_positionVersion != _position.version ||
_view_lookAtVersion != _lookAt.version ||
_view_upVersion != _up.version)
{
_view = Matrix4x4.lookAtLH(_position, _lookAt, _up, _view);
_view_positionVersion = _position.version;
_view_lookAtVersion = _lookAt.version;
_view_upVersion = _lookAt.version;
}
return _view;
}
public function get projection() : Matrix4x4
{
if (_projection_invalidated)
{
_projection = Matrix4x4.perspectiveFoVLH(_fov, _ratio, _zNear, _zFar, _projection);
_projection_invalidated = false;
}
return _projection;
}
public function get frustrum() : Frustum
{
var projectionMatrix : Matrix4x4 = projection;
if (_frustum_projectionVersion != projectionMatrix.version)
{
if (_frustum == null)
_frustum = new Frustum();
_frustum.update(projectionMatrix);
_frustum_projectionVersion = projectionMatrix.version;
}
return _frustum;
}
public function get localPosition() : Vector4
{
if (_localPosition_positionVersion != _position.version)
{
_localPosition = _localData.world.multiplyVector(_position, _localPosition);
_localPosition_positionVersion = _position.version;
}
return _localPosition;
}
public function get localLookAt() : Vector4
{
if (_localLookAt_lookAtVersion != _lookAt.version)
{
_localLookAt = _localData.world.deltaMultiplyVector(_lookAt, _localLookAt);
_localLookAt_lookAtVersion = _lookAt.version;
}
return _localLookAt;
}
public function get localDirection() : Vector4
{
// FIXME: handle cache
return Vector4.subtract(localPosition, localLookAt).normalize();
}
public function get direction() : Vector4
{
// FIXME: handle cache
return Vector4.subtract(position, lookAt).normalize();
}
public function set ratio(v : Number) : void
{
_ratio = v;
_projection_invalidated = true;
}
public function set position(v : Vector4) : void
{
_position = v;
}
public function set lookAt(v : Vector4) : void
{
_lookAt = v;
}
public function set up(v : Vector4) : void
{
_up = v;
}
public function set fov(v : Number) : void
{
_fov = v;
_projection_invalidated = true;
}
public function set zNear(v : Number) : void
{
_zNear = v;
_projection_invalidated = true;
}
public function set zFar(v : Number) : void
{
_zFar = v;
_projection_invalidated = true;
}
public function CameraData()
{
reset()
}
public function setLocalDataProvider(styleStack : StyleStack,
localData : LocalData) : void
{
_styleStack = styleStack;
_localData = localData;
}
public function invalidate() : void
{
// do nothing
}
public function reset() : void
{
_position = null;
_lookAt = null;
_up = null;
_ratio = -1;
_fov = -1;
_zNear = -1;
_zFar = -1;
_view_positionVersion = uint.MAX_VALUE;
_view_lookAtVersion = uint.MAX_VALUE;
_view_upVersion = uint.MAX_VALUE;
_localPosition_positionVersion = uint.MAX_VALUE;
_localLookAt_lookAtVersion = uint.MAX_VALUE;
_frustum_projectionVersion = uint.MAX_VALUE;
_zFarParts_invalidated = true;
_projection_invalidated = true;
}
}
}
|
package aerys.minko.scene.visitor.data
{
import aerys.minko.type.math.Frustum;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
public class CameraData implements IWorldData
{
public static const POSITION : String = 'position';
public static const LOOK_AT : String = 'lookAt';
public static const UP : String = 'up';
public static const RATIO : String = 'ratio';
public static const FOV : String = 'fov';
public static const Z_NEAR : String = 'zNear';
public static const Z_FAR : String = 'zFar';
public static const Z_FAR_PARTS : String = 'zFarParts';
public static const VIEW : String = 'view';
public static const PROJECTION : String = 'projection';
public static const LOCAL_POSITION : String = 'localPosition';
public static const LOCAL_LOOK_AT : String = 'localLookAt';
public static const DIRECTION : String = 'direction';
public static const LOCAL_DIRECTION : String = 'localDirection';
public static const FRUSTUM : String = 'frustum';
// local data provider
protected var _styleStack : StyleStack;
protected var _localData : LocalData;
// data available on initialisation
protected var _position : Vector4;
protected var _lookAt : Vector4;
protected var _up : Vector4;
protected var _ratio : Number;
protected var _fov : Number;
protected var _zNear : Number;
protected var _zFar : Number;
// computed data
protected var _zFarParts : Vector4;
protected var _zFarParts_invalidated : Boolean;
protected var _view : Matrix4x4;
protected var _view_positionVersion : uint;
protected var _view_lookAtVersion : uint;
protected var _view_upVersion : uint;
protected var _projection : Matrix4x4;
protected var _projection_invalidated : Boolean;
protected var _localPosition : Vector4;
protected var _localPosition_positionVersion : uint;
protected var _localPosition_worldVersion : uint;
protected var _localLookAt : Vector4;
protected var _localLookAt_lookAtVersion : uint;
protected var _localLookAt_worldVersion : uint;
protected var _frustum : Frustum;
protected var _frustum_projectionVersion : uint;
public function get position() : Vector4
{
return _position;
}
public function get lookAt() : Vector4
{
return _lookAt;
}
public function get up() : Vector4
{
return _up;
}
public function get fieldOfView() : Number
{
return _fov;
}
public function get zNear() : Number
{
return _zNear;
}
public function get zFar() : Number
{
return _zFar;
}
public function get zFarParts() : Vector4
{
if (_zFarParts_invalidated)
{
_zFarParts = new Vector4(0, 0.25 * _zFar, 0.5 * _zFar, 0.75 * _zFar);
_zFarParts_invalidated = false;
}
return _zFarParts;
}
public function get view() : Matrix4x4
{
if (_view_positionVersion != _position.version ||
_view_lookAtVersion != _lookAt.version ||
_view_upVersion != _up.version)
{
_view = Matrix4x4.lookAtLH(_position, _lookAt, _up, _view);
_view_positionVersion = _position.version;
_view_lookAtVersion = _lookAt.version;
_view_upVersion = _lookAt.version;
}
return _view;
}
public function get projection() : Matrix4x4
{
if (_projection_invalidated)
{
_projection = Matrix4x4.perspectiveFoVLH(_fov, _ratio, _zNear, _zFar, _projection);
_projection_invalidated = false;
}
return _projection;
}
public function get frustrum() : Frustum
{
var projectionMatrix : Matrix4x4 = projection;
if (_frustum_projectionVersion != projectionMatrix.version)
{
if (_frustum == null)
_frustum = new Frustum();
_frustum.update(projectionMatrix);
_frustum_projectionVersion = projectionMatrix.version;
}
return _frustum;
}
public function get localPosition() : Vector4
{
var worldMatrix : Matrix4x4 = _localData.world;
if (_localPosition_positionVersion != _position.version ||
_localPosition_worldVersion != worldMatrix.version)
{
_localPosition = worldMatrix.multiplyVector(_position, _localPosition);
_localPosition_positionVersion = _position.version;
_localPosition_worldVersion = worldMatrix.version;
}
return _localPosition;
}
public function get localLookAt() : Vector4
{
var worldMatrix : Matrix4x4 = _localData.world;
if (_localLookAt_lookAtVersion != _lookAt.version ||
_localLookAt_worldVersion != worldMatrix.version)
{
_localLookAt = worldMatrix.multiplyVector(_lookAt, _localLookAt);
_localLookAt_lookAtVersion = _lookAt.version;
_localLookAt_worldVersion = worldMatrix.version;
}
return _localLookAt;
}
public function get localDirection() : Vector4
{
// FIXME: handle cache
return Vector4.subtract(localPosition, localLookAt).normalize();
}
public function get direction() : Vector4
{
// FIXME: handle cache
return Vector4.subtract(position, lookAt).normalize();
}
public function set ratio(v : Number) : void
{
_ratio = v;
_projection_invalidated = true;
}
public function set position(v : Vector4) : void
{
_position = v;
}
public function set lookAt(v : Vector4) : void
{
_lookAt = v;
}
public function set up(v : Vector4) : void
{
_up = v;
}
public function set fov(v : Number) : void
{
_fov = v;
_projection_invalidated = true;
}
public function set zNear(v : Number) : void
{
_zNear = v;
_projection_invalidated = true;
}
public function set zFar(v : Number) : void
{
_zFar = v;
_projection_invalidated = true;
}
public function CameraData()
{
reset()
}
public function setLocalDataProvider(styleStack : StyleStack,
localData : LocalData) : void
{
_styleStack = styleStack;
_localData = localData;
}
public function invalidate() : void
{
// do nothing
}
public function reset() : void
{
_position = null;
_lookAt = null;
_up = null;
_ratio = -1;
_fov = -1;
_zNear = -1;
_zFar = -1;
_view_positionVersion = uint.MAX_VALUE;
_view_lookAtVersion = uint.MAX_VALUE;
_view_upVersion = uint.MAX_VALUE;
_localPosition_positionVersion = uint.MAX_VALUE;
_localPosition_worldVersion = uint.MAX_VALUE;
_localLookAt_lookAtVersion = uint.MAX_VALUE;
_localLookAt_worldVersion = uint.MAX_VALUE;
_frustum_projectionVersion = uint.MAX_VALUE;
_zFarParts_invalidated = true;
_projection_invalidated = true;
}
}
}
|
Fix versionning bug in lazy access to local data from the CameraData (cameraLocalPosition and cameraLocalLookAt)
|
Fix versionning bug in lazy access to local data from the CameraData (cameraLocalPosition and cameraLocalLookAt)
|
ActionScript
|
mit
|
aerys/minko-as3
|
45f1d7629b40ae609124f51671fa85bce00b6e10
|
src/aerys/minko/type/loader/TextureLoader.as
|
src/aerys/minko/type/loader/TextureLoader.as
|
package aerys.minko.type.loader
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.Signal;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.system.LoaderContext;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public final class TextureLoader implements ILoader
{
private var _progress : Signal;
private var _error : Signal;
private var _complete : Signal;
private var _isComplete : Boolean;
private var _mipmap : Boolean;
private var _textureResource : TextureResource;
public function get progress() : Signal
{
return _progress;
}
public function get error() : Signal
{
return _error;
}
public function get complete() : Signal
{
return _complete;
}
public function get isComplete() : Boolean
{
return _isComplete;
}
public function get textureResource() : TextureResource
{
return _textureResource;
}
public function TextureLoader(enableMipmapping : Boolean = true)
{
_mipmap = enableMipmapping;
_textureResource = new TextureResource();
_isComplete = false;
_error = new Signal();
_progress = new Signal();
_complete = new Signal();
}
public function load(request : URLRequest) : void
{
var loader : URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(ProgressEvent.PROGRESS, onLoadProgressHandler);
loader.addEventListener(Event.COMPLETE, onLoadCompleteHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, onLoadIoErrorEvent);
loader.load(request);
}
private function onLoadIoErrorEvent(e : IOErrorEvent) : void
{
_textureResource = null;
_error.execute(this, e.errorID, e.text);
}
private function onLoadProgressHandler(e : ProgressEvent) : void
{
_progress.execute(this, e.bytesLoaded, e.bytesTotal);
}
private function onLoadCompleteHandler(e : Event) : void
{
loadBytes(URLLoader(e.currentTarget).data);
}
public function loadClass(classObject : Class) : void
{
var assetObject : Object = new classObject();
if (assetObject is Bitmap || assetObject is BitmapData)
{
var bitmapData : BitmapData = assetObject as BitmapData;
if (bitmapData == null)
bitmapData = Bitmap(assetObject).bitmapData;
// _textureResource = new TextureResource();
_textureResource.setContentFromBitmapData(bitmapData, _mipmap);
_complete.execute(this, _textureResource);
_isComplete = true;
}
else if (assetObject is ByteArray)
{
loadBytes(ByteArray(assetObject));
}
else
{
var className : String = getQualifiedClassName(classObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error('No texture can be created from an object of type \'' + className + '\'');
}
}
public function loadBytes(bytes : ByteArray) : void
{
bytes.position = 0;
if (bytes.readByte() == 'A'.charCodeAt(0) &&
bytes.readByte() == 'T'.charCodeAt(0) &&
bytes.readByte() == 'F'.charCodeAt(0))
{
bytes.position = 0;
// _textureResource = new TextureResource();
_textureResource.setContentFromATF(bytes);
_complete.execute(this, _textureResource);
_isComplete = true;
}
else
{
bytes.position = 0;
var loader : Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadBytesComplete);
loader.loadBytes(bytes);
}
}
private function onLoadBytesComplete(e : Event) : void
{
var displayObject : DisplayObject = LoaderInfo(e.currentTarget).content;
if (displayObject is Bitmap)
{
_textureResource.setContentFromBitmapData(Bitmap(displayObject).bitmapData, _mipmap);
_complete.execute(this, _textureResource);
_isComplete = true;
}
else
{
var className : String = getQualifiedClassName(displayObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error('No texture can be created from an object of type \'' + className + '\'');
}
}
public static function loadClass(classObject : Class,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadClass(classObject);
return textureLoader.textureResource;
}
public static function load(request : URLRequest,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.load(request);
return textureLoader.textureResource;
}
public static function loadBytes(bytes : ByteArray,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadBytes(bytes);
return textureLoader.textureResource;
}
}
}
|
package aerys.minko.type.loader
{
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.Signal;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.system.LoaderContext;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class TextureLoader implements ILoader
{
private var _progress : Signal;
private var _error : Signal;
private var _complete : Signal;
private var _isComplete : Boolean;
private var _mipmap : Boolean;
private var _textureResource : TextureResource;
public function get progress() : Signal
{
return _progress;
}
public function get error() : Signal
{
return _error;
}
public function get complete() : Signal
{
return _complete;
}
public function get isComplete() : Boolean
{
return _isComplete;
}
public function get textureResource() : TextureResource
{
return _textureResource;
}
public function TextureLoader(enableMipmapping : Boolean = true)
{
_mipmap = enableMipmapping;
_textureResource = new TextureResource();
_isComplete = false;
_error = new Signal();
_progress = new Signal();
_complete = new Signal();
}
public function load(request : URLRequest) : void
{
var loader : URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.addEventListener(ProgressEvent.PROGRESS, onLoadProgressHandler);
loader.addEventListener(Event.COMPLETE, onLoadCompleteHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, onLoadIoErrorEvent);
loader.load(request);
}
private function onLoadIoErrorEvent(e : IOErrorEvent) : void
{
_textureResource = null;
_error.execute(this, e.errorID, e.text);
}
private function onLoadProgressHandler(e : ProgressEvent) : void
{
_progress.execute(this, e.bytesLoaded, e.bytesTotal);
}
private function onLoadCompleteHandler(e : Event) : void
{
loadBytes(URLLoader(e.currentTarget).data);
}
public function loadClass(classObject : Class) : void
{
var assetObject : Object = new classObject();
if (assetObject is Bitmap || assetObject is BitmapData)
{
var bitmapData : BitmapData = assetObject as BitmapData;
if (bitmapData == null)
bitmapData = Bitmap(assetObject).bitmapData;
// _textureResource = new TextureResource();
_textureResource.setContentFromBitmapData(bitmapData, _mipmap);
_complete.execute(this, _textureResource);
_isComplete = true;
}
else if (assetObject is ByteArray)
{
loadBytes(ByteArray(assetObject));
}
else
{
var className : String = getQualifiedClassName(classObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error('No texture can be created from an object of type \'' + className + '\'');
}
}
public function loadBytes(bytes : ByteArray) : void
{
bytes.position = 0;
if (bytes.readByte() == 'A'.charCodeAt(0) &&
bytes.readByte() == 'T'.charCodeAt(0) &&
bytes.readByte() == 'F'.charCodeAt(0))
{
bytes.position = 0;
// _textureResource = new TextureResource();
_textureResource.setContentFromATF(bytes);
_complete.execute(this, _textureResource);
_isComplete = true;
}
else
{
bytes.position = 0;
var loader : Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadBytesComplete);
loader.loadBytes(bytes);
}
}
private function onLoadBytesComplete(e : Event) : void
{
var displayObject : DisplayObject = LoaderInfo(e.currentTarget).content;
if (displayObject is Bitmap)
{
_textureResource.setContentFromBitmapData(Bitmap(displayObject).bitmapData, _mipmap);
_complete.execute(this, _textureResource);
_isComplete = true;
}
else
{
var className : String = getQualifiedClassName(displayObject);
className = className.substr(className.lastIndexOf(':') + 1);
_isComplete = true;
throw new Error('No texture can be created from an object of type \'' + className + '\'');
}
}
public static function loadClass(classObject : Class,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadClass(classObject);
return textureLoader.textureResource;
}
public static function load(request : URLRequest,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.load(request);
return textureLoader.textureResource;
}
public static function loadBytes(bytes : ByteArray,
enableMipMapping : Boolean = true) : TextureResource
{
var textureLoader : TextureLoader = new TextureLoader(enableMipMapping);
textureLoader.loadBytes(bytes);
return textureLoader.textureResource;
}
}
}
|
Make TextureLoader inheritable.
|
Make TextureLoader inheritable.
|
ActionScript
|
mit
|
aerys/minko-as3
|
38d4644fc0df7965e6298d41f101f1aec9a0c287
|
test/request/HTTPClientTest.as
|
test/request/HTTPClientTest.as
|
package test.request {
import mx.rpc.events.ResultEvent;
import flails.request.HTTPClient;
import flails.request.JSONFilter;
import flails.request.Record;
import flails.request.ResourcePathBuilder;
import net.digitalprimates.fluint.tests.TestCase;
public class HTTPClientTest extends TestCase {
private var r:HTTPClient;
override protected function setUp():void {
var cleanup:HTTPClient = new HTTPClient(null)
cleanup.addEventListener("result", asyncHandler(pendUntilComplete, 1000))
cleanup.doGet("/posts/reset");
r = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter());
}
public function testIndex():void {
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var a:Array = e.result as Array;
assertEquals(2, a.length);
assertEquals('testFindAll #1', a[0].subject);
assertEquals('testFindAll #1 body', a[0].body);
assertEquals('testFindAll #2', a[1].subject);
assertEquals('testFindAll #2 body', a[1].body);
}, 1000));
r.index();
}
5
public function testFindById():void {
var r:HTTPClient = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter());
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = e.result as Record;
assertEquals('testFindAll #1', p.subject);
assertEquals('testFindAll #1 body', p.body);
}, 1500));
r.show(1);
}
public function testUpdate():void {
var r:HTTPClient = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter());
r.addEventListener("result", asyncHandler(verifyUpdateComplete, 1500));
r.update(2, {post: {subject: "testFindAll #2 updated", body: "testFindAll #2 body updated"}});
}
private function verifyUpdateComplete(e:ResultEvent, data:Object):void {
var r:HTTPClient = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter());
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = e.result as Record;
assertEquals('testFindAll #2 updated', p.subject);
assertEquals('testFindAll #2 body updated', p.body);
}, 1500));
r.show(2);
}
}
}
|
package test.request {
import mx.rpc.events.ResultEvent;
import flails.request.HTTPClient;
import flails.request.JSONFilter;
import flails.request.Record;
import flails.request.ResourcePathBuilder;
import net.digitalprimates.fluint.tests.TestCase;
public class HTTPClientTest extends TestCase {
private var r:HTTPClient;
override protected function setUp():void {
var cleanup:HTTPClient = new HTTPClient(null)
cleanup.addEventListener("result", asyncHandler(pendUntilComplete, 1000))
cleanup.doGet("/posts/reset");
r = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter());
}
public function testIndex():void {
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var a:Array = e.result as Array;
assertEquals(2, a.length);
assertEquals('testFindAll #1', a[0].subject);
assertEquals('testFindAll #1 body', a[0].body);
assertEquals('testFindAll #2', a[1].subject);
assertEquals('testFindAll #2 body', a[1].body);
}, 1000));
r.index();
}
5
public function testFindById():void {
var r:HTTPClient = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter());
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = e.result as Record;
assertEquals('testFindAll #1', p.subject);
assertEquals('testFindAll #1 body', p.body);
}, 1500));
r.show(1);
}
public function testCreate():void {
var r:HTTPClient = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter());
r.addEventListener("result", asyncHandler(verifyCreateComplete, 1500));
r.create({post: {subject: "creating new post", body: "creating new post with body"}});
}
private function verifyCreateComplete(e:ResultEvent, data:Object):void {
var r:HTTPClient = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter());
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = e.result as Record;
assertEquals('testFindAll #2 updated', p.subject);
assertEquals('testFindAll #2 body updated', p.body);
}, 1500));
r.show(2);
}
public function testUpdate():void {
var r:HTTPClient = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter());
r.addEventListener("result", asyncHandler(verifyUpdateComplete, 1500));
r.update(2, {post: {subject: "testFindAll #2 updated", body: "testFindAll #2 body updated"}});
}
private function verifyUpdateComplete(e:ResultEvent, data:Object):void {
var r:HTTPClient = new HTTPClient(new ResourcePathBuilder("posts"), new JSONFilter());
r.addEventListener("result", asyncHandler(function (e:ResultEvent, data:Object):void {
var p:Record = e.result as Record;
assertEquals('testFindAll #2 updated', p.subject);
assertEquals('testFindAll #2 body updated', p.body);
}, 1500));
r.show(2);
}
}
}
|
create test
|
create test
|
ActionScript
|
mit
|
lancecarlson/flails,lancecarlson/flails
|
95546895f81c971e2e4a91bcc3480430832c71d7
|
src/as/com/threerings/cast/ComponentDataPack.as
|
src/as/com/threerings/cast/ComponentDataPack.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.cast {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.events.Event;
import flash.utils.ByteArray;
import nochump.util.zip.ZipEntry;
import nochump.util.zip.ZipError;
import nochump.util.zip.ZipFile;
import com.threerings.media.image.PngRecolorUtil;
import com.threerings.media.tile.TileDataPack;
import com.threerings.media.tile.TileSet;
import com.threerings.util.DataPack;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.MultiLoader;
import com.threerings.util.Set;
import com.threerings.util.StringUtil;
/**
* Like a normal data pack, but we don't deal with any data, and all our filenames are a direct
* translation, so we need no metadata file. We also serve as a tile ImageProvider.
*/
public class ComponentDataPack extends TileDataPack
implements FrameProvider
{
private static var log :Log = Log.getLog(ComponentDataPack);
public function ComponentDataPack (source :Object, actions :Map,
completeListener :Function = null, errorListener :Function = null)
{
super(source, completeListener, errorListener);
_actions = actions;
}
// Documentation inherited from interface
public function getFrames (component :CharacterComponent, action :String,
type :String) :ActionFrames
{
// obtain the action sequence definition for this action
var actseq :ActionSequence = _actions.get(action);
if (actseq == null) {
log.warning("Missing action sequence definition [action=" + action +
", component=" + component + "].");
return null;
}
// determine our image path name
var imgpath :String = action;
var dimgpath :String = ActionSequence.DEFAULT_SEQUENCE;
if (type != null) {
imgpath += "_" + type;
dimgpath += "_" + type;
}
var root :String = component.componentClass.name + "/" + component.name + "/";
var cpath :String = root + imgpath + ".png";
var dpath :String = root + dimgpath + ".png";
// look to see if this tileset is already cached (as the custom action or the default
// action)
var aset :TileSet = _setcache.get(cpath);
if (aset == null) {
aset = _setcache.get(dpath);
if (aset != null) {
// save ourselves a lookup next time
_setcache.put(cpath, aset);
}
}
try {
// then try loading up a tileset customized for this action
if (aset == null) {
if (_zip.getEntry(cpath)) {
aset = TileSet(actseq.tileset.clone());
aset.setImagePath(cpath);
} else if (_zip.getEntry(dpath)) {
aset = TileSet(TileSet(_actions.get(ActionSequence.DEFAULT_SEQUENCE)).clone());
aset.setImagePath(dpath);
_setcache.put(dpath, aset);
}
}
// if that failed too, we're hosed
if (aset == null) {
// if this is a shadow or crop image, no need to freak out as they are optional
if (!StandardActions.CROP_TYPE == type &&
!StandardActions.SHADOW_TYPE == type) {
log.warning("Unable to locate tileset for action '" + imgpath + "' " +
component + ".");
}
return null;
}
aset.setImageProvider(this);
_setcache.put(cpath, aset);
return new TileSetFrameImage(aset, actseq);
} catch (e :Error) {
log.warning("Error loading tset for action '" + imgpath + "' " + component + ".", e);
}
return null;
}
// Documentation inherited from interface
public function getFramePath (
component :CharacterComponent, action :String, type :String, existentPaths :Set) :String
{
var actionPath :String = makePath(component, action, type);
if (!existentPaths.contains(actionPath)) {
return makePath(component, ActionSequence.DEFAULT_SEQUENCE, type);
}
return actionPath;
}
protected function makePath (component :CharacterComponent, action :String,
type :String) :String
{
var imgpath :String = action;
if (type != null) {
imgpath += "_" + type;
}
var root :String = component.componentClass.name + "/" + component.name + "/";
return root + imgpath + ".png";
}
protected var _actions :Map;
protected var _setcache :Map = Maps.newMapOf(String);
}
}
|
//
// 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.cast {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.events.Event;
import flash.utils.ByteArray;
import nochump.util.zip.ZipEntry;
import nochump.util.zip.ZipError;
import nochump.util.zip.ZipFile;
import com.threerings.media.image.PngRecolorUtil;
import com.threerings.media.tile.TileDataPack;
import com.threerings.media.tile.TileSet;
import com.threerings.util.DataPack;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.MultiLoader;
import com.threerings.util.Set;
import com.threerings.util.StringUtil;
/**
* Like a normal data pack, but we don't deal with any data, and all our filenames are a direct
* translation, so we need no metadata file. We also serve as a tile ImageProvider.
*/
public class ComponentDataPack extends TileDataPack
implements FrameProvider
{
private static var log :Log = Log.getLog(ComponentDataPack);
public function ComponentDataPack (source :Object, actions :Map,
completeListener :Function = null, errorListener :Function = null)
{
super(source, completeListener, errorListener);
_actions = actions;
}
// Documentation inherited from interface
public function getFrames (component :CharacterComponent, action :String,
type :String) :ActionFrames
{
// obtain the action sequence definition for this action
var actseq :ActionSequence = _actions.get(action);
if (actseq == null) {
log.warning("Missing action sequence definition [action=" + action +
", component=" + component + "].");
return null;
}
// determine our image path name
var imgpath :String = action;
var dimgpath :String = ActionSequence.DEFAULT_SEQUENCE;
if (type != null) {
imgpath += "_" + type;
dimgpath += "_" + type;
}
var root :String = component.componentClass.name + "/" + component.name + "/";
var cpath :String = root + imgpath + ".png";
var dpath :String = root + dimgpath + ".png";
// look to see if this tileset is already cached (as the custom action or the default
// action)
var aset :TileSet = _setcache.get(cpath);
if (aset == null) {
aset = _setcache.get(dpath);
if (aset != null) {
// save ourselves a lookup next time
_setcache.put(cpath, aset);
}
}
try {
// then try loading up a tileset customized for this action
if (aset == null) {
if (_zip.getEntry(cpath)) {
aset = TileSet(actseq.tileset.clone());
aset.setImagePath(cpath);
} else if (_zip.getEntry(dpath)) {
actseq = _actions.get(ActionSequence.DEFAULT_SEQUENCE);
aset = TileSet(actseq.tileset.clone());
aset.setImagePath(dpath);
_setcache.put(dpath, aset);
}
}
// if that failed too, we're hosed
if (aset == null) {
// if this is a shadow or crop image, no need to freak out as they are optional
if (!StandardActions.CROP_TYPE == type &&
!StandardActions.SHADOW_TYPE == type) {
log.warning("Unable to locate tileset for action '" + imgpath + "' " +
component + ".");
}
return null;
}
aset.setImageProvider(this);
_setcache.put(cpath, aset);
return new TileSetFrameImage(aset, actseq);
} catch (e :Error) {
log.warning("Error loading tset for action '" + imgpath + "' " + component + ".", e);
}
return null;
}
// Documentation inherited from interface
public function getFramePath (
component :CharacterComponent, action :String, type :String, existentPaths :Set) :String
{
var actionPath :String = makePath(component, action, type);
if (!existentPaths.contains(actionPath)) {
return makePath(component, ActionSequence.DEFAULT_SEQUENCE, type);
}
return actionPath;
}
protected function makePath (component :CharacterComponent, action :String,
type :String) :String
{
var imgpath :String = action;
if (type != null) {
imgpath += "_" + type;
}
var root :String = component.componentClass.name + "/" + component.name + "/";
return root + imgpath + ".png";
}
protected var _actions :Map;
protected var _setcache :Map = Maps.newMapOf(String);
}
}
|
Fix bug with falling back to default action.
|
Fix bug with falling back to default action.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@996 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
23c568cace968c7c1b3808ac5ed4dd9a1b652c83
|
WeaveData/src/weave/data/KeySets/SortedKeySet.as
|
WeaveData/src/weave/data/KeySets/SortedKeySet.as
|
/*
Weave (Web-based Analysis and Visualization Environment)
Copyright (C) 2008-2011 University of Massachusetts Lowell
This file is a part of Weave.
Weave is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, Version 3,
as published by the Free Software Foundation.
Weave is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Weave. If not, see <http://www.gnu.org/licenses/>.
*/
package weave.data.KeySets
{
import mx.utils.ObjectUtil;
import weave.api.core.ICallbackCollection;
import weave.api.core.ILinkableObject;
import weave.api.data.IAttributeColumn;
import weave.api.data.IKeySet;
import weave.api.data.IQualifiedKey;
import weave.api.getCallbackCollection;
import weave.api.linkableObjectIsBusy;
import weave.api.newDisposableChild;
import weave.api.newLinkableChild;
import weave.api.registerLinkableChild;
import weave.compiler.StandardLib;
import weave.core.CallbackCollection;
import weave.data.QKeyManager;
import weave.utils.AsyncSort;
/**
* This provides the keys from an existing IKeySet in a sorted order.
* Callbacks will trigger when the sorted result changes.
*
* @author adufilie
*/
public class SortedKeySet implements IKeySet
{
public static var debug:Boolean = false;
/**
* @param keySet An IKeySet to sort.
* @param compare A function that compares two IQualifiedKey objects and returns an integer.
* @param dependencies A list of ILinkableObjects that affect the result of the compare function.
*/
public function SortedKeySet(keySet:IKeySet, keyCompare:Function = null, dependencies:Array = null)
{
_keySet = keySet;
_compare = keyCompare || QKeyManager.keyCompare;
getCallbackCollection(_asyncSort).addImmediateCallback(this, _handleSorted);
for each (var object:ILinkableObject in dependencies)
registerLinkableChild(_dependencies, object);
registerLinkableChild(_dependencies, _keySet);
_dependencies.addImmediateCallback(this, _validate, true);
if (debug)
getCallbackCollection(this).addImmediateCallback(this, _firstCallback);
}
private function _firstCallback():void { debugTrace(this,'trigger',keys.length,'keys'); }
/**
* This is the list of keys from the IKeySet, sorted.
*/
public function get keys():Array
{
if (_triggerCounter != _dependencies.triggerCounter)
_validate();
return _sortedKeys;
}
/**
* @inheritDoc
*/
public function containsKey(key:IQualifiedKey):Boolean
{
return _keySet.containsKey(key);
}
private var _triggerCounter:uint = 0;
private var _dependencies:ICallbackCollection = newDisposableChild(this, CallbackCollection);
private var _keySet:IKeySet;
private var _compare:Function;
private var _asyncSort:AsyncSort = newLinkableChild(this, AsyncSort);
private var _sortedKeys:Array = [];
private var _prevSortedKeys:Array = [];
private function _validate():void
{
_triggerCounter = _dependencies.triggerCounter;
// if actively sorting, don't overwrite previous keys
if (!linkableObjectIsBusy(_asyncSort))
_prevSortedKeys = _sortedKeys;
// begin sorting a copy of the new keys
_sortedKeys = _keySet.keys.concat();
_asyncSort.beginSort(_sortedKeys, _compare);
}
private function _handleSorted():void
{
// only trigger callbacks if sorting changes order
if (StandardLib.arrayCompare(_prevSortedKeys, _sortedKeys) != 0)
getCallbackCollection(this).triggerCallbacks();
}
/**
* This funciton generates a compare function that will compare IQualifiedKeys based on the corresponding values in the specified columns.
* @param columns An Array of IAttributeColumns to use for comparing IQualifiedKeys.
* @param sortDirections Array of sort directions corresponding to the columns and given as integers (1=ascending, -1=descending, 0=none).
* @return A new Function that will compare two IQualifiedKeys using numeric values from the specified columns.
*/
public static function generateCompareFunction(columns:Array, sortDirections:Array = null):Function
{
return new KeyComparator(columns, sortDirections).compare;
}
}
}
import mx.utils.ObjectUtil;
import weave.api.core.ILinkableObject;
import weave.api.data.IAttributeColumn;
import weave.api.data.IQualifiedKey;
import weave.api.getCallbackCollection;
import weave.data.QKeyManager;
internal class KeyComparator
{
public function KeyComparator(columns:Array, sortDirections:Array)
{
this.columns = columns.concat();
this.n = columns.length;
if (sortDirections)
{
this.sortDirections = sortDirections.concat();
this.sortDirections.length = columns.length;
}
// when any of the columns are disposed, disable the compare function
for each (var obj:ILinkableObject in columns)
getCallbackCollection(obj).addDisposeCallback(null, dispose);
}
private var columns:Array;
private var sortDirections:Array;
private var n:int;
public function compare(key1:IQualifiedKey, key2:IQualifiedKey):int
{
for (var i:int = 0; i < n; i++)
{
var column:IAttributeColumn = columns[i] as IAttributeColumn;
if (!column || (sortDirections && !sortDirections[i]))
continue;
var value1:* = column.getValueFromKey(key1, Number);
var value2:* = column.getValueFromKey(key2, Number);
var result:int = ObjectUtil.numericCompare(value1, value2);
if (result != 0)
{
if (sortDirections && sortDirections[i] < 0)
return -result;
return result;
}
}
return QKeyManager.keyCompare(key1, key2);
}
public function dispose():void
{
columns = null;
sortDirections = null;
n = 0;
}
}
|
/*
Weave (Web-based Analysis and Visualization Environment)
Copyright (C) 2008-2011 University of Massachusetts Lowell
This file is a part of Weave.
Weave is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, Version 3,
as published by the Free Software Foundation.
Weave is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Weave. If not, see <http://www.gnu.org/licenses/>.
*/
package weave.data.KeySets
{
import mx.utils.ObjectUtil;
import weave.api.core.ICallbackCollection;
import weave.api.core.ILinkableObject;
import weave.api.data.IAttributeColumn;
import weave.api.data.IKeySet;
import weave.api.data.IQualifiedKey;
import weave.api.getCallbackCollection;
import weave.api.linkableObjectIsBusy;
import weave.api.newDisposableChild;
import weave.api.registerLinkableChild;
import weave.compiler.StandardLib;
import weave.core.CallbackCollection;
import weave.data.QKeyManager;
import weave.utils.AsyncSort;
/**
* This provides the keys from an existing IKeySet in a sorted order.
* Callbacks will trigger when the sorted result changes.
*
* @author adufilie
*/
public class SortedKeySet implements IKeySet
{
public static var debug:Boolean = false;
/**
* @param keySet An IKeySet to sort.
* @param compare A function that compares two IQualifiedKey objects and returns an integer.
* @param dependencies A list of ILinkableObjects that affect the result of the compare function.
*/
public function SortedKeySet(keySet:IKeySet, keyCompare:Function = null, dependencies:Array = null)
{
_keySet = keySet;
_compare = keyCompare || QKeyManager.keyCompare;
getCallbackCollection(_asyncSort).addImmediateCallback(this, _handleSorted);
for each (var object:ILinkableObject in dependencies)
registerLinkableChild(_dependencies, object);
registerLinkableChild(_dependencies, _keySet);
_dependencies.addImmediateCallback(this, _validate, true);
if (debug)
getCallbackCollection(this).addImmediateCallback(this, _firstCallback);
}
private function _firstCallback():void { debugTrace(this,'trigger',keys.length,'keys'); }
/**
* This is the list of keys from the IKeySet, sorted.
*/
public function get keys():Array
{
if (_triggerCounter != _dependencies.triggerCounter)
_validate();
return _sortedKeys;
}
/**
* @inheritDoc
*/
public function containsKey(key:IQualifiedKey):Boolean
{
return _keySet.containsKey(key);
}
private var _triggerCounter:uint = 0;
private var _dependencies:ICallbackCollection = newDisposableChild(this, CallbackCollection);
private var _keySet:IKeySet;
private var _compare:Function;
// Note: not using newLinkableChild for _asyncSort because we do not trigger if sorting does not affect order
private var _asyncSort:AsyncSort = newDisposableChild(this, AsyncSort);
private var _sortedKeys:Array = [];
private var _prevSortedKeys:Array = [];
private function _validate():void
{
_triggerCounter = _dependencies.triggerCounter;
// if actively sorting, don't overwrite previous keys
if (!linkableObjectIsBusy(_asyncSort))
_prevSortedKeys = _sortedKeys;
// begin sorting a copy of the new keys
_sortedKeys = _keySet.keys.concat();
_asyncSort.beginSort(_sortedKeys, _compare);
}
private function _handleSorted():void
{
// only trigger callbacks if sorting changes order
if (StandardLib.arrayCompare(_prevSortedKeys, _sortedKeys) != 0)
getCallbackCollection(this).triggerCallbacks();
}
/**
* This funciton generates a compare function that will compare IQualifiedKeys based on the corresponding values in the specified columns.
* @param columns An Array of IAttributeColumns to use for comparing IQualifiedKeys.
* @param sortDirections Array of sort directions corresponding to the columns and given as integers (1=ascending, -1=descending, 0=none).
* @return A new Function that will compare two IQualifiedKeys using numeric values from the specified columns.
*/
public static function generateCompareFunction(columns:Array, sortDirections:Array = null):Function
{
return new KeyComparator(columns, sortDirections).compare;
}
}
}
import mx.utils.ObjectUtil;
import weave.api.core.ILinkableObject;
import weave.api.data.IAttributeColumn;
import weave.api.data.IQualifiedKey;
import weave.api.getCallbackCollection;
import weave.data.QKeyManager;
internal class KeyComparator
{
public function KeyComparator(columns:Array, sortDirections:Array)
{
this.columns = columns.concat();
this.n = columns.length;
if (sortDirections)
{
this.sortDirections = sortDirections.concat();
this.sortDirections.length = columns.length;
}
// when any of the columns are disposed, disable the compare function
for each (var obj:ILinkableObject in columns)
getCallbackCollection(obj).addDisposeCallback(null, dispose);
}
private var columns:Array;
private var sortDirections:Array;
private var n:int;
public function compare(key1:IQualifiedKey, key2:IQualifiedKey):int
{
for (var i:int = 0; i < n; i++)
{
var column:IAttributeColumn = columns[i] as IAttributeColumn;
if (!column || (sortDirections && !sortDirections[i]))
continue;
var value1:* = column.getValueFromKey(key1, Number);
var value2:* = column.getValueFromKey(key2, Number);
var result:int = ObjectUtil.numericCompare(value1, value2);
if (result != 0)
{
if (sortDirections && sortDirections[i] < 0)
return -result;
return result;
}
}
return QKeyManager.keyCompare(key1, key2);
}
public function dispose():void
{
columns = null;
sortDirections = null;
n = 0;
}
}
|
revert accidental change to SortedKeySet
|
revert accidental change to SortedKeySet
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
9e0f29c106cd2a41b2348b8f5a65764da852d865
|
WEB-INF/lps/lfc/kernel/swf9/LzInputTextSprite.as
|
WEB-INF/lps/lfc/kernel/swf9/LzInputTextSprite.as
|
/**
* LzInputTextSprite.as
*
* @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
*/
/**
* @shortdesc Used for input text.
*
*/
public class LzInputTextSprite extends LzTextSprite {
#passthrough (toplevel:true) {
import flash.display.InteractiveObject;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
}#
#passthrough {
function LzInputTextSprite (newowner:LzView = null, args:Object = null) {
super(newowner);
}
var enabled :Boolean = true;
var focusable :Boolean = true;
var hasFocus :Boolean = false;
override public function __initTextProperties (args:Object) :void {
super.__initTextProperties(args);
// We do not support html in input fields.
if (this.enabled) {
textfield.type = TextFieldType.INPUT;
} else {
textfield.type = TextFieldType.DYNAMIC;
}
/*
TODO [hqm 2008-01]
these handlers need to be implemented via Flash native event listenters:
focusIn , focusOut
change -- dispatched after text input is modified
textInput -- dispatched before the content is modified
Do we need to use this for intercepting when we have
a pattern restriction on input?
*/
textfield.addEventListener(Event.CHANGE , __onChanged);
//textfield.addEventListener(TextEvent.TEXT_INPUT, __onTextInput);
textfield.addEventListener(FocusEvent.FOCUS_IN , __gotFocus);
textfield.addEventListener(FocusEvent.FOCUS_OUT, __lostFocus);
this.hasFocus = false;
}
/**
* Called from LzInputText#_gotFocusEvent() after focus was set by lz.Focus
* @access private
*/
public function gotFocus () :void {
if ( this.hasFocus ) { return; }
// assign keyboard control
LFCApplication.stage.focus = this.textfield;
this.select();
this.hasFocus = true;
}
/**
* Called from LzInputText#_gotBlurEvent() after focus was cleared by lz.Focus
* @access private
*/
function gotBlur () :void {
this.hasFocus = false;
this.deselect();
if (LFCApplication.stage.focus === this.textfield) {
// remove keyboard control
LFCApplication.stage.focus = LFCApplication.stage;
}
}
function select () :void {
textfield.setSelection(0, textfield.text.length);
}
function deselect () :void {
textfield.setSelection(0, 0);
}
/**
* TODO [hqm 2008-01] I have no idea whether this comment
* still applies:
* Register for update on every frame when the text field gets the focus.
* Set the behavior of the enter key depending on whether the field is
* multiline or not.
*
* @access private
*/
function __gotFocus (event:FocusEvent) :void {
// scroll text fields horizontally back to start
if (owner) owner.inputtextevent('onfocus');
}
/**
* @access private
* TODO [hqm 2008-01] Does we still need this workaround???
*/
function __lostFocus (event:FocusEvent) :void {
// defer execution, see swf8 kernel
LzTimeKernel.setTimeout(this.__handlelostFocus, 1, event);
}
/**
* TODO [hqm 2008-01] Does this comment still apply? Do we still need this workaround???
*
* must be called after an idle event to prevent the selection from being
* cleared prematurely, e.g. before a button click. If the selection is
* cleared, the button doesn't send mouse events.
* @access private
*/
function __handlelostFocus (event:Event) :void {
if (owner) owner.inputtextevent('onblur');
}
/**
* Register to be called when the text field is modified. Convert this
* into a LFC ontext event.
* @access private
*/
function __onChanged (event:Event) :void {
this.text = this.getText();
if (owner) owner.inputtextevent('onchange', this.text);
}
/**
* Get the current text for this inputtext-sprite.
* @protected
*/
override public function getText() :String {
// We normalize swf's \r to \n
return this.textfield.text.replace(/\r/g, '\n');
}
/**
* Sets whether user can modify input text field
* @param Boolean enabled: true if the text field can be edited
*/
function setEnabled (enabled:Boolean) :void {
this.enabled = enabled;
if (enabled) {
textfield.type = 'input';
} else {
textfield.type = 'dynamic';
}
}
/**
* If a mouse event occurs in an input text field, find the focused view
*/
static function findSelection() :LzInputText {
var f:InteractiveObject = LFCApplication.stage.focus;
if (f is TextField && f.parent is LzInputTextSprite) {
return (f.parent as LzInputTextSprite).owner;
}
return null;
}
}# // #passthrough
} // End of LzInputTextSprite
|
/**
* LzInputTextSprite.as
*
* @copyright Copyright 2001-2009 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
*/
/**
* @shortdesc Used for input text.
*
*/
public class LzInputTextSprite extends LzTextSprite {
#passthrough (toplevel:true) {
import flash.display.InteractiveObject;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.text.TextField;
import flash.text.TextFieldType;
}#
#passthrough {
function LzInputTextSprite (newowner:LzView = null, args:Object = null) {
super(newowner);
}
var enabled :Boolean = true;
var focusable :Boolean = true;
var hasFocus :Boolean = false;
override public function __initTextProperties (args:Object) :void {
super.__initTextProperties(args);
// We do not support html in input fields.
this.html = false;
if (this.enabled) {
textfield.type = TextFieldType.INPUT;
} else {
textfield.type = TextFieldType.DYNAMIC;
}
/*
TODO [hqm 2008-01]
these handlers need to be implemented via Flash native event listenters:
focusIn , focusOut
change -- dispatched after text input is modified
textInput -- dispatched before the content is modified
Do we need to use this for intercepting when we have
a pattern restriction on input?
*/
textfield.addEventListener(Event.CHANGE , __onChanged);
//textfield.addEventListener(TextEvent.TEXT_INPUT, __onTextInput);
textfield.addEventListener(FocusEvent.FOCUS_IN , __gotFocus);
textfield.addEventListener(FocusEvent.FOCUS_OUT, __lostFocus);
this.hasFocus = false;
}
/**
* Called from LzInputText#_gotFocusEvent() after focus was set by lz.Focus
* @access private
*/
public function gotFocus () :void {
if ( this.hasFocus ) { return; }
// assign keyboard control
LFCApplication.stage.focus = this.textfield;
this.select();
this.hasFocus = true;
}
/**
* Called from LzInputText#_gotBlurEvent() after focus was cleared by lz.Focus
* @access private
*/
function gotBlur () :void {
this.hasFocus = false;
this.deselect();
if (LFCApplication.stage.focus === this.textfield) {
// remove keyboard control
LFCApplication.stage.focus = LFCApplication.stage;
}
}
function select () :void {
textfield.setSelection(0, textfield.text.length);
}
function deselect () :void {
textfield.setSelection(0, 0);
}
/**
* TODO [hqm 2008-01] I have no idea whether this comment
* still applies:
* Register for update on every frame when the text field gets the focus.
* Set the behavior of the enter key depending on whether the field is
* multiline or not.
*
* @access private
*/
function __gotFocus (event:FocusEvent) :void {
// scroll text fields horizontally back to start
if (owner) owner.inputtextevent('onfocus');
}
/**
* @access private
* TODO [hqm 2008-01] Does we still need this workaround???
*/
function __lostFocus (event:FocusEvent) :void {
// defer execution, see swf8 kernel
LzTimeKernel.setTimeout(this.__handlelostFocus, 1, event);
}
/**
* TODO [hqm 2008-01] Does this comment still apply? Do we still need this workaround???
*
* must be called after an idle event to prevent the selection from being
* cleared prematurely, e.g. before a button click. If the selection is
* cleared, the button doesn't send mouse events.
* @access private
*/
function __handlelostFocus (event:Event) :void {
if (owner) owner.inputtextevent('onblur');
}
/**
* Register to be called when the text field is modified. Convert this
* into a LFC ontext event.
* @access private
*/
function __onChanged (event:Event) :void {
this.text = this.getText();
if (owner) owner.inputtextevent('onchange', this.text);
}
/**
* Get the current text for this inputtext-sprite.
* @protected
*/
override public function getText() :String {
// We normalize swf's \r to \n
return this.textfield.text.replace(/\r/g, '\n');
}
/**
* Sets whether user can modify input text field
* @param Boolean enabled: true if the text field can be edited
*/
function setEnabled (enabled:Boolean) :void {
this.enabled = enabled;
if (enabled) {
textfield.type = 'input';
} else {
textfield.type = 'dynamic';
}
}
/**
* If a mouse event occurs in an input text field, find the focused view
*/
static function findSelection() :LzInputText {
var f:InteractiveObject = LFCApplication.stage.focus;
if (f is TextField && f.parent is LzInputTextSprite) {
return (f.parent as LzInputTextSprite).owner;
}
return null;
}
}# // #passthrough
} // End of LzInputTextSprite
|
Change 20090406-bargull-ybS by bargull@dell--p4--2-53 on 2009-04-06 00:42:09 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20090406-bargull-ybS by bargull@dell--p4--2-53 on 2009-04-06 00:42:09
in /home/Admin/src/svn/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: inputtext shouldn't be in html-mode by default
New Features:
Bugs Fixed: LPP-8026 (SWF9: edittext/inputtext is in html-mode)
Technical Reviewer: max
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
Set html-flag to false for compatibility with swf8 and dhtml.
Tests:
testcase from bugreport
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@13609 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
42da9fdf16f0def59ca10d3b3d55e9f2bf8e079b
|
as3/smartform/src/com/rpath/raf/util/UIHelper.as
|
as3/smartform/src/com/rpath/raf/util/UIHelper.as
|
/*
#
# Copyright (c) 2005-2009 rPath, Inc.
#
# All rights reserved
#
*/
/*
#
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
*/
package com.rpath.raf.util
{
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import spark.components.Application;
import mx.core.FlexGlobals;
import mx.core.IFlexDisplayObject;
import mx.formatters.NumberBaseRoundType;
import mx.formatters.NumberFormatter;
import mx.managers.PopUpManager;
import mx.managers.PopUpManagerChildList;
public class UIHelper
{
public static function checkBooleans(...args):Boolean
{
for each (var b:* in args)
{
if (b is Array || b is ArrayCollection)
{
for each (var c:* in b)
{
// allow for nested arrays
checkBooleans(c);
}
}
else
{
if (!b)
return false;
}
}
return true;
}
public static function checkOneOf(...args):Boolean
{
for each (var b:* in args)
{
if (b)
return true;
}
return false;
}
public static function formattedDate(unixTimestamp:Number):String
{
if (isNaN(unixTimestamp))
return "";
var date:Date = new Date(unixTimestamp * 1000);
/*
* Note that we add 1 to month b/c January is 0 in Flex
*/
return padLeft(date.getMonth() +1) + "/" + padLeft(date.getDate()) +
"/" + padLeft(date.getFullYear()) + " " + padLeft(date.getHours()) +
":" + padLeft(date.getMinutes()) + ":" + padLeft(date.getSeconds());
}
private static function padLeft(number:Number):String
{
var strNum:String = number.toString();
if (number.toString().length == 1)
strNum = "0" + strNum;
return strNum;
}
/**
* Replace \r\n with \n, replace \r with \n
*/
public static function processCarriageReturns(value:String):String
{
if (!value)
return value;
var cr:String = String.fromCharCode(13);
var crRegex:RegExp = new RegExp(cr, "gm");
var crnl:String = String.fromCharCode(13, 10);
var crnlRegex:RegExp = new RegExp(crnl, "gm");
// process CRNL first
value = value.replace(crnlRegex, '\n');
// process CR
value = value.replace(crRegex, '\n');
return value;
}
private static var popupModelMap:Dictionary = new Dictionary(true);
private static var popupOwnerMap:Dictionary = new Dictionary(true);
public static function createPopup(clazz:Class):*
{
var popup:Object = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application,
clazz, false, PopUpManagerChildList.APPLICATION) as clazz;
return popup as IFlexDisplayObject;
}
public static function createSingletonPopupForModel(clazz:Class, model:Object, owner:Object=null):*
{
var popup:Object;
popup = popupForModel(model);
if (popup == null)
{
popup = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application,
clazz, false, PopUpManagerChildList.APPLICATION) as clazz;
popupModelMap[model] = popup;
if (owner)
{
popupOwnerMap[popup] = owner;
}
}
return popup as IFlexDisplayObject;
}
public static function popupForModel(model:Object):*
{
return popupModelMap[model];
}
public static function removePopupForModel(model:Object):void
{
var popup:IFlexDisplayObject = popupModelMap[model];
if (popup)
{
delete popupModelMap[model];
delete popupOwnerMap[popup];
}
}
public static function removePopupsForOwner(owner:Object):void
{
for (var popup:* in popupOwnerMap)
{
if (popupOwnerMap[popup] === owner)
{
delete popupOwnerMap[popup];
// scan the model map too
for (var model:* in popupModelMap)
{
if (popupModelMap[model] === popup)
{
delete popupModelMap[model];
}
}
}
}
}
public static function popupsForOwner(owner:Object):Array
{
var result:Array = [];
for (var popup:* in popupOwnerMap)
{
if (popupOwnerMap[popup] === owner)
{
result.push(popup);
}
}
return result;
}
public static function closePopupsForOwner(owner:Object):void
{
for each (var popup:* in UIHelper.popupsForOwner(owner))
{
PopUpManager.removePopUp(popup);
}
removePopupsForOwner(owner);
}
// make bytes human readable
public static function humanReadableSize(bytes:int, precision:int=1):String
{
var s:String = bytes + ' bytes';
var nf:NumberFormatter = new NumberFormatter();
nf.precision = precision;
nf.useThousandsSeparator = true;
nf.useNegativeSign = true;
nf.rounding = NumberBaseRoundType.NEAREST;
if (bytes > 1073741824)
{
s = nf.format((bytes / 1073741824.0)) + ' GB' + ' (' + (s) + ')';
}
else if (bytes > 1048576)
{
s = nf.format((bytes / 1048576.0)) + ' MB' + ' (' + (s) + ')';
}
else if (bytes > 1024)
{
s = nf.format((bytes / 1024.0)) + ' KB' + ' (' + (s) + ')';
}
return s;
}
}
}
|
/*
#
# Copyright (c) 2005-2009 rPath, Inc.
#
# All rights reserved
#
*/
/*
#
# Copyright (c) 2009 rPath, Inc.
#
# This program is distributed under the terms of the MIT License as found
# in a file called LICENSE. If it is not present, the license
# is always available at http://www.opensource.org/licenses/mit-license.php.
#
# This program is distributed in the hope that it will be useful, but
# without any waranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
*/
package com.rpath.raf.util
{
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import spark.components.Application;
import mx.core.FlexGlobals;
import mx.core.IFlexDisplayObject;
import mx.formatters.NumberBaseRoundType;
import mx.formatters.NumberFormatter;
import mx.managers.PopUpManager;
import mx.managers.PopUpManagerChildList;
public class UIHelper
{
public static function checkBooleans(...args):Boolean
{
for each (var b:* in args)
{
if (b is Array || b is ArrayCollection)
{
for each (var c:* in b)
{
// allow for nested arrays
checkBooleans(c);
}
}
else
{
if (!b)
return false;
}
}
return true;
}
public static function checkOneOf(...args):Boolean
{
for each (var b:* in args)
{
if (b)
return true;
}
return false;
}
public static function formattedDate(unixTimestamp:Number):String
{
if (isNaN(unixTimestamp))
return "";
var date:Date = new Date(unixTimestamp * 1000);
/*
* Note that we add 1 to month b/c January is 0 in Flex
*/
return padLeft(date.getMonth() +1) + "/" + padLeft(date.getDate()) +
"/" + padLeft(date.getFullYear()) + " " + padLeft(date.getHours()) +
":" + padLeft(date.getMinutes()) + ":" + padLeft(date.getSeconds());
}
public static function padLeft(number:Number):String
{
var strNum:String = number.toString();
if (number.toString().length == 1)
strNum = "0" + strNum;
return strNum;
}
/**
* Replace \r\n with \n, replace \r with \n
*/
public static function processCarriageReturns(value:String):String
{
if (!value)
return value;
var cr:String = String.fromCharCode(13);
var crRegex:RegExp = new RegExp(cr, "gm");
var crnl:String = String.fromCharCode(13, 10);
var crnlRegex:RegExp = new RegExp(crnl, "gm");
// process CRNL first
value = value.replace(crnlRegex, '\n');
// process CR
value = value.replace(crRegex, '\n');
return value;
}
private static var popupModelMap:Dictionary = new Dictionary(true);
private static var popupOwnerMap:Dictionary = new Dictionary(true);
public static function createPopup(clazz:Class):*
{
var popup:Object = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application,
clazz, false, PopUpManagerChildList.APPLICATION) as clazz;
return popup as IFlexDisplayObject;
}
public static function createSingletonPopupForModel(clazz:Class, model:Object, owner:Object=null):*
{
var popup:Object;
popup = popupForModel(model);
if (popup == null)
{
popup = PopUpManager.createPopUp(FlexGlobals.topLevelApplication as Application,
clazz, false, PopUpManagerChildList.APPLICATION) as clazz;
popupModelMap[model] = popup;
if (owner)
{
popupOwnerMap[popup] = owner;
}
}
return popup as IFlexDisplayObject;
}
public static function popupForModel(model:Object):*
{
return popupModelMap[model];
}
public static function removePopupForModel(model:Object):void
{
var popup:IFlexDisplayObject = popupModelMap[model];
if (popup)
{
delete popupModelMap[model];
delete popupOwnerMap[popup];
}
}
public static function removePopupsForOwner(owner:Object):void
{
for (var popup:* in popupOwnerMap)
{
if (popupOwnerMap[popup] === owner)
{
delete popupOwnerMap[popup];
// scan the model map too
for (var model:* in popupModelMap)
{
if (popupModelMap[model] === popup)
{
delete popupModelMap[model];
}
}
}
}
}
public static function popupsForOwner(owner:Object):Array
{
var result:Array = [];
for (var popup:* in popupOwnerMap)
{
if (popupOwnerMap[popup] === owner)
{
result.push(popup);
}
}
return result;
}
public static function closePopupsForOwner(owner:Object):void
{
for each (var popup:* in UIHelper.popupsForOwner(owner))
{
PopUpManager.removePopUp(popup);
}
removePopupsForOwner(owner);
}
// make bytes human readable
public static function humanReadableSize(bytes:int, precision:int=1):String
{
var s:String = bytes + ' bytes';
var nf:NumberFormatter = new NumberFormatter();
nf.precision = precision;
nf.useThousandsSeparator = true;
nf.useNegativeSign = true;
nf.rounding = NumberBaseRoundType.NEAREST;
if (bytes > 1073741824)
{
s = nf.format((bytes / 1073741824.0)) + ' GB' + ' (' + (s) + ')';
}
else if (bytes > 1048576)
{
s = nf.format((bytes / 1048576.0)) + ' MB' + ' (' + (s) + ')';
}
else if (bytes > 1024)
{
s = nf.format((bytes / 1024.0)) + ' KB' + ' (' + (s) + ')';
}
return s;
}
}
}
|
make UIHelper.padLeft public
|
make UIHelper.padLeft public
|
ActionScript
|
apache-2.0
|
sassoftware/smartform
|
20a9685cc4ed3b98df16d1004b008c9695975cdf
|
src/as/com/threerings/mx/controls/CommandMenu.as
|
src/as/com/threerings/mx/controls/CommandMenu.as
|
package com.threerings.mx.controls {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.geom.Rectangle;
import mx.controls.Menu;
import mx.core.mx_internal;
import mx.events.MenuEvent;
import com.threerings.mx.events.CommandEvent;
/**
* A pretty standard menu that can submit CommandEvents if menu items
* have "command" and possibly "arg" properties.
*
* Example dataProvider array:
* [ { label: "Go home", icon: homeIconClass,
* command: Controller.GO_HOME, arg: homeId },
* { type: "separator"},
* { label: "Other places", children: subMenuArray }
* ];
*
* See "Defining menu structure and data" in the Flex manual for the
* full list.
*/
public class CommandMenu extends Menu
{
public function CommandMenu ()
{
super();
addEventListener(MenuEvent.ITEM_CLICK, itemClicked);
}
/**
* Factory method to create a command menu.
*
* @param parent The parent of this menu.
* @param items an array of menu items.
*/
public static function createMenu (
parent :DisplayObjectContainer, items :Array) :CommandMenu
{
var menu :CommandMenu = new CommandMenu();
menu.tabEnabled = false;
menu.showRoot = true;
Menu.popUpMenu(menu, parent, items);
return menu;
}
/**
* Actually pop up the menu. This can be used instead of show().
*/
public function popUp (
trigger :DisplayObject, popUpwards :Boolean = true) :void
{
var r :Rectangle = trigger.getBounds(trigger.stage);
if (popUpwards) {
show(r.x, 0);
// then, reposition the y once we know our size
y = r.y - getExplicitOrMeasuredHeight();
} else {
// simply position it below the trigger
show(r.x, r.y + r.height);
}
}
/**
* Callback for MenuEvent.ITEM_CLICK.
*/
protected function itemClicked (event :MenuEvent) :void
{
var cmd :String = getItemCommand(event.item);
if (cmd != null) {
event.stopImmediatePropagation();
var arg :Object = getItemArgument(event.item);
CommandEvent.dispatch(mx_internal::parentDisplayObject, cmd, arg);
}
}
/**
* Get the command for the specified item, if any.
* Somewhat similar to bits in the DefaultDataDescriptor.
*/
protected function getItemCommand (item :Object) :String
{
try {
if (item is XML) {
return String(item.@command);
} else if (item is Object) {
return String(item.command);
}
} catch (e :Error) {
// fall through
}
return null;
}
/**
* Get the command for the specified item, if any.
* Somewhat similar to bits in the DefaultDataDescriptor.
*/
protected function getItemArgument (item :Object) :Object
{
try {
if (item is XML) {
return item.@arg;
} else if (item is Object) {
return item.arg;
}
} catch (e :Error) {
// fall through
}
return null;
}
}
}
|
package com.threerings.mx.controls {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.geom.Rectangle;
import mx.controls.Menu;
import mx.core.mx_internal;
import mx.core.ScrollPolicy;
import mx.events.MenuEvent;
import com.threerings.mx.events.CommandEvent;
/**
* A pretty standard menu that can submit CommandEvents if menu items
* have "command" and possibly "arg" properties. Commands are submitted to
* controllers for processing. Alternatively, you may specify
* "callback" properties that specify a function closure to call, with the
* "arg" property containing either a single arg or an array of args.
*
* Example dataProvider array:
* [ { label: "Go home", icon: homeIconClass,
* command: Controller.GO_HOME, arg: homeId },
* { type: "separator"},
{ label: "Crazytown", callback: setCrazy, arg: [ true, false ] },
* { label: "Other places", children: subMenuArray }
* ];
*
* See "Defining menu structure and data" in the Flex manual for the
* full list.
*/
public class CommandMenu extends Menu
{
public function CommandMenu ()
{
super();
addEventListener(MenuEvent.ITEM_CLICK, itemClicked);
// addEventListener(MenuEvent.MENU_SHOW, handleMenuShown);
}
/**
* Factory method to create a command menu.
*
* @param parent The parent of this menu.
* @param items an array of menu items.
*/
public static function createMenu (
parent :DisplayObjectContainer, items :Array) :CommandMenu
{
var menu :CommandMenu = new CommandMenu();
menu.tabEnabled = false;
menu.showRoot = true;
Menu.popUpMenu(menu, parent, items);
return menu;
}
/**
* Actually pop up the menu. This can be used instead of show().
*/
public function popUp (
trigger :DisplayObject, popUpwards :Boolean = true) :void
{
var r :Rectangle = trigger.getBounds(trigger.stage);
if (popUpwards) {
show(r.x, 0);
// then, reposition the y once we know our size
y = r.y - getExplicitOrMeasuredHeight();
} else {
// simply position it below the trigger
show(r.x, r.y + r.height);
}
}
/**
* Callback for MenuEvent.ITEM_CLICK.
*/
protected function itemClicked (event :MenuEvent) :void
{
var arg :Object = getItemArgument(event.item);
var cmd :String = getItemCommand(event.item);
var fn :Function;
if (cmd == null) {
fn = getItemCallback(event.item);
}
if (cmd != null || fn != null) {
event.stopImmediatePropagation();
if (cmd != null) {
CommandEvent.dispatch(mx_internal::parentDisplayObject, cmd, arg);
} else {
try {
var args :Array = (arg as Array);
if (args == null && arg != null) {
args = [ arg ];
}
fn.apply(null, args);
} catch (err :Error) {
Log.getLog(this).warning("Unable to call menu callback: " +
event.item);
}
}
}
}
// /**
// * Callback for MenuEvent.MENU_SHOW.
// */
// protected function handleMenuShown (event :MenuEvent) :void
// {
// // just ensure that every menu can scroll
// event.menu.verticalScrollPolicy = ScrollPolicy.ON;
// }
/**
* Get the command for the specified item, if any.
* Somewhat similar to bits in the DefaultDataDescriptor.
*/
protected function getItemCommand (item :Object) :String
{
try {
if (item is XML) {
return (item.@command as String);
} else if (item is Object) {
return (item.command as String);
}
} catch (e :Error) {
// fall through
}
return null;
}
/**
* Get the callback function for the specified item, if any.
*/
protected function getItemCallback (item :Object) :Function
{
try {
if (item is XML) {
return (item.@callback as Function);
} else if (item is Object) {
return (item.callback as Function);
}
} catch (e :Error) {
// fall through
}
return null;
}
/**
* Get the command for the specified item, if any.
* Somewhat similar to bits in the DefaultDataDescriptor.
*/
protected function getItemArgument (item :Object) :Object
{
try {
if (item is XML) {
return item.@arg;
} else if (item is Object) {
return item.arg;
}
} catch (e :Error) {
// fall through
}
return null;
}
}
}
|
Allow menu items to be configured with a callback function directly (to which any args will be passed), instead of only dispatching controller commands.
|
Allow menu items to be configured with a callback function directly
(to which any args will be passed), instead of only dispatching
controller commands.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4465 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
05cdd13bc4de681e2f14c177c8147cfd1349563b
|
src/org/jivesoftware/xiff/core/XMPPBOSHConnection.as
|
src/org/jivesoftware/xiff/core/XMPPBOSHConnection.as
|
package org.jivesoftware.xiff.core
{
import flash.events.ErrorEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.jivesoftware.xiff.auth.Anonymous;
import org.jivesoftware.xiff.auth.External;
import org.jivesoftware.xiff.auth.Plain;
import org.jivesoftware.xiff.auth.SASLAuth;
import org.jivesoftware.xiff.data.IQ;
import org.jivesoftware.xiff.data.bind.BindExtension;
import org.jivesoftware.xiff.data.session.SessionExtension;
import org.jivesoftware.xiff.events.ConnectionSuccessEvent;
import org.jivesoftware.xiff.events.IncomingDataEvent;
import org.jivesoftware.xiff.events.LoginEvent;
import org.jivesoftware.xiff.events.XIFFErrorEvent;
import org.jivesoftware.xiff.util.Callback;
public class XMPPBOSHConnection extends XMPPConnection
{
private static var saslMechanisms:Object = {
"PLAIN":Plain,
"ANONYMOUS":Anonymous,
"EXTERNAL":External
};
private var maxConcurrentRequests:uint = 2;
private var boshVersion:Number = 1.6;
private var headers:Object = {
"post": [],
"get": ['Cache-Control', 'no-store', 'Cache-Control', 'no-cache', 'Pragma', 'no-cache']
};
private var requestCount:int = 0;
private var failedRequests:Array = [];
private var requestQueue:Array = [];
private var responseQueue:Array = [];
private const responseTimer:Timer = new Timer(0.0, 1);
private var isDisconnecting:Boolean = false;
private var boshPollingInterval:Number = 10000;
private var sid:String;
private var rid:Number;
private var wait:int;
private var inactivity:int;
private var pollTimer:Timer;
private var isCurrentlyPolling:Boolean = false;
private var auth:SASLAuth;
private var authHandler:Function;
private var https:Boolean = false;
private var _port:Number = -1;
private var callbacks:Object = {};
public static var logger:Object = null;
public override function connect(streamType:String=null):Boolean
{
if(logger)
logger.log("CONNECT()", "INFO");
BindExtension.enable();
active = false;
loggedIn = false;
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
hold: maxConcurrentRequests,
rid: nextRID,
secure: https,
wait: 10,
ver: boshVersion
}
var result:XMLNode = new XMLNode(1, "body");
result.attributes = attrs;
sendRequests(result);
return true;
}
public static function registerSASLMechanism(name:String, authClass:Class):void
{
saslMechanisms[name] = authClass;
}
public static function disableSASLMechanism(name:String):void
{
saslMechanisms[name] = null;
}
public function set secure(flag:Boolean):void
{
https = flag;
}
public override function set port(portnum:Number):void
{
_port = portnum;
}
public override function get port():Number
{
if(_port == -1)
return https ? 8483 : 8080;
return _port;
}
public function get httpServer():String
{
return (https ? "https" : "http") + "://" + server + ":" + port + "/http-bind/";
}
public override function disconnect():void
{
super.disconnect();
pollTimer.stop();
pollTimer = null;
}
public function processConnectionResponse(responseBody:XMLNode):void
{
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
boshPollingInterval = attributes.polling * 1000;
// if we have a polling interval of 1, we want to add an extra second for a little bit of
// padding.
if(boshPollingInterval <= 1000 && boshPollingInterval > 0)
boshPollingInterval += 1000;
wait = attributes.wait;
inactivity = attributes.inactivity;
var serverRequests:int = attributes.requests;
if (serverRequests)
maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests);
active = true;
configureConnection(responseBody);
responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse);
pollTimer = new Timer(boshPollingInterval, 1);
pollTimer.addEventListener(TimerEvent.TIMER, pollServer);
}
private function processResponse(event:TimerEvent=null):void
{
// Read the data and send it to the appropriate parser
var currentNode:XMLNode = responseQueue.shift();
var nodeName:String = currentNode.nodeName.toLowerCase();
switch( nodeName )
{
case "stream:features":
//we already handled this in httpResponse()
break;
case "stream:error":
handleStreamError( currentNode );
break;
case "iq":
handleIQ( currentNode );
break;
case "message":
handleMessage( currentNode );
break;
case "presence":
handlePresence( currentNode );
break;
case "success":
handleAuthentication( currentNode );
break;
default:
dispatchError( "undefined-condition", "Unknown Error", "modify", 500 );
break;
}
resetResponseProcessor();
}
private function resetResponseProcessor():void
{
if(responseQueue.length > 0)
{
responseTimer.reset();
responseTimer.start();
}
}
private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:ResultEvent):void
{
requestCount--;
var rawXML:String = evt.result as String;
if(logger)
logger.log(rawXML, "INCOMING");
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML( rawXML );
var bodyNode:XMLNode = xmlData.firstChild;
var event:IncomingDataEvent = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent( event );
if(bodyNode.attributes["type"] == "terminal")
{
dispatchError( "BOSH Error", bodyNode.attributes["condition"], "", -1 );
active = false;
}
for each(var childNode:XMLNode in bodyNode.childNodes)
{
if(childNode.nodeName == "stream:features")
{
_expireTagSearch = false;
processConnectionResponse( bodyNode );
}
else
responseQueue.push(childNode);
}
resetResponseProcessor();
//if we just processed a poll response, we're no longer in mid-poll
if(isPollResponse)
isCurrentlyPolling = false;
//if we have queued requests we want to send them before attempting to poll again
//otherwise, if we don't already have a countdown going for the next poll, start one
if (!sendQueuedRequests() && (!pollTimer || !pollTimer.running))
resetPollTimer();
}
private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void
{
active = false;
dispatchError("Unknown HTTP Error", evt.fault.rootCause.text, "", -1);
}
protected override function sendXML(body:*):void
{
sendQueuedRequests(body);
}
private function sendQueuedRequests(body:*=null):Boolean
{
if(body)
requestQueue.push(body);
else if(requestQueue.length == 0)
return false;
return sendRequests();
}
//returns true if any requests were sent
private function sendRequests(data:XMLNode = null, isPoll:Boolean=false):Boolean
{
if(requestCount >= maxConcurrentRequests)
return false;
if(isPoll)
trace("Polling at: " + new Date().getSeconds());
requestCount++;
if(!data)
{
if(isPoll)
{
data = createRequest();
}
else
{
var temp:Array = [];
for(var i:uint = 0; i < 10 && requestQueue.length > 0; i++)
{
temp.push(requestQueue.shift());
}
data = createRequest(temp);
}
}
//build the http request
var request:HTTPService = new HTTPService();
request.method = "post";
request.headers = headers[request.method];
request.url = httpServer;
request.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
request.contentType = "text/xml";
var responseCallback:Callback = new Callback(this, httpResponse, data, isPoll);
var errorCallback:Callback = new Callback(this, httpError, data, isPoll);
request.addEventListener(ResultEvent.RESULT, responseCallback.call, false);
request.addEventListener(FaultEvent.FAULT, errorCallback.call, false);
if(logger)
logger.log(data, "OUTGOING");
request.send(data);
resetPollTimer();
return true;
}
private function resetPollTimer():void
{
if(!pollTimer)
return;
pollTimer.reset();
pollTimer.start();
}
private function pollServer(evt:TimerEvent):void
{
//We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress
if(!isActive() || sendQueuedRequests() || isCurrentlyPolling)
return;
//this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests()
isCurrentlyPolling = sendRequests(null, true);
}
private function get nextRID():Number {
if(!rid)
rid = Math.floor(Math.random() * 1000000);
return ++rid;
}
private function createRequest(bodyContent:Array=null):XMLNode {
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
rid: nextRID,
sid: sid
}
var req:XMLNode = new XMLNode(1, "body");
if(bodyContent)
for each(var content:XMLNode in bodyContent)
req.appendChild(content);
req.attributes = attrs;
return req;
}
private function handleAuthentication(responseBody:XMLNode):void
{
// if(!response || response.length == 0) {
// return;
// }
var status:Object = auth.handleResponse(0, responseBody);
if (status.authComplete) {
if (status.authSuccess) {
bindConnection();
}
else {
dispatchEvent(new ErrorEvent(ErrorEvent.ERROR));
disconnect();
}
}
}
private function configureConnection(responseBody:XMLNode):void
{
var features:XMLNode = responseBody.firstChild;
var authentication:Object = {};
for each(var feature:XMLNode in features.childNodes)
{
if (feature.nodeName == "mechanisms")
authentication.auth = configureAuthMechanisms(feature);
else if (feature.nodeName == "bind")
authentication.bind = true;
else if (feature.nodeName == "session")
authentication.session = true;
}
auth = authentication.auth;
dispatchEvent(new ConnectionSuccessEvent());
authHandler = handleAuthentication;
sendXML(auth.request);
}
private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth
{
var authMechanism:SASLAuth;
var authClass:Class;
for each(var mechanism:XMLNode in mechanisms.childNodes)
{
authClass = saslMechanisms[mechanism.firstChild.nodeValue];
if(authClass)
break;
}
if (!authClass) {
dispatchError("SASL missing", "The server is not configured to support any available SASL mechanisms", "SASL", -1);
return null;
}
return new authClass(this);
}
public function handleBindResponse(packet:IQ):void
{
var bind:BindExtension = packet.getExtension("bind") as BindExtension;
var jid:String = bind.getJID();
var parts:Array = jid.split("/");
myResource = parts[1];
parts = parts[0].split("@");
myUsername = parts[0];
domain = parts[1];
establishSession();
}
private function bindConnection():void
{
var bindIQ:IQ = new IQ(null, "set");
var bindExt:BindExtension = new BindExtension();
if(resource)
bindExt.resource = resource;
bindIQ.addExtension(bindExt);
//this is laaaaaame, it should be a function
bindIQ.callbackName = "handleBindResponse";
bindIQ.callbackScope = this;
send(bindIQ);
}
public function handleSessionResponse(packet:IQ):void
{
dispatchEvent(new LoginEvent());
}
private function establishSession():void
{
var sessionIQ:IQ = new IQ(null, "set");
sessionIQ.addExtension(new SessionExtension());
sessionIQ.callbackName = "handleSessionResponse";
sessionIQ.callbackScope = this;
send(sessionIQ);
}
//do nothing, we use polling instead
public override function sendKeepAlive():void {}
}
}
|
package org.jivesoftware.xiff.core
{
import flash.events.ErrorEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.xml.XMLDocument;
import flash.xml.XMLNode;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;
import org.jivesoftware.xiff.auth.Anonymous;
import org.jivesoftware.xiff.auth.External;
import org.jivesoftware.xiff.auth.Plain;
import org.jivesoftware.xiff.auth.SASLAuth;
import org.jivesoftware.xiff.data.IQ;
import org.jivesoftware.xiff.data.bind.BindExtension;
import org.jivesoftware.xiff.data.session.SessionExtension;
import org.jivesoftware.xiff.events.ConnectionSuccessEvent;
import org.jivesoftware.xiff.events.IncomingDataEvent;
import org.jivesoftware.xiff.events.LoginEvent;
import org.jivesoftware.xiff.events.XIFFErrorEvent;
import org.jivesoftware.xiff.util.Callback;
public class XMPPBOSHConnection extends XMPPConnection
{
private static var saslMechanisms:Object = {
"PLAIN":Plain,
"ANONYMOUS":Anonymous,
"EXTERNAL":External
};
private var maxConcurrentRequests:uint = 2;
private var boshVersion:Number = 1.6;
private var headers:Object = {
"post": [],
"get": ['Cache-Control', 'no-store', 'Cache-Control', 'no-cache', 'Pragma', 'no-cache']
};
private var requestCount:int = 0;
private var failedRequests:Array = [];
private var requestQueue:Array = [];
private var responseQueue:Array = [];
private const responseTimer:Timer = new Timer(0.0, 1);
private var isDisconnecting:Boolean = false;
private var boshPollingInterval:Number = 10000;
private var sid:String;
private var rid:Number;
private var wait:int;
private var inactivity:int;
private var pollTimer:Timer;
private var isCurrentlyPolling:Boolean = false;
private var auth:SASLAuth;
private var authHandler:Function;
private var https:Boolean = false;
private var _port:Number = -1;
private var callbacks:Object = {};
public static var logger:Object = null;
public override function connect(streamType:String=null):Boolean
{
if(logger)
logger.log("CONNECT()", "INFO");
BindExtension.enable();
active = false;
loggedIn = false;
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
hold: maxConcurrentRequests,
rid: nextRID,
secure: https,
wait: 10,
ver: boshVersion
}
var result:XMLNode = new XMLNode(1, "body");
result.attributes = attrs;
sendRequests(result);
return true;
}
public static function registerSASLMechanism(name:String, authClass:Class):void
{
saslMechanisms[name] = authClass;
}
public static function disableSASLMechanism(name:String):void
{
saslMechanisms[name] = null;
}
public function set secure(flag:Boolean):void
{
https = flag;
}
public override function set port(portnum:Number):void
{
_port = portnum;
}
public override function get port():Number
{
if(_port == -1)
return https ? 8483 : 8080;
return _port;
}
public function get httpServer():String
{
return (https ? "https" : "http") + "://" + server + ":" + port + "/http-bind/";
}
public override function disconnect():void
{
super.disconnect();
pollTimer.stop();
pollTimer = null;
}
public function processConnectionResponse(responseBody:XMLNode):void
{
var attributes:Object = responseBody.attributes;
sid = attributes.sid;
boshPollingInterval = attributes.polling * 1000;
wait = attributes.wait;
inactivity = attributes.inactivity * 1000;
if(inactivity - 2000 >= boshPollingInterval || (boshPollingInterval <= 1000 && boshPollingInterval > 0))
{
boshPollingInterval += 1000;
}
var serverRequests:int = attributes.requests;
if (serverRequests)
maxConcurrentRequests = Math.min(serverRequests, maxConcurrentRequests);
active = true;
configureConnection(responseBody);
responseTimer.addEventListener(TimerEvent.TIMER_COMPLETE, processResponse);
pollTimer = new Timer(boshPollingInterval, 1);
pollTimer.addEventListener(TimerEvent.TIMER, pollServer);
}
private function processResponse(event:TimerEvent=null):void
{
// Read the data and send it to the appropriate parser
var currentNode:XMLNode = responseQueue.shift();
var nodeName:String = currentNode.nodeName.toLowerCase();
switch( nodeName )
{
case "stream:features":
//we already handled this in httpResponse()
break;
case "stream:error":
handleStreamError( currentNode );
break;
case "iq":
handleIQ( currentNode );
break;
case "message":
handleMessage( currentNode );
break;
case "presence":
handlePresence( currentNode );
break;
case "success":
handleAuthentication( currentNode );
break;
default:
dispatchError( "undefined-condition", "Unknown Error", "modify", 500 );
break;
}
resetResponseProcessor();
}
private function resetResponseProcessor():void
{
if(responseQueue.length > 0)
{
responseTimer.reset();
responseTimer.start();
}
}
private function httpResponse(req:XMLNode, isPollResponse:Boolean, evt:ResultEvent):void
{
requestCount--;
var rawXML:String = evt.result as String;
if(logger)
logger.log(rawXML, "INCOMING");
var xmlData:XMLDocument = new XMLDocument();
xmlData.ignoreWhite = this.ignoreWhite;
xmlData.parseXML( rawXML );
var bodyNode:XMLNode = xmlData.firstChild;
var event:IncomingDataEvent = new IncomingDataEvent();
event.data = xmlData;
dispatchEvent( event );
if(bodyNode.attributes["type"] == "terminal")
{
dispatchError( "BOSH Error", bodyNode.attributes["condition"], "", -1 );
active = false;
}
for each(var childNode:XMLNode in bodyNode.childNodes)
{
if(childNode.nodeName == "stream:features")
{
_expireTagSearch = false;
processConnectionResponse( bodyNode );
}
else
responseQueue.push(childNode);
}
resetResponseProcessor();
//if we just processed a poll response, we're no longer in mid-poll
if(isPollResponse)
isCurrentlyPolling = false;
//if we have queued requests we want to send them before attempting to poll again
//otherwise, if we don't already have a countdown going for the next poll, start one
if (!sendQueuedRequests() && (!pollTimer || !pollTimer.running))
resetPollTimer();
}
private function httpError(req:XMLNode, isPollResponse:Boolean, evt:FaultEvent):void
{
active = false;
dispatchError("Unknown HTTP Error", evt.fault.rootCause.text, "", -1);
}
protected override function sendXML(body:*):void
{
sendQueuedRequests(body);
}
private function sendQueuedRequests(body:*=null):Boolean
{
if(body)
requestQueue.push(body);
else if(requestQueue.length == 0)
return false;
return sendRequests();
}
//returns true if any requests were sent
private function sendRequests(data:XMLNode = null, isPoll:Boolean=false):Boolean
{
if(requestCount >= maxConcurrentRequests)
return false;
if(isPoll)
trace("Polling at: " + new Date().getSeconds());
requestCount++;
if(!data)
{
if(isPoll)
{
data = createRequest();
}
else
{
var temp:Array = [];
for(var i:uint = 0; i < 10 && requestQueue.length > 0; i++)
{
temp.push(requestQueue.shift());
}
data = createRequest(temp);
}
}
//build the http request
var request:HTTPService = new HTTPService();
request.method = "post";
request.headers = headers[request.method];
request.url = httpServer;
request.resultFormat = HTTPService.RESULT_FORMAT_TEXT;
request.contentType = "text/xml";
var responseCallback:Callback = new Callback(this, httpResponse, data, isPoll);
var errorCallback:Callback = new Callback(this, httpError, data, isPoll);
request.addEventListener(ResultEvent.RESULT, responseCallback.call, false);
request.addEventListener(FaultEvent.FAULT, errorCallback.call, false);
if(logger)
logger.log(data, "OUTGOING");
request.send(data);
resetPollTimer();
return true;
}
private function resetPollTimer():void
{
if(!pollTimer)
return;
pollTimer.reset();
pollTimer.start();
}
private function pollServer(evt:TimerEvent):void
{
//We shouldn't poll if the connection is dead, if we had requests to send instead, or if there's already one in progress
if(!isActive() || sendQueuedRequests() || isCurrentlyPolling)
return;
//this should be safe since sendRequests checks to be sure it's not over the concurrent requests limit, and we just ensured that the queue is empty by calling sendQueuedRequests()
isCurrentlyPolling = sendRequests(null, true);
}
private function get nextRID():Number {
if(!rid)
rid = Math.floor(Math.random() * 1000000);
return ++rid;
}
private function createRequest(bodyContent:Array=null):XMLNode {
var attrs:Object = {
xmlns: "http://jabber.org/protocol/httpbind",
rid: nextRID,
sid: sid
}
var req:XMLNode = new XMLNode(1, "body");
if(bodyContent)
for each(var content:XMLNode in bodyContent)
req.appendChild(content);
req.attributes = attrs;
return req;
}
private function handleAuthentication(responseBody:XMLNode):void
{
// if(!response || response.length == 0) {
// return;
// }
var status:Object = auth.handleResponse(0, responseBody);
if (status.authComplete) {
if (status.authSuccess) {
bindConnection();
}
else {
dispatchEvent(new ErrorEvent(ErrorEvent.ERROR));
disconnect();
}
}
}
private function configureConnection(responseBody:XMLNode):void
{
var features:XMLNode = responseBody.firstChild;
var authentication:Object = {};
for each(var feature:XMLNode in features.childNodes)
{
if (feature.nodeName == "mechanisms")
authentication.auth = configureAuthMechanisms(feature);
else if (feature.nodeName == "bind")
authentication.bind = true;
else if (feature.nodeName == "session")
authentication.session = true;
}
auth = authentication.auth;
dispatchEvent(new ConnectionSuccessEvent());
authHandler = handleAuthentication;
sendXML(auth.request);
}
private function configureAuthMechanisms(mechanisms:XMLNode):SASLAuth
{
var authMechanism:SASLAuth;
var authClass:Class;
for each(var mechanism:XMLNode in mechanisms.childNodes)
{
authClass = saslMechanisms[mechanism.firstChild.nodeValue];
if(authClass)
break;
}
if (!authClass) {
dispatchError("SASL missing", "The server is not configured to support any available SASL mechanisms", "SASL", -1);
return null;
}
return new authClass(this);
}
public function handleBindResponse(packet:IQ):void
{
var bind:BindExtension = packet.getExtension("bind") as BindExtension;
var jid:String = bind.getJID();
var parts:Array = jid.split("/");
myResource = parts[1];
parts = parts[0].split("@");
myUsername = parts[0];
domain = parts[1];
establishSession();
}
private function bindConnection():void
{
var bindIQ:IQ = new IQ(null, "set");
var bindExt:BindExtension = new BindExtension();
if(resource)
bindExt.resource = resource;
bindIQ.addExtension(bindExt);
//this is laaaaaame, it should be a function
bindIQ.callbackName = "handleBindResponse";
bindIQ.callbackScope = this;
send(bindIQ);
}
public function handleSessionResponse(packet:IQ):void
{
dispatchEvent(new LoginEvent());
}
private function establishSession():void
{
var sessionIQ:IQ = new IQ(null, "set");
sessionIQ.addExtension(new SessionExtension());
sessionIQ.callbackName = "handleSessionResponse";
sessionIQ.callbackScope = this;
send(sessionIQ);
}
//do nothing, we use polling instead
public override function sendKeepAlive():void {}
}
}
|
Add a little padding on BOSH polling; sacrifices a tiny bit of responsiveness for some safety, HOPEFULLY fixing XIFF-31. r=Daniel
|
Add a little padding on BOSH polling; sacrifices a tiny bit of responsiveness for some safety, HOPEFULLY fixing XIFF-31. r=Daniel
git-svn-id: c197267f952b24206666de142881703007ca05d5@10583 b35dd754-fafc-0310-a699-88a17e54d16e
|
ActionScript
|
apache-2.0
|
nazoking/xiff
|
3ce78587bb2469dab4476a54ccd4d7f278acbbae
|
KeyGenerator.as
|
KeyGenerator.as
|
package mns.crypto{
import com.hurlant.crypto.prng.Random;
import com.hurlant.crypto.rsa.RSAKey;
import com.hurlant.util.Hex;
import flash.external.ExternalInterface;
import flash.utils.ByteArray;
public class KeyGenerator
{
public static function generateKeys():void{
var exp:String = "10001";
var rsa:RSAKey = RSAKey.generate(1024, exp);
ExternalInterface.call("setvalue", "publickey", rsa.n.toString());
ExternalInterface.call("setvalue", "d", rsa.d.toString());
ExternalInterface.call("setvalue", "p", rsa.p.toString());
ExternalInterface.call("setvalue", "q", rsa.q.toString());
ExternalInterface.call("setvalue", "dmp", rsa.dmp1.toString());
ExternalInterface.call("setvalue", "dmq", rsa.dmq1.toString());
ExternalInterface.call("setvalue", "qinv", rsa.coeff.toString());
var data:ByteArray, prehashedkey:ByteArray, hashedkey:ByteArray;
var r:Random = new Random;
var rankey:ByteArray = new ByteArray
r.nextBytes(rankey, 32);
ExternalInterface.call("setvalue", "rk", Hex.fromArray(rankey));
}
}
}
|
package dse{
import com.hurlant.crypto.prng.Random;
import com.hurlant.crypto.rsa.RSAKey;
import com.hurlant.util.Hex;
import flash.external.ExternalInterface;
import flash.utils.ByteArray;
public class KeyGenerator
{
public static function generateKeys():void{
var exp:String = "10001";
var rsa:RSAKey = RSAKey.generate(1024, exp);
ExternalInterface.call("setvalue", "publickey", rsa.n.toString());
ExternalInterface.call("setvalue", "d", rsa.d.toString());
ExternalInterface.call("setvalue", "p", rsa.p.toString());
ExternalInterface.call("setvalue", "q", rsa.q.toString());
ExternalInterface.call("setvalue", "dmp", rsa.dmp1.toString());
ExternalInterface.call("setvalue", "dmq", rsa.dmq1.toString());
ExternalInterface.call("setvalue", "qinv", rsa.coeff.toString());
var data:ByteArray, prehashedkey:ByteArray, hashedkey:ByteArray;
var r:Random = new Random;
var rankey:ByteArray = new ByteArray
r.nextBytes(rankey, 32);
ExternalInterface.call("setvalue", "rk", Hex.fromArray(rankey));
}
}
}
|
change package of ActionScript class
|
change package of ActionScript class
|
ActionScript
|
mit
|
snoble/dse
|
205cd9245c5a04ae2d8063d2d91d017dba6cc46c
|
src/org/mangui/hls/HLSSettings.as
|
src/org/mangui/hls/HLSSettings.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* autoStartLoad
*
* if set to true,
* start level playlist and first fragments will be loaded automatically,
* after triggering of HlsEvent.MANIFEST_PARSED event
* if set to false,
* an explicit API call (hls.startLoad()) will be needed
* to start quality level/fragment loading.
*
* Default is true
*/
public static var autoStartLoad : Boolean = true;
/**
* capLevelToStage
*
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* maxLevelCappingMode
*
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // // /////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // // /////////////////////////////////
/**
* minBufferLength
*
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* minBufferLengthCapping
*
* Defines minimum buffer length capping value (max value) if minBufferLength is set to -1
*
* Default is -1 = no capping
*/
public static var minBufferLengthCapping : Number = -1;
/**
* maxBufferLength
*
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 120
*/
public static var maxBufferLength : Number = 120;
/**
* maxBackBufferLength
*
* Defines maximum back buffer length in seconds.
* (0 means infinite back buffering)
*
* Default is 30
*/
public static var maxBackBufferLength : Number = 30;
/**
* lowBufferLength
*
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3
*/
public static var lowBufferLength : Number = 3;
/**
* mediaTimeUpdatePeriod
*
* time update period in ms
* period at which HLSEvent.MEDIA_TIME will be triggered
* Default is 100 ms
*/
public static var mediaTimePeriod : int = 100;
/**
* fpsDroppedMonitoringPeriod
*
* dropped FPS Monitor Period in ms
* period at which nb dropped FPS will be checked
* Default is 5000 ms
*/
public static var fpsDroppedMonitoringPeriod : int = 5000;
/**
* fpsDroppedMonitoringThreshold
*
* dropped FPS Threshold
* every fpsDroppedMonitoringPeriod, dropped FPS will be compared to displayed FPS.
* if during that period, ratio of (dropped FPS/displayed FPS) is greater or equal
* than fpsDroppedMonitoringThreshold, HLSEvent.FPS_DROP event will be fired
* Default is 0.2 (20%)
*/
public static var fpsDroppedMonitoringThreshold : Number = 0.2;
/**
* capLevelonFPSDrop
*
* Limit levels usable in auto-quality when FPS drop is detected
* i.e. if frame drop is detected on level 5, auto level will be capped to level 4 a
* true - enabled
* false - disabled
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelonFPSDrop : Boolean = false;
/**
* smoothAutoSwitchonFPSDrop
*
* force a smooth level switch Limit when FPS drop is detected in auto-quality
* i.e. if frame drop is detected on level 5, it will trigger an auto quality level switch
* to level 4 for next fragment
* true - enabled
* false - disabled
*
* Note: this setting is active only if capLevelonFPSDrop==true
*
* Default is true
*/
public static var smoothAutoSwitchonFPSDrop : Boolean = true;
/**
* switchDownOnLevelError
*
* if level loading fails, and if in auto mode, and we are not on lowest level
* don't report Level loading error straight-away, try to switch down first
* true - enabled
* false - disabled
*
* Default is true
*/
public static var switchDownOnLevelError : Boolean = true;
/**
* seekMode
*
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
*
* Default is HLSSeekMode.KEYFRAME_SEEK
*/
public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK;
/**
* keyLoadMaxRetry
*
* Max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*
* Default is 3
*/
public static var keyLoadMaxRetry : int = 3;
/**
* keyLoadMaxRetryTimeout
*
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/**
* fragmentLoadMaxRetry
*
* Max number of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*
* Default is 3
*/
public static var fragmentLoadMaxRetry : int = 3;
/**
* fragmentLoadMaxRetryTimeout
*
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 4000
*/
public static var fragmentLoadMaxRetryTimeout : Number = 4000
/**
* fragmentLoadSkipAfterMaxRetry
*
* control behaviour in case fragment load still fails after max retry timeout
* if set to true, fragment will be skipped and next one will be loaded.
* If set to false, an I/O Error will be raised.
*
* Default is true.
*/
public static var fragmentLoadSkipAfterMaxRetry : Boolean = true;
/**
* flushLiveURLCache
*
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/**
* initialLiveManifestSize
*
* Number of segments needed to start playback of Live stream.
*
* Default is 1
*/
public static var initialLiveManifestSize: uint = 1;
/**
* manifestLoadMaxRetry
*
* max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = 3;
/**
* manifestLoadMaxRetryTimeout
*
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* manifestRedundantLoadmaxRetry
*
* max nb of looping over the redundant streams.
* >0 means looping over the stream array 2 or more times
* 0 means looping exactly once (no retries) - default behaviour
* -1 means infinite retry
*/
public static var manifestRedundantLoadmaxRetry : int = 3;
/**
* startFromBitrate
*
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*
* Default is -1
*/
public static var startFromBitrate : Number = -1;
/**
* startFromLevel
*
* start level :
* from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
* -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate)
*
* Default is -1
*/
public static var startFromLevel : Number = -1;
/**
* autoStartMaxDuration
*
* max fragment loading duration in automatic start level selection mode (in ms)
* -1 : max duration not capped
* other : max duration is capped to avoid long playback starting time
*
* Default is -1
*/
public static var autoStartMaxDuration : Number = -1;
/**
* seekFromLevel
*
* Seek level:
* from 0 to 1: indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*
* Default is -1
*/
public static var seekFromLevel : Number = -1;
/**
* useHardwareVideoDecoder
*
* Use hardware video decoder:
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*
* Default is true
*/
public static var useHardwareVideoDecoder : Boolean = true;
/**
* logInfo
*
* Defines whether INFO level log messages will will appear in the console
*
* Default is true
*/
public static var logInfo : Boolean = true;
/**
* logDebug
*
* Defines whether DEBUG level log messages will will appear in the console
*
* Default is false
*/
public static var logDebug : Boolean = false;
/**
* logDebug2
*
* Defines whether DEBUG2 level log messages will will appear in the console
*
* Default is false
*/
public static var logDebug2 : Boolean = false;
/**
* logWarn
*
* Defines whether WARN level log messages will will appear in the console
*
* Default is true
*/
public static var logWarn : Boolean = true;
/**
* logError
*
* Defines whether ERROR level log messages will will appear in the console
*
* Default is true
*/
public static var logError : Boolean = true;
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* autoStartLoad
*
* if set to true,
* start level playlist and first fragments will be loaded automatically,
* after triggering of HlsEvent.MANIFEST_PARSED event
* if set to false,
* an explicit API call (hls.startLoad()) will be needed
* to start quality level/fragment loading.
*
* Default is true
*/
public static var autoStartLoad : Boolean = true;
/**
* capLevelToStage
*
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* maxLevelCappingMode
*
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // // /////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // // /////////////////////////////////
/**
* minBufferLength
*
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* minBufferLengthCapping
*
* Defines minimum buffer length capping value (max value) if minBufferLength is set to -1
*
* Default is -1 = no capping
*/
public static var minBufferLengthCapping : Number = -1;
/**
* maxBufferLength
*
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 120
*/
public static var maxBufferLength : Number = 120;
/**
* maxBackBufferLength
*
* Defines maximum back buffer length in seconds.
* (0 means infinite back buffering)
*
* Default is 30
*/
public static var maxBackBufferLength : Number = 30;
/**
* lowBufferLength
*
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3
*/
public static var lowBufferLength : Number = 3;
/**
* mediaTimeUpdatePeriod
*
* time update period in ms
* period at which HLSEvent.MEDIA_TIME will be triggered
* Default is 100 ms
*/
public static var mediaTimePeriod : int = 100;
/**
* fpsDroppedMonitoringPeriod
*
* dropped FPS Monitor Period in ms
* period at which nb dropped FPS will be checked
* Default is 5000 ms
*/
public static var fpsDroppedMonitoringPeriod : int = 5000;
/**
* fpsDroppedMonitoringThreshold
*
* dropped FPS Threshold
* every fpsDroppedMonitoringPeriod, dropped FPS will be compared to displayed FPS.
* if during that period, ratio of (dropped FPS/displayed FPS) is greater or equal
* than fpsDroppedMonitoringThreshold, HLSEvent.FPS_DROP event will be fired
* Default is 0.2 (20%)
*/
public static var fpsDroppedMonitoringThreshold : Number = 0.2;
/**
* capLevelonFPSDrop
*
* Limit levels usable in auto-quality when FPS drop is detected
* i.e. if frame drop is detected on level 5, auto level will be capped to level 4 a
* true - enabled
* false - disabled
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelonFPSDrop : Boolean = false;
/**
* smoothAutoSwitchonFPSDrop
*
* force a smooth level switch Limit when FPS drop is detected in auto-quality
* i.e. if frame drop is detected on level 5, it will trigger an auto quality level switch
* to level 4 for next fragment
* true - enabled
* false - disabled
*
* Note: this setting is active only if capLevelonFPSDrop==true
*
* Default is true
*/
public static var smoothAutoSwitchonFPSDrop : Boolean = true;
/**
* switchDownOnLevelError
*
* if level loading fails, and if in auto mode, and we are not on lowest level
* don't report Level loading error straight-away, try to switch down first
* true - enabled
* false - disabled
*
* Default is true
*/
public static var switchDownOnLevelError : Boolean = true;
/**
* seekMode
*
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
*
* Default is HLSSeekMode.KEYFRAME_SEEK
*/
public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK;
/**
* keyLoadMaxRetry
*
* Max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*
* Default is 3
*/
public static var keyLoadMaxRetry : int = 3;
/**
* keyLoadMaxRetryTimeout
*
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/**
* fragmentLoadMaxRetry
*
* Max number of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*
* Default is 3
*/
public static var fragmentLoadMaxRetry : int = 3;
/**
* fragmentLoadMaxRetryTimeout
*
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 4000
*/
public static var fragmentLoadMaxRetryTimeout : Number = 4000;
/**
* fragmentLoadSkipAfterMaxRetry
*
* control behaviour in case fragment load still fails after max retry timeout
* if set to true, fragment will be skipped and next one will be loaded.
* If set to false, an I/O Error will be raised.
*
* Default is true.
*/
public static var fragmentLoadSkipAfterMaxRetry : Boolean = true;
/**
* flushLiveURLCache
*
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/**
* initialLiveManifestSize
*
* Number of segments needed to start playback of Live stream.
*
* Default is 1
*/
public static var initialLiveManifestSize : uint = 1;
/**
* manifestLoadMaxRetry
*
* max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = 3;
/**
* manifestLoadMaxRetryTimeout
*
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* manifestRedundantLoadmaxRetry
*
* max nb of looping over the redundant streams.
* >0 means looping over the stream array 2 or more times
* 0 means looping exactly once (no retries) - default behaviour
* -1 means infinite retry
*/
public static var manifestRedundantLoadmaxRetry : int = 3;
/**
* startFromBitrate
*
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*
* Default is -1
*/
public static var startFromBitrate : Number = -1;
/**
* startFromLevel
*
* start level :
* from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
* -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate)
*
* Default is -1
*/
public static var startFromLevel : Number = -1;
/**
* autoStartMaxDuration
*
* max fragment loading duration in automatic start level selection mode (in ms)
* -1 : max duration not capped
* other : max duration is capped to avoid long playback starting time
*
* Default is -1
*/
public static var autoStartMaxDuration : Number = -1;
/**
* seekFromLevel
*
* Seek level:
* from 0 to 1: indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*
* Default is -1
*/
public static var seekFromLevel : Number = -1;
/**
* useHardwareVideoDecoder
*
* Use hardware video decoder:
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*
* Default is true
*/
public static var useHardwareVideoDecoder : Boolean = true;
/**
* logInfo
*
* Defines whether INFO level log messages will will appear in the console
*
* Default is true
*/
public static var logInfo : Boolean = true;
/**
* logDebug
*
* Defines whether DEBUG level log messages will will appear in the console
*
* Default is false
*/
public static var logDebug : Boolean = false;
/**
* logDebug2
*
* Defines whether DEBUG2 level log messages will will appear in the console
*
* Default is false
*/
public static var logDebug2 : Boolean = false;
/**
* logWarn
*
* Defines whether WARN level log messages will will appear in the console
*
* Default is true
*/
public static var logWarn : Boolean = true;
/**
* logError
*
* Defines whether ERROR level log messages will will appear in the console
*
* Default is true
*/
public static var logError : Boolean = true;
}
}
|
add missing colon and indent in HLSSettings.as
|
add missing colon and indent in HLSSettings.as
|
ActionScript
|
mpl-2.0
|
mangui/flashls,vidible/vdb-flashls,fixedmachine/flashls,clappr/flashls,jlacivita/flashls,tedconf/flashls,jlacivita/flashls,neilrackett/flashls,hola/flashls,codex-corp/flashls,clappr/flashls,mangui/flashls,NicolasSiver/flashls,NicolasSiver/flashls,tedconf/flashls,codex-corp/flashls,neilrackett/flashls,vidible/vdb-flashls,fixedmachine/flashls,hola/flashls
|
fe54045f9ea16b9846f47985312375edd920ea6e
|
frameworks/as/src/org/apache/flex/core/ViewBase.as
|
frameworks/as/src/org/apache/flex/core/ViewBase.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.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.utils.MXMLDataInterpreter;
[DefaultProperty("mxmlContent")]
public class ViewBase extends UIBase
{
public function ViewBase()
{
super();
}
public function initUI(model:Object):void
{
_applicationModel = model;
dispatchEvent(new Event("modelChanged"));
// each MXML file can also have styles in fx:Style block
ValuesManager.valuesImpl.init(this);
MXMLDataInterpreter.generateMXMLProperties(this, MXMLProperties);
MXMLDataInterpreter.generateMXMLInstances(this, this, MXMLDescriptor);
}
public function get MXMLDescriptor():Array
{
return null;
}
public function get MXMLProperties():Array
{
return null;
}
public var mxmlContent:Array;
private var _applicationModel:Object;
[Bindable("modelChanged")]
public function get applicationModel():Object
{
return _applicationModel;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.utils.MXMLDataInterpreter;
[Event(name="initComplete", type="org.apache.flex.events.Event")]
[DefaultProperty("mxmlContent")]
public class ViewBase extends UIBase
{
public function ViewBase()
{
super();
}
public function initUI(model:Object):void
{
_applicationModel = model;
dispatchEvent(new Event("modelChanged"));
// each MXML file can also have styles in fx:Style block
ValuesManager.valuesImpl.init(this);
MXMLDataInterpreter.generateMXMLProperties(this, MXMLProperties);
MXMLDataInterpreter.generateMXMLInstances(this, this, MXMLDescriptor);
dispatchEvent(new Event("initComplete"))
}
public function get MXMLDescriptor():Array
{
return null;
}
public function get MXMLProperties():Array
{
return null;
}
public var mxmlContent:Array;
private var _applicationModel:Object;
[Bindable("modelChanged")]
public function get applicationModel():Object
{
return _applicationModel;
}
}
}
|
add initComplete event sort of like creationComplete in current Flex SDK
|
add initComplete event sort of like creationComplete in current Flex SDK
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
7e33dea8bf12522f45956ce699c84eb07ef5358a
|
src/org/zozuar/volumetrics/EffectContainer.as
|
src/org/zozuar/volumetrics/EffectContainer.as
|
package org.zozuar.volumetrics {
import flash.display.*;
import flash.events.*;
import flash.filters.*;
import flash.geom.*;
/**
* The EffectContainer class creates a volumetric light effect (also known as crepuscular or "god" rays).
* This is done in 2D with some bitmap processing of an emission object, and optionally an occlusion object.
*/
public class EffectContainer extends Sprite {
/**
* When true a blur filter is applied to the final effect bitmap (can help when colorIntegrity == true).
*/
public var blur:Boolean = false;
/**
* Selects rendering method; when set to true colors won't be distorted and performance will be
* a little worse. Also, this might make the final output appear grainier.
*/
public var colorIntegrity:Boolean = false;
/**
* Light intensity.
*/
public var intensity:Number = 4;
/**
* Number of passes applied to buffer. Lower numbers mean lower quality but better performance,
* anything above 8 is probably overkill.
*/
public var passes:uint = 6;
/**
* Set this to one of the StageQuality constants to use this quality level when drawing bitmaps, or to
* null to use the current stage quality. Mileage may vary on different platforms and player versions.
* I think it should only be used when stage.quality is LOW (set this to BEST to get reasonable results).
*/
public var rasterQuality:String = null;
/**
* Final scale of emission. Should always be more than 1.
*/
public var scale:Number = 2;
/**
* Smooth scaling of the effect's final output bitmap.
*/
public var smoothing:Boolean = true;
/**
* Light source x.
* @default viewport center (set in constructor).
*/
public var srcX:Number;
/**
* Light source y.
* @default viewport center (set in constructor).
*/
public var srcY:Number;
protected var _blurFilter:BlurFilter = new BlurFilter(2, 2);
protected var _emission:DisplayObject;
protected var _occlusion:DisplayObject;
protected var _ct:ColorTransform = new ColorTransform;
protected var _halve:ColorTransform = new ColorTransform(0.5, 0.5, 0.5);
protected var _occlusionLoResBmd:BitmapData;
protected var _occlusionLoResBmp:Bitmap;
protected var _baseBmd:BitmapData;
protected var _bufferBmd:BitmapData;
protected var _lightBmp:Bitmap = new Bitmap;
protected var _bufferSize:uint = 0x8000;
protected var _bufferWidth:uint;
protected var _bufferHeight:uint;
protected var _viewportWidth:uint;
protected var _viewportHeight:uint;
protected var _mtx:Matrix = new Matrix;
/**
* Creates a new effect container.
*
* @param width Viewport width in pixels.
* @param height Viewport height in pixels.
* @param emission A DisplayObject to which the effect will be applied. This object will be
* added as a child of the container. When applying the effect the object's filters and color
* transform are ignored, if you want to use filters or a color transform put your content in
* another object and addChild it to this one instead.
* @param occlusion An optional occlusion object, handled the same way as the emission object.
*/
public function EffectContainer(width:uint, height:uint, emission:DisplayObject, occlusion:DisplayObject = null) {
if(!emission) throw(new Error("emission DisplayObject must not be null."));
addChild(_emission = emission);
if(occlusion) addChild(_occlusion = occlusion);
setViewportSize(width, height);
_lightBmp.blendMode = BlendMode.ADD;
addChild(_lightBmp);
srcX = width / 2;
srcY = height / 2;
}
/**
* Sets the container's size. This method recreates internal buffers (slow), do not call this on
* every frame.
*
* @param width Viewport width in pixels
* @param height Viewport height in pixels
*/
public function setViewportSize(width:uint, height:uint):void {
_viewportWidth = width;
_viewportHeight = height;
scrollRect = new Rectangle(0, 0, width, height);
_updateBuffers();
}
/**
* Sets the approximate size (in pixels) of the effect's internal buffers. Smaller number means lower
* quality and better performance. This method recreates internal buffers (slow), do not call this on
* every frame.
*
* @param size Buffer size in pixels
*/
public function setBufferSize(size:uint):void {
_bufferSize = size;
_updateBuffers();
}
protected function _updateBuffers():void {
var aspect:Number = _viewportWidth / _viewportHeight;
_bufferHeight = Math.max(1, Math.sqrt(_bufferSize / aspect));
_bufferWidth = Math.max(1, _bufferHeight * aspect);
dispose();
_baseBmd = new BitmapData(_bufferWidth, _bufferHeight, false, 0);
_bufferBmd = new BitmapData(_bufferWidth, _bufferHeight, false, 0);
_occlusionLoResBmd = new BitmapData(_bufferWidth, _bufferHeight, true, 0);
_occlusionLoResBmp = new Bitmap(_occlusionLoResBmd);
}
/**
* Render a single frame.
*
* @param e In case you want to make this an event listener.
*/
public function render(e:Event = null):void {
if(!(_lightBmp.visible = intensity > 0)) return;
var savedQuality:String = stage.quality;
if(rasterQuality) stage.quality = rasterQuality;
var mul:Number = colorIntegrity ? intensity : intensity/(1<<passes);
_ct.redMultiplier = _ct.greenMultiplier = _ct.blueMultiplier = mul;
_drawLoResEmission();
if(_occlusion) _eraseLoResOcclusion();
if(rasterQuality) stage.quality = savedQuality;
var s:Number = 1 + (scale-1) / (1 << passes);
var tx:Number = srcX/_viewportWidth*_bufferWidth;
var ty:Number = srcY/_viewportHeight*_bufferHeight;
_mtx.identity();
_mtx.translate(-tx, -ty);
_mtx.scale(s, s);
_mtx.translate(tx, ty);
_applyEffect(_baseBmd, _bufferBmd, _mtx, passes);
_lightBmp.bitmapData = _baseBmd;
_lightBmp.width = _viewportWidth;
_lightBmp.height = _viewportHeight;
_lightBmp.smoothing = smoothing;
}
/**
* Draws a scaled-down emission on _baseBmd.
*/
protected function _drawLoResEmission():void {
_copyMatrix(_emission.transform.matrix, _mtx);
_mtx.scale(_bufferWidth / _viewportWidth, _bufferHeight / _viewportHeight);
_baseBmd.fillRect(_baseBmd.rect, 0);
_baseBmd.draw(_emission, _mtx, colorIntegrity ? null : _ct);
}
/**
* Draws a scaled-down occlusion on _occlusionLoResBmd and erases it from _baseBmd.
*/
protected function _eraseLoResOcclusion():void {
_occlusionLoResBmd.fillRect(_occlusionLoResBmd.rect, 0);
_copyMatrix(_occlusion.transform.matrix, _mtx);
_mtx.scale(_bufferWidth / _viewportWidth, _bufferHeight / _viewportHeight);
_occlusionLoResBmd.draw(_occlusion, _mtx);
_baseBmd.draw(_occlusionLoResBmp, null, null, BlendMode.ERASE);
}
/**
* Render the effect on every frame until stopRendering is called.
*/
public function startRendering():void {
addEventListener(Event.ENTER_FRAME, render);
}
/**
* Stop rendering on every frame.
*/
public function stopRendering():void {
removeEventListener(Event.ENTER_FRAME, render);
}
/**
* Low-level workhorse, applies the lighting effect to a bitmap. This function modifies the bmd and buffer
* bitmaps and its mtx argument.
*
* @param bmd The BitmapData to apply the effect on.
* @param buffer Another BitmapData object for temporary storage. Must be the same size as bmd.
* @param mtx Effect matrix.
* @param passes Number of passes to make.
*/
protected function _applyEffect(bmd:BitmapData, buffer:BitmapData, mtx:Matrix, passes:uint):void {
while(passes--) {
if(colorIntegrity) bmd.colorTransform(bmd.rect, _halve);
buffer.copyPixels(bmd, bmd.rect, bmd.rect.topLeft);
bmd.draw(buffer, mtx, null, BlendMode.ADD, null, true);
mtx.concat(mtx);
}
if(colorIntegrity) bmd.colorTransform(bmd.rect, _ct);
if(blur) bmd.applyFilter(bmd, bmd.rect, bmd.rect.topLeft, _blurFilter);
}
/**
* Dispose of all intermediate buffers. After calling this the EffectContainer object will be unusable.
*/
public function dispose():void {
if(_baseBmd) _baseBmd.dispose();
if(_occlusionLoResBmd) _occlusionLoResBmd.dispose();
if(_bufferBmd) _bufferBmd.dispose();
_baseBmd = _occlusionLoResBmd = _bufferBmd = _lightBmp.bitmapData = null;
}
protected function _copyMatrix(src:Matrix, dst:Matrix):void {
dst.a = src.a;
dst.b = src.b;
dst.c = src.c;
dst.d = src.d;
dst.tx = src.tx;
dst.ty = src.ty;
}
}
}
|
package org.zozuar.volumetrics {
import flash.display.*;
import flash.events.*;
import flash.filters.*;
import flash.geom.*;
/**
* The EffectContainer class creates a volumetric light effect (also known as crepuscular or "god" rays).
* This is done in 2D with some bitmap processing of an emission object, and optionally an occlusion object.
*/
public class EffectContainer extends Sprite {
/**
* When true a blur filter is applied to the final effect bitmap (can help when colorIntegrity == true).
*/
public var blur:Boolean = false;
/**
* Selects rendering method; when set to true colors won't be distorted and performance will be
* a little worse. Also, this might make the final output appear grainier.
*/
public var colorIntegrity:Boolean = false;
/**
* Light intensity.
*/
public var intensity:Number = 4;
/**
* Number of passes applied to buffer. Lower numbers mean lower quality but better performance,
* anything above 8 is probably overkill.
*/
public var passes:uint = 6;
/**
* Set this to one of the StageQuality constants to use this quality level when drawing bitmaps, or to
* null to use the current stage quality. Mileage may vary on different platforms and player versions.
* I think it should only be used when stage.quality is LOW (set this to BEST to get reasonable results).
*/
public var rasterQuality:String = null;
/**
* Final scale of emission. Should always be more than 1.
*/
public var scale:Number = 2;
/**
* Smooth scaling of the effect's final output bitmap.
*/
public var smoothing:Boolean = true;
/**
* Light source x.
* @default viewport center (set in constructor).
*/
public var srcX:Number;
/**
* Light source y.
* @default viewport center (set in constructor).
*/
public var srcY:Number;
protected var _blurFilter:BlurFilter = new BlurFilter(2, 2);
protected var _emission:DisplayObject;
protected var _occlusion:DisplayObject;
protected var _ct:ColorTransform = new ColorTransform;
protected var _halve:ColorTransform = new ColorTransform(0.5, 0.5, 0.5);
protected var _occlusionLoResBmd:BitmapData;
protected var _occlusionLoResBmp:Bitmap;
protected var _baseBmd:BitmapData;
protected var _bufferBmd:BitmapData;
protected var _lightBmp:Bitmap = new Bitmap;
protected var _bufferSize:uint = 0x8000;
protected var _bufferWidth:uint;
protected var _bufferHeight:uint;
protected var _bufferRect:Rectangle = new Rectangle;
protected var _viewportWidth:uint;
protected var _viewportHeight:uint;
protected var _mtx:Matrix = new Matrix;
protected var _zero:Point = new Point;
/**
* Creates a new effect container.
*
* @param width Viewport width in pixels.
* @param height Viewport height in pixels.
* @param emission A DisplayObject to which the effect will be applied. This object will be
* added as a child of the container. When applying the effect the object's filters and color
* transform are ignored, if you want to use filters or a color transform put your content in
* another object and addChild it to this one instead.
* @param occlusion An optional occlusion object, handled the same way as the emission object.
*/
public function EffectContainer(width:uint, height:uint, emission:DisplayObject, occlusion:DisplayObject = null) {
if(!emission) throw(new Error("emission DisplayObject must not be null."));
addChild(_emission = emission);
if(occlusion) addChild(_occlusion = occlusion);
setViewportSize(width, height);
_lightBmp.blendMode = BlendMode.ADD;
addChild(_lightBmp);
srcX = width / 2;
srcY = height / 2;
}
/**
* Sets the container's size. This method recreates internal buffers (slow), do not call this on
* every frame.
*
* @param width Viewport width in pixels
* @param height Viewport height in pixels
*/
public function setViewportSize(width:uint, height:uint):void {
_viewportWidth = width;
_viewportHeight = height;
scrollRect = new Rectangle(0, 0, width, height);
_updateBuffers();
}
/**
* Sets the approximate size (in pixels) of the effect's internal buffers. Smaller number means lower
* quality and better performance. This method recreates internal buffers (slow), do not call this on
* every frame.
*
* @param size Buffer size in pixels
*/
public function setBufferSize(size:uint):void {
_bufferSize = size;
_updateBuffers();
}
protected function _updateBuffers():void {
var aspect:Number = _viewportWidth / _viewportHeight;
_bufferHeight = Math.max(1, Math.sqrt(_bufferSize / aspect));
_bufferWidth = Math.max(1, _bufferHeight * aspect);
dispose();
_baseBmd = new BitmapData(_bufferWidth, _bufferHeight, false, 0);
_bufferBmd = new BitmapData(_bufferWidth, _bufferHeight, false, 0);
_occlusionLoResBmd = new BitmapData(_bufferWidth, _bufferHeight, true, 0);
_occlusionLoResBmp = new Bitmap(_occlusionLoResBmd);
_bufferRect.height = _bufferHeight;
_bufferRect.width = _bufferWidth;
}
/**
* Render a single frame.
*
* @param e In case you want to make this an event listener.
*/
public function render(e:Event = null):void {
if(!(_lightBmp.visible = intensity > 0)) return;
var savedQuality:String = stage.quality;
if(rasterQuality) stage.quality = rasterQuality;
var mul:Number = colorIntegrity ? intensity : intensity/(1<<passes);
_ct.redMultiplier = _ct.greenMultiplier = _ct.blueMultiplier = mul;
_drawLoResEmission();
if(_occlusion) _eraseLoResOcclusion();
if(rasterQuality) stage.quality = savedQuality;
var s:Number = 1 + (scale-1) / (1 << passes);
var tx:Number = srcX/_viewportWidth*_bufferWidth;
var ty:Number = srcY/_viewportHeight*_bufferHeight;
_mtx.identity();
_mtx.translate(-tx, -ty);
_mtx.scale(s, s);
_mtx.translate(tx, ty);
_applyEffect(_baseBmd, _bufferRect, _bufferBmd, _mtx, passes);
_lightBmp.bitmapData = _baseBmd;
_lightBmp.width = _viewportWidth;
_lightBmp.height = _viewportHeight;
_lightBmp.smoothing = smoothing;
}
/**
* Draws a scaled-down emission on _baseBmd.
*/
protected function _drawLoResEmission():void {
_copyMatrix(_emission.transform.matrix, _mtx);
_mtx.scale(_bufferWidth / _viewportWidth, _bufferHeight / _viewportHeight);
_baseBmd.fillRect(_bufferRect, 0);
_baseBmd.draw(_emission, _mtx, colorIntegrity ? null : _ct);
}
/**
* Draws a scaled-down occlusion on _occlusionLoResBmd and erases it from _baseBmd.
*/
protected function _eraseLoResOcclusion():void {
_occlusionLoResBmd.fillRect(_bufferRect, 0);
_copyMatrix(_occlusion.transform.matrix, _mtx);
_mtx.scale(_bufferWidth / _viewportWidth, _bufferHeight / _viewportHeight);
_occlusionLoResBmd.draw(_occlusion, _mtx);
_baseBmd.draw(_occlusionLoResBmp, null, null, BlendMode.ERASE);
}
/**
* Render the effect on every frame until stopRendering is called.
*/
public function startRendering():void {
addEventListener(Event.ENTER_FRAME, render);
}
/**
* Stop rendering on every frame.
*/
public function stopRendering():void {
removeEventListener(Event.ENTER_FRAME, render);
}
/**
* Low-level workhorse, applies the lighting effect to a bitmap. This function modifies the bmd and buffer
* bitmaps and its mtx argument.
*
* @param bmd The BitmapData to apply the effect on.
* @param rect BitmapData rectangle.
* @param buffer Another BitmapData object for temporary storage. Must be the same size as bmd.
* @param mtx Effect matrix.
* @param passes Number of passes to make.
*/
protected function _applyEffect(bmd:BitmapData, rect:Rectangle, buffer:BitmapData, mtx:Matrix, passes:uint):void {
while(passes--) {
if(colorIntegrity) bmd.colorTransform(rect, _halve);
buffer.copyPixels(bmd, rect, _zero);
bmd.draw(buffer, mtx, null, BlendMode.ADD, null, true);
mtx.concat(mtx);
}
if(colorIntegrity) bmd.colorTransform(rect, _ct);
if(blur) bmd.applyFilter(bmd, rect, _zero, _blurFilter);
}
/**
* Dispose of all intermediate buffers. After calling this the EffectContainer object will be unusable.
*/
public function dispose():void {
if(_baseBmd) _baseBmd.dispose();
if(_occlusionLoResBmd) _occlusionLoResBmd.dispose();
if(_bufferBmd) _bufferBmd.dispose();
_baseBmd = _occlusionLoResBmd = _bufferBmd = _lightBmp.bitmapData = null;
}
protected function _copyMatrix(src:Matrix, dst:Matrix):void {
dst.a = src.a;
dst.b = src.b;
dst.c = src.c;
dst.d = src.d;
dst.tx = src.tx;
dst.ty = src.ty;
}
}
}
|
patch from makc - https://github.com/yonatan/volumetrics/pull/1
|
patch from makc - https://github.com/yonatan/volumetrics/pull/1
|
ActionScript
|
mit
|
yonatan/volumetrics
|
0267a346c6682799d12f2776104b52bbdcbf44e9
|
FlexUnit4Test/src/org/flexunit/cases/AssertCase.as
|
FlexUnit4Test/src/org/flexunit/cases/AssertCase.as
|
package org.flexunit.cases
{
import flexunit.framework.AssertionFailedError;
import org.flexunit.Assert;
public class AssertCase
{
protected var asserterCalled:int = 0;
[Test(description="Ensure that the assertWithApply function correctly runs the function with the parameter array")]
public function testAssertWithApply():void {
asserterCalled = 0;
Assert.assertWithApply( test, [new Object()] );
Assert.assertEquals( 1, asserterCalled );
}
[Test(description="Ensure that the assertWith function correct runs the function with the list of paramters")]
public function testAssertWith():void {
asserterCalled = 0;
Assert.assertWith( test, new Object() );
Assert.assertEquals( 1, asserterCalled );
}
[Test(description="Ensure that the assertionsMade property returns the correct assertCount")]
public function testAssertionsMade():void {
//Reset the fields to ensure the the count is accurate
Assert.resetAssertionsFields();
Assert.assertEquals( 0, 0 );
Assert.assertEquals( Assert.assertionsMade, 1 );
}
[Test(description="Ensure that the resetAssertionsFields function correctly resets the assertCount")]
public function testResetAssertionsFields():void {
Assert.assertEquals( 0, 0 );
//Ensure that the number of assertions are greater than zero
Assert.assertTrue( Assert.assertionsMade > 0 );
//Reset the assertions
Assert.resetAssertionsFields();
Assert.assertEquals( Assert.assertionsMade, 0 );
}
[Test(description="Ensure that the assertEquals function correctly determines if two non-strictly equal items are equal")]
public function testAssertEquals():void {
var o:Object = new Object();
Assert.assertEquals( null, null );
Assert.assertEquals( o, o );
Assert.assertEquals( 5, 5 );
Assert.assertEquals( "5", "5" );
Assert.assertEquals( 5, "5" );
}
[Test(description="Ensure that the assertEquals function correctly determines if two non-strictly equal items are equal when a message is provided")]
public function testAssertEqualsWithMessage():void {
Assert.assertEquals( "Assert equals fail", "5", 5 );
}
[Test(description="Ensure that the assertEquals function fails when two items are not equal")]
public function testAssertEqualsFails():void {
var failed:Boolean = false;
try {
Assert.assertEquals( 2, 4 );
} catch (error:AssertionFailedError) {
failed = true;
Assert.assertEquals( "expected:<2> but was:<4>", error.message );
}
if ( !failed ) {
Assert.fail( "Assert equals didn't fail" );
}
}
[Test(description="Ensure that the assertEquals function fails when two items are not equal and the proper passed message is displayed")]
public function testAssertEqualsWithMessageFails():void {
var message:String = "Assert equals fail";
var failed:Boolean = false;
try {
Assert.assertEquals( message, 2, 4 );
// if we get an error with the right message we pass
} catch (error:AssertionFailedError) {
failed = true;
Assert.assertEquals( message + " - expected:<2> but was:<4>", error.message );
}
if ( !failed ) {
Assert.fail( "Assert equals didn't fail" );
}
}
[Test(description="Ensure that the failNotEquals function correctly determines if two non-strictly equal values are equal")]
public function testFailNotEquals():void {
Assert.failNotEquals( "Failure", "5", 5 );
}
[Test(description="Ensure that the failNotEqula function fails when two values are not equal",
expects="flexunit.framework.AssertionFailedError")]
public function testFailNotEqualsFails():void {
Assert.failNotEquals( "Failure", 2, 4 );
}
[Test(description="Ensure that the assertStrictlyEquals function correctly determines if two values are strictly equal")]
public function testAssertStrictlyEquals():void {
var o:Object = new Object();
Assert.assertStrictlyEquals( o, o );
}
[Test(description="Ensure that the assertStrictlyEquals function correctly determines if two values are strictly equal when a message is provided")]
public function testAssertStrictlyEqualsWithMessage():void {
var o:Object = new Object();
Assert.assertStrictlyEquals( "Assert strictly equals fail", o, o );
}
[Test(description="Ensure that the assertStrictlyEquals function fails when two items are not strictly equal")]
public function testAssertStrictlyEqualsFails():void {
var failed:Boolean = false;
try {
Assert.assertStrictlyEquals( 5, "5" );
} catch (error:AssertionFailedError) {
failed = true;
Assert.assertEquals( "expected:<5> but was:<5>", error.message );
}
if ( !failed ) {
Assert.fail( "Assert strictly equals didn't fail" );
}
}
[Test(description="Ensure that the assertStrictlyEquals function fails when two items are not strictly euqal and the proper passed message is displayed")]
public function testAssertStrictlyEqualsWithMessageFails():void {
var message:String = "Assert strictly equals fail";
var failed:Boolean = false;
try {
Assert.assertStrictlyEquals( message, 5, "5" );
// if we get an error with the right message we pass
} catch (error:AssertionFailedError) {
failed = true;
Assert.assertEquals( message + " - expected:<5> but was:<5>", error.message );
}
if ( !failed ) {
Assert.fail( "Assert strictly equals didn't fail" );
}
}
[Test(description="Ensure that the failNotStrictlyEquals function correctly works when two strictly equal values are provided")]
public function testFailNotStrictlyEquals():void {
var o:Object = new Object();
Assert.failNotStrictlyEquals( "Assert strictly equals fail", o, o );
}
//TODO:: This test is not complete. Errors in my build prevented completion.
[Test(description="Ensure that the failNotStrictlyEquals function fails when two non-strictly equal values are provided")]
public function testFailNotStrictlyEqualsFails():void {
var failed:Boolean = false;
/*
try {
Assert.failNotStrictlyEquals( "Assert strictly equals fail", 5, "5" );
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( "expected true but was false", error.message );
}
*/
if ( !failed ) {
Assert.fail( "Assert strictly equals didn't fail" );
}
}
[Test(description="Ensure that the assertTrue fucntion correctly works when a true value is provided")]
public function testAssertTrue():void {
Assert.assertTrue( true );
}
[Test(description="Ensure that the assertTrue function correctly works when a true value and a message are provided")]
public function testAssertTrueWithMessage():void {
Assert.assertTrue( "Assert true fail", true );
}
[Test(description="Ensure that the assertTrue function fails when a false value is provided")]
public function testAssertTrueFails():void {
var failed:Boolean = false;
try {
Assert.assertTrue( false )
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( "expected true but was false", error.message );
}
if ( !failed ) {
Assert.fail( "Assert true didn't fail" );
}
}
[Test(description="Ensure that the assertTrue functions fails when a false value is provided and the proper passed message is displayed")]
public function testAssertTrueWithMessageFails():void {
var message:String = "Assert true fail";
var failed:Boolean = false;
try {
Assert.assertTrue( message, false )
// if we get an error with the right message we pass
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( message + " - expected true but was false", error.message );
}
if ( !failed ) {
Assert.fail( "Assert true didn't fail" );
}
}
[Test(description="Ensure that the failNotTrue function correctly works when a value of true is provided")]
public function testFailNotTrue():void {
Assert.failNotTrue( "Fail not true fail", true );
}
[Test(description="Ensure that the failNotTrue function fails when a value of false is provided",
expects="flexunit.framework.AssertionFailedError")]
public function testFailNotTrueFails():void {
Assert.failNotTrue( "Fail not true fail", false );
}
[Test(description="Ensure that the assertFalse function correctly works when a value of false is provided")]
public function testAssertFalse():void {
Assert.assertFalse( false );
}
[Test(description="Ensure that the assertFalse function correctly works when a value of false and a message are provided")]
public function testAssertFalseWithMessage():void {
Assert.assertFalse( "Assert false fail", false );
}
[Test(description="Ensure that the assertFalse function fails when a value of true is provided")]
public function testAssertFalseFails():void {
var failed:Boolean = false;
try {
Assert.assertFalse( true )
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( "expected false but was true", error.message );
}
if ( !failed ) {
Assert.fail( "Assert false didn't fail" );
}
}
[Test(description="Ensure that the assertFalse function fails when a value of true is provided and the proper message is displayed")]
public function testAssertFalseWithMessageFails():void {
var message:String = "Assert false fail";
var failed:Boolean = false;
try {
Assert.assertFalse( message, true )
// if we get an error with the right message we pass
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( message + " - expected false but was true", error.message );
}
if ( !failed ) {
Assert.fail( "Assert false didn't fail" );
}
}
[Test(description="Ensure that the failTrue function correctly works when a value of false is provided")]
public function testFailTrue():void {
Assert.failTrue( "Fail true fail", false );
}
[Test(description="Ensure that the failTrue function fails when a value of true is provided",
expects="flexunit.framework.AssertionFailedError")]
public function testFailTrueFails():void {
Assert.failTrue( "Fail true fail", true );
}
[Test(description="Ensure that the assertNull function correctly works when a value of null is provided")]
public function testAssertNull():void {
Assert.assertNull( null );
}
[Test(description="Ensure that the assertNull function correctly works when a value of null and a message are provided")]
public function testAssertNullWithMessage():void {
Assert.assertNull( "Assert null fail", null );
}
[Test(description="Ensure that the assertNull function fails when a non-null value is provided")]
public function testAssertNullFails():void {
var o:Object = new Object();
var failed:Boolean = false;
try {
Assert.assertNull( o )
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( "object was not null: [object Object]", error.message );
}
if ( !failed ) {
Assert.fail( "Assert null didn't fail" );
}
}
[Test(description="Ensure that the assertNull functions fails when a non-null value is provided an the proper message is displayed")]
public function testAssertNullWithMessageFails():void {
var o:Object = new Object();
var failed:Boolean = false;
var message:String = "Assert null fail";
try {
Assert.assertNull( message, o )
// if we get an error with the right message we pass
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( message + " - object was not null: [object Object]", error.message );
}
if ( !failed ) {
Assert.fail( "Assert null didn't fail" );
}
}
[Test(description="Ensure that the failNull function works correctly when a non-null value is provided")]
public function testFailNull():void {
var o:Object = new Object();
Assert.failNull( "Fail null fail", o );
}
[Test(description="Ensure that the failNull function fails when a null value is provided",
expects="flexunit.framework.AssertionFailedError")]
public function testFailNullFails():void {
Assert.failNull( "Fail null fail", null );
}
[Test(description="Ensure the the assertNotNull function correctly works when a non-null value is provided")]
public function testAssertNotNull():void {
var o:Object = new Object();
Assert.assertNotNull( o );
}
[Test(description="Ensure that the assertNotNull function correctly works when a non-null value and a message are provided")]
public function testAssertNotNullWithMessage():void {
var o:Object = new Object();
Assert.assertNotNull( "Assert not null fail", o );
}
[Test(description="Ensure that the assertNotNull function fails when a null value is provided")]
public function testAssertNotNullFails():void {
var failed:Boolean = false;
try {
Assert.assertNotNull( null )
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( "object was null: null", error.message );
}
if ( !failed ) {
Assert.fail( "Assert not null didn't fail" );
}
}
[Test(description="Ensure that the assertNotNull function fails when a null value is provided and the proper message is displayed")]
public function testAssertNotNullWithMessageFails():void {
var failed:Boolean = false;
var message:String = "Assert not null fail";
try {
Assert.assertNotNull( message, null )
// if we get an error with the right message we pass
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( message + " - object was null: null", error.message );
}
if ( !failed ) {
Assert.fail( "Assert not null didn't fail" );
}
}
[Test(description="Ensure that the failNotNull function works correctly when a null value is provided")]
public function testFailNotNull():void {
Assert.failNotNull( "Fail not null fail", null );
}
[Test(description="Ensure that the failNotNull function fails when a non-null value is provided")]
public function testFailNotNullFails():void {
var o:Object = new Object();
var failed:Boolean = false;
var message:String = "Fail not null fail";
try {
Assert.failNotNull( "Fail not null fail", o );
} catch(error:AssertionFailedError) {
failed = true;
Assert.assertEquals( message + " - object was not null: [object Object]", error.message );
}
if(!failed) {
Assert.fail("The failNotNull function has failed");
}
}
[Test(description="Ensure that the testFail function correctly throws an AssertionFailedError and sends the proper message")]
public function testFail():void {
var message:String = "Fail test";
var failed:Boolean = false;
try {
Assert.fail(message);
} catch(error:AssertionFailedError) {
failed = true;
Assert.assertEquals( message, error.message );
}
if(!failed) {
Assert.fail("The fail function has failed");
}
}
protected function test( obj:Object ):void {
asserterCalled++;
}
}
}
|
package org.flexunit.cases
{
import flexunit.framework.AssertionFailedError;
import org.flexunit.Assert;
public class AssertCase
{
protected var asserterCalled:int = 0;
[Test(description="Ensure that the assertWithApply function correctly runs the function with the parameter array")]
public function testAssertWithApply():void {
asserterCalled = 0;
Assert.assertWithApply( test, [new Object()] );
Assert.assertEquals( 1, asserterCalled );
}
[Test(description="Ensure that the assertWith function correct runs the function with the list of paramters")]
public function testAssertWith():void {
asserterCalled = 0;
Assert.assertWith( test, new Object() );
Assert.assertEquals( 1, asserterCalled );
}
[Test(description="Ensure that the assertionsMade property returns the correct assertCount")]
public function testAssertionsMade():void {
//Reset the fields to ensure the the count is accurate
Assert.resetAssertionsFields();
Assert.assertEquals( 0, 0 );
Assert.assertEquals( Assert.assertionsMade, 1 );
}
[Test(description="Ensure that the resetAssertionsFields function correctly resets the assertCount")]
public function testResetAssertionsFields():void {
Assert.assertEquals( 0, 0 );
//Ensure that the number of assertions are greater than zero
Assert.assertTrue( Assert.assertionsMade > 0 );
//Reset the assertions
Assert.resetAssertionsFields();
Assert.assertEquals( Assert.assertionsMade, 0 );
}
[Test(description="Ensure that the assertEquals function correctly determines if two non-strictly equal items are equal")]
public function testAssertEquals():void {
var o:Object = new Object();
Assert.assertEquals( null, null );
Assert.assertEquals( o, o );
Assert.assertEquals( 5, 5 );
Assert.assertEquals( "5", "5" );
Assert.assertEquals( 5, "5" );
}
[Test(description="Ensure that the assertEquals function correctly determines if two non-strictly equal items are equal when a message is provided")]
public function testAssertEqualsWithMessage():void {
Assert.assertEquals( "Assert equals fail", "5", 5 );
}
[Test(description="Ensure that the assertEquals function fails when two items are not equal")]
public function testAssertEqualsFails():void {
var failed:Boolean = false;
try {
Assert.assertEquals( 2, 4 );
} catch (error:AssertionFailedError) {
failed = true;
Assert.assertEquals( "expected:<2> but was:<4>", error.message );
}
if ( !failed ) {
Assert.fail( "Assert equals didn't fail" );
}
}
[Test(description="Ensure that the assertEquals function fails when two items are not equal and the proper passed message is displayed")]
public function testAssertEqualsWithMessageFails():void {
var message:String = "Assert equals fail";
var failed:Boolean = false;
try {
Assert.assertEquals( message, 2, 4 );
// if we get an error with the right message we pass
} catch (error:AssertionFailedError) {
failed = true;
Assert.assertEquals( message + " - expected:<2> but was:<4>", error.message );
}
if ( !failed ) {
Assert.fail( "Assert equals didn't fail" );
}
}
[Test(description="Ensure that the failNotEquals function correctly determines if two non-strictly equal values are equal")]
public function testFailNotEquals():void {
Assert.failNotEquals( "Failure", "5", 5 );
}
[Test(description="Ensure that the failNotEqula function fails when two values are not equal",
expects="flexunit.framework.AssertionFailedError")]
public function testFailNotEqualsFails():void {
Assert.failNotEquals( "Failure", 2, 4 );
}
[Test(description="Ensure that the assertStrictlyEquals function correctly determines if two values are strictly equal")]
public function testAssertStrictlyEquals():void {
var o:Object = new Object();
Assert.assertStrictlyEquals( o, o );
}
[Test(description="Ensure that the assertStrictlyEquals function correctly determines if two values are strictly equal when a message is provided")]
public function testAssertStrictlyEqualsWithMessage():void {
var o:Object = new Object();
Assert.assertStrictlyEquals( "Assert strictly equals fail", o, o );
}
[Test(description="Ensure that the assertStrictlyEquals function fails when two items are not strictly equal")]
public function testAssertStrictlyEqualsFails():void {
var failed:Boolean = false;
try {
Assert.assertStrictlyEquals( 5, "5" );
} catch (error:AssertionFailedError) {
failed = true;
Assert.assertEquals( "expected:<5> but was:<5>", error.message );
}
if ( !failed ) {
Assert.fail( "Assert strictly equals didn't fail" );
}
}
[Test(description="Ensure that the assertStrictlyEquals function fails when two items are not strictly euqal and the proper passed message is displayed")]
public function testAssertStrictlyEqualsWithMessageFails():void {
var message:String = "Assert strictly equals fail";
var failed:Boolean = false;
try {
Assert.assertStrictlyEquals( message, 5, "5" );
// if we get an error with the right message we pass
} catch (error:AssertionFailedError) {
failed = true;
Assert.assertEquals( message + " - expected:<5> but was:<5>", error.message );
}
if ( !failed ) {
Assert.fail( "Assert strictly equals didn't fail" );
}
}
[Test(description="Ensure that the failNotStrictlyEquals function correctly works when two strictly equal values are provided")]
public function testFailNotStrictlyEquals():void {
var o:Object = new Object();
Assert.failNotStrictlyEquals( "Assert strictly equals fail", o, o );
}
[Test(description="Ensure that the failNotStrictlyEquals function fails when two non-strictly equal values are provided")]
public function testFailNotStrictlyEqualsFails():void {
var failed:Boolean = false;
try {
Assert.failNotStrictlyEquals( "Assert strictly equals fail", 5, "5" );
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( "Assert strictly equals fail - expected:<5> but was:<5>", error.message );
}
if ( !failed ) {
Assert.fail( "Assert strictly equals didn't fail" );
}
}
[Test(description="Ensure that the assertTrue fucntion correctly works when a true value is provided")]
public function testAssertTrue():void {
Assert.assertTrue( true );
}
[Test(description="Ensure that the assertTrue function correctly works when a true value and a message are provided")]
public function testAssertTrueWithMessage():void {
Assert.assertTrue( "Assert true fail", true );
}
[Test(description="Ensure that the assertTrue function fails when a false value is provided")]
public function testAssertTrueFails():void {
var failed:Boolean = false;
try {
Assert.assertTrue( false )
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( "expected true but was false", error.message );
}
if ( !failed ) {
Assert.fail( "Assert true didn't fail" );
}
}
[Test(description="Ensure that the assertTrue functions fails when a false value is provided and the proper passed message is displayed")]
public function testAssertTrueWithMessageFails():void {
var message:String = "Assert true fail";
var failed:Boolean = false;
try {
Assert.assertTrue( message, false )
// if we get an error with the right message we pass
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( message + " - expected true but was false", error.message );
}
if ( !failed ) {
Assert.fail( "Assert true didn't fail" );
}
}
[Test(description="Ensure that the failNotTrue function correctly works when a value of true is provided")]
public function testFailNotTrue():void {
Assert.failNotTrue( "Fail not true fail", true );
}
[Test(description="Ensure that the failNotTrue function fails when a value of false is provided",
expects="flexunit.framework.AssertionFailedError")]
public function testFailNotTrueFails():void {
Assert.failNotTrue( "Fail not true fail", false );
}
[Test(description="Ensure that the assertFalse function correctly works when a value of false is provided")]
public function testAssertFalse():void {
Assert.assertFalse( false );
}
[Test(description="Ensure that the assertFalse function correctly works when a value of false and a message are provided")]
public function testAssertFalseWithMessage():void {
Assert.assertFalse( "Assert false fail", false );
}
[Test(description="Ensure that the assertFalse function fails when a value of true is provided")]
public function testAssertFalseFails():void {
var failed:Boolean = false;
try {
Assert.assertFalse( true )
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( "expected false but was true", error.message );
}
if ( !failed ) {
Assert.fail( "Assert false didn't fail" );
}
}
[Test(description="Ensure that the assertFalse function fails when a value of true is provided and the proper message is displayed")]
public function testAssertFalseWithMessageFails():void {
var message:String = "Assert false fail";
var failed:Boolean = false;
try {
Assert.assertFalse( message, true )
// if we get an error with the right message we pass
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( message + " - expected false but was true", error.message );
}
if ( !failed ) {
Assert.fail( "Assert false didn't fail" );
}
}
[Test(description="Ensure that the failTrue function correctly works when a value of false is provided")]
public function testFailTrue():void {
Assert.failTrue( "Fail true fail", false );
}
[Test(description="Ensure that the failTrue function fails when a value of true is provided",
expects="flexunit.framework.AssertionFailedError")]
public function testFailTrueFails():void {
Assert.failTrue( "Fail true fail", true );
}
[Test(description="Ensure that the assertNull function correctly works when a value of null is provided")]
public function testAssertNull():void {
Assert.assertNull( null );
}
[Test(description="Ensure that the assertNull function correctly works when a value of null and a message are provided")]
public function testAssertNullWithMessage():void {
Assert.assertNull( "Assert null fail", null );
}
[Test(description="Ensure that the assertNull function fails when a non-null value is provided")]
public function testAssertNullFails():void {
var o:Object = new Object();
var failed:Boolean = false;
try {
Assert.assertNull( o )
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( "object was not null: [object Object]", error.message );
}
if ( !failed ) {
Assert.fail( "Assert null didn't fail" );
}
}
[Test(description="Ensure that the assertNull functions fails when a non-null value is provided an the proper message is displayed")]
public function testAssertNullWithMessageFails():void {
var o:Object = new Object();
var failed:Boolean = false;
var message:String = "Assert null fail";
try {
Assert.assertNull( message, o )
// if we get an error with the right message we pass
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( message + " - object was not null: [object Object]", error.message );
}
if ( !failed ) {
Assert.fail( "Assert null didn't fail" );
}
}
[Test(description="Ensure that the failNull function works correctly when a non-null value is provided")]
public function testFailNull():void {
var o:Object = new Object();
Assert.failNull( "Fail null fail", o );
}
[Test(description="Ensure that the failNull function fails when a null value is provided",
expects="flexunit.framework.AssertionFailedError")]
public function testFailNullFails():void {
Assert.failNull( "Fail null fail", null );
}
[Test(description="Ensure the the assertNotNull function correctly works when a non-null value is provided")]
public function testAssertNotNull():void {
var o:Object = new Object();
Assert.assertNotNull( o );
}
[Test(description="Ensure that the assertNotNull function correctly works when a non-null value and a message are provided")]
public function testAssertNotNullWithMessage():void {
var o:Object = new Object();
Assert.assertNotNull( "Assert not null fail", o );
}
[Test(description="Ensure that the assertNotNull function fails when a null value is provided")]
public function testAssertNotNullFails():void {
var failed:Boolean = false;
try {
Assert.assertNotNull( null )
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( "object was null: null", error.message );
}
if ( !failed ) {
Assert.fail( "Assert not null didn't fail" );
}
}
[Test(description="Ensure that the assertNotNull function fails when a null value is provided and the proper message is displayed")]
public function testAssertNotNullWithMessageFails():void {
var failed:Boolean = false;
var message:String = "Assert not null fail";
try {
Assert.assertNotNull( message, null )
// if we get an error with the right message we pass
} catch ( error:AssertionFailedError ) {
failed = true;
Assert.assertEquals( message + " - object was null: null", error.message );
}
if ( !failed ) {
Assert.fail( "Assert not null didn't fail" );
}
}
[Test(description="Ensure that the failNotNull function works correctly when a null value is provided")]
public function testFailNotNull():void {
Assert.failNotNull( "Fail not null fail", null );
}
[Test(description="Ensure that the failNotNull function fails when a non-null value is provided")]
public function testFailNotNullFails():void {
var o:Object = new Object();
var failed:Boolean = false;
var message:String = "Fail not null fail";
try {
Assert.failNotNull( "Fail not null fail", o );
} catch(error:AssertionFailedError) {
failed = true;
Assert.assertEquals( message + " - object was not null: [object Object]", error.message );
}
if(!failed) {
Assert.fail("The failNotNull function has failed");
}
}
[Test(description="Ensure that the testFail function correctly throws an AssertionFailedError and sends the proper message")]
public function testFail():void {
var message:String = "Fail test";
var failed:Boolean = false;
try {
Assert.fail(message);
} catch(error:AssertionFailedError) {
failed = true;
Assert.assertEquals( message, error.message );
}
if(!failed) {
Assert.fail("The fail function has failed");
}
}
protected function test( obj:Object ):void {
asserterCalled++;
}
}
}
|
Update to complete the testFailNotStrictlyEqualsFails test.
|
Update to complete the testFailNotStrictlyEqualsFails test.
|
ActionScript
|
apache-2.0
|
apache/flex-flexunit,SlavaRa/flex-flexunit,SlavaRa/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit
|
1e09879d012a1391d59f2f605c848c440c5747af
|
src/org/mangui/flowplayer/HLSStreamProvider.as
|
src/org/mangui/flowplayer/HLSStreamProvider.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.flowplayer {
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.utils.Params2Settings;
import flash.display.DisplayObject;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.Dictionary;
import flash.media.Video;
import org.mangui.hls.HLS;
import org.mangui.hls.constant.HLSPlayStates;
import org.flowplayer.model.Plugin;
import org.flowplayer.model.PluginModel;
import org.flowplayer.view.Flowplayer;
import org.flowplayer.controller.StreamProvider;
import org.flowplayer.controller.TimeProvider;
import org.flowplayer.controller.VolumeController;
import org.flowplayer.model.Clip;
import org.flowplayer.model.ClipType;
import org.flowplayer.model.ClipEvent;
import org.flowplayer.model.ClipEventType;
import org.flowplayer.model.Playlist;
import org.flowplayer.view.StageVideoWrapper;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSStreamProvider implements StreamProvider,Plugin {
private var _volumecontroller : VolumeController;
private var _playlist : Playlist;
private var _timeProvider : TimeProvider;
private var _model : PluginModel;
private var _player : Flowplayer;
private var _clip : Clip;
private var _video : Video;
/** reference to the framework. **/
private var _hls : HLS;
// event values
private var _position : Number = 0;
private var _duration : Number = 0;
private var _bufferedTime : Number = 0;
private var _videoWidth : int = -1;
private var _videoHeight : int = -1;
private var _isManifestLoaded : Boolean = false;
private var _pauseAfterStart : Boolean;
private var _seekable : Boolean = false;
public function getDefaultConfig() : Object {
return null;
}
public function onConfig(model : PluginModel) : void {
CONFIG::LOGGING {
Log.info("onConfig()");
}
_model = model;
}
public function onLoad(player : Flowplayer) : void {
CONFIG::LOGGING {
Log.info("onLoad()");
}
_player = player;
_hls = new HLS();
_hls.stage = player.screen.getDisplayObject().stage;
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler);
_hls.addEventListener(HLSEvent.ERROR, _errorHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler);
_hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.addEventListener(HLSEvent.ID3_UPDATED, _ID3Handler);
var cfg : Object = _model.config;
for (var object : String in cfg) {
var subidx : int = object.indexOf("hls_");
if (subidx != -1) {
Params2Settings.set(object.substr(4), cfg[object]);
}
}
_model.dispatchOnLoad();
}
private function _completeHandler(event : HLSEvent) : void {
// dispatch a before event because the finish has default behavior that can be prevented by listeners
_clip.dispatchBeforeEvent(new ClipEvent(ClipEventType.FINISH));
};
private function _errorHandler(event : HLSEvent) : void {
};
private function _ID3Handler(event : HLSEvent) : void {
_clip.dispatch(ClipEventType.NETSTREAM_EVENT, "onID3", event.ID3Data);
};
private function _manifestHandler(event : HLSEvent) : void {
_duration = event.levels[_hls.startlevel].duration;
_isManifestLoaded = true;
_clip.duration = _duration;
_clip.stopLiveOnPause = false;
_clip.dispatch(ClipEventType.METADATA);
_seekable = true;
// if (_hls.type == HLSTypes.LIVE) {
// _seekable = false;
// } else {
// _seekable = true;
// }
_hls.stream.play();
_clip.dispatch(ClipEventType.SEEK);
if (_pauseAfterStart) {
pause(new ClipEvent(ClipEventType.PAUSE));
}
};
private function _mediaTimeHandler(event : HLSEvent) : void {
_position = Math.max(0, event.mediatime.position);
_duration = event.mediatime.duration;
_clip.duration = _duration;
_bufferedTime = event.mediatime.buffer + event.mediatime.position;
var videoWidth : int = _video.videoWidth;
var videoHeight : int = _video.videoHeight;
if (videoWidth && videoHeight) {
var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight;
if (changed) {
CONFIG::LOGGING {
Log.info("video size changed to " + videoWidth + "/" + videoHeight);
}
_videoWidth = videoWidth;
_videoHeight = videoHeight;
_clip.originalWidth = videoWidth;
_clip.originalHeight = videoHeight;
_clip.dispatch(ClipEventType.START);
_clip.dispatch(ClipEventType.METADATA_CHANGED);
}
}
};
private function _stateHandler(event : HLSEvent) : void {
// CONFIG::LOGGING {
// Log.txt("state:"+ event.state);
// }
switch(event.state) {
case HLSPlayStates.IDLE:
case HLSPlayStates.PLAYING:
case HLSPlayStates.PAUSED:
_clip.dispatch(ClipEventType.BUFFER_FULL);
break;
case HLSPlayStates.PLAYING_BUFFERING:
case HLSPlayStates.PAUSED_BUFFERING:
_clip.dispatch(ClipEventType.BUFFER_EMPTY);
break;
default:
break;
}
};
/**
* Starts loading the specified clip. Once video data is available the provider
* must set it to the clip using <code>clip.setContent()</code>. Typically the video
* object passed to the clip is an instance of <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">flash.media.Video</a>.
*
* @param event the event that this provider should dispatch once loading has successfully started,
* once dispatched the player will call <code>getVideo()</code>
* @param clip the clip to load
* @param pauseAfterStart if <code>true</code> the playback is paused on first frame and
* buffering is continued
* @see Clip#setContent()
* @see #getVideo()
*/
public function load(event : ClipEvent, clip : Clip, pauseAfterStart : Boolean = true) : void {
_clip = clip;
CONFIG::LOGGING {
Log.info("load()" + clip.completeUrl);
}
_hls.load(clip.completeUrl);
_pauseAfterStart = pauseAfterStart;
clip.type = ClipType.VIDEO;
clip.dispatch(ClipEventType.BEGIN);
clip.setNetStream(_hls.stream);
return;
}
/**
* Gets the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">Video</a> object.
* A stream will be attached to the returned video object using <code>attachStream()</code>.
* @param clip the clip for which the Video object is queried for
* @see #attachStream()
*/
public function getVideo(clip : Clip) : DisplayObject {
CONFIG::LOGGING {
Log.debug("getVideo()");
}
if (_video == null) {
if (clip.useStageVideo) {
CONFIG::LOGGING {
Log.debug("useStageVideo");
}
_video = new StageVideoWrapper(clip);
} else {
_video = new Video();
_video.smoothing = clip.smoothing;
}
}
return _video;
}
/**
* Attaches a stream to the specified display object.
* @param video the video object that was originally retrieved using <code>getVideo()</code>.
* @see #getVideo()
*/
public function attachStream(video : DisplayObject) : void {
CONFIG::LOGGING {
Log.debug("attachStream()");
}
Video(video).attachNetStream(_hls.stream);
return;
}
/**
* Pauses playback.
* @param event the event that this provider should dispatch once loading has been successfully paused
*/
public function pause(event : ClipEvent) : void {
CONFIG::LOGGING {
Log.info("pause()");
}
_hls.stream.pause();
if (event) {
_clip.dispatch(ClipEventType.PAUSE);
}
return;
}
/**
* Resumes playback.
* @param event the event that this provider should dispatch once loading has been successfully resumed
*/
public function resume(event : ClipEvent) : void {
CONFIG::LOGGING {
Log.info("resume()");
}
_hls.stream.resume();
_clip.dispatch(ClipEventType.RESUME);
return;
}
/**
* Stops and rewinds to the beginning of current clip.
* @param event the event that this provider should dispatch once loading has been successfully stopped
*/
public function stop(event : ClipEvent, closeStream : Boolean = false) : void {
CONFIG::LOGGING {
Log.info("stop()");
}
_hls.stream.close();
return;
}
/**
* Seeks to the specified point in the timeline.
* @param event the event that this provider should dispatch once the seek is in target
* @param seconds the target point in the timeline
*/
public function seek(event : ClipEvent, seconds : Number) : void {
CONFIG::LOGGING {
Log.info("seek()");
}
_hls.stream.seek(seconds);
_position = seconds;
_bufferedTime = seconds;
_clip.dispatch(ClipEventType.SEEK, seconds);
return;
}
/**
* File size in bytes.
*/
public function get fileSize() : Number {
return 0;
}
/**
* Current playhead time in seconds.
*/
public function get time() : Number {
return _position;
}
/**
* The point in timeline where the buffered data region begins, in seconds.
*/
public function get bufferStart() : Number {
return 0;
}
/**
* The point in timeline where the buffered data region ends, in seconds.
*/
public function get bufferEnd() : Number {
return _bufferedTime;
}
/**
* Does this provider support random seeking to unbuffered areas in the timeline?
*/
public function get allowRandomSeek() : Boolean {
// CONFIG::LOGGING {
// Log.info("allowRandomSeek()");
// }
return _seekable;
}
/**
* Volume controller used to control the video volume.
*/
public function set volumeController(controller : VolumeController) : void {
_volumecontroller = controller;
_volumecontroller.netStream = _hls.stream;
return;
}
/**
* Is this provider in the process of stopping the stream?
* When stopped the provider should not dispatch any events resulting from events that
* might get triggered by the underlying streaming implementation.
*/
public function get stopping() : Boolean {
CONFIG::LOGGING {
Log.info("stopping()");
}
return false;
}
/**
* The playlist instance.
*/
public function set playlist(playlist : Playlist) : void {
// CONFIG::LOGGING {
// Log.debug("set playlist()");
// }
_playlist = playlist;
return;
}
public function get playlist() : Playlist {
CONFIG::LOGGING {
Log.debug("get playlist()");
}
return _playlist;
}
/**
* Adds a callback public function to the NetConnection instance. This public function will fire ClipEvents whenever
* the callback is invoked in the connection.
* @param name
* @param listener
* @return
* @see ClipEventType#CONNECTION_EVENT
*/
public function addConnectionCallback(name : String, listener : Function) : void {
CONFIG::LOGGING {
Log.debug("addConnectionCallback()");
}
return;
}
/**
* Adds a callback public function to the NetStream object. This public function will fire a ClipEvent of type StreamEvent whenever
* the callback has been invoked on the stream. The invokations typically come from a server-side app running
* on RTMP server.
* @param name
* @param listener
* @return
* @see ClipEventType.NETSTREAM_EVENT
*/
public function addStreamCallback(name : String, listener : Function) : void {
CONFIG::LOGGING {
Log.debug("addStreamCallback()");
}
return;
}
/**
* Get the current stream callbacks.
* @return a dictionary of callbacks, keyed using callback names and values being the callback functions
*/
public function get streamCallbacks() : Dictionary {
CONFIG::LOGGING {
Log.debug("get streamCallbacks()");
}
return null;
}
/**
* Gets the underlying NetStream object.
* @return the netStream currently in use, or null if this provider has not started streaming yet
*/
public function get netStream() : NetStream {
CONFIG::LOGGING {
Log.debug("get netStream()");
}
return _hls.stream;
}
/**
* Gets the underlying netConnection object.
* @return the netConnection currently in use, or null if this provider has not started streaming yet
*/
public function get netConnection() : NetConnection {
CONFIG::LOGGING {
Log.debug("get netConnection()");
}
return null;
}
/**
* Sets a time provider to be used by this StreamProvider. Normally the playhead time is queried from
* the NetStream.time property.
*
* @param timeProvider
*/
public function set timeProvider(timeProvider : TimeProvider) : void {
CONFIG::LOGGING {
Log.debug("set timeProvider()");
}
_timeProvider = timeProvider;
return;
}
/**
* Gets the type of StreamProvider either http, rtmp, psuedo.
*/
public function get type() : String {
return "httpstreaming";
}
/**
* Switch the stream in realtime with / without dynamic stream switching support
*
* @param event ClipEvent the clip event
* @param clip Clip the clip to switch to
* @param netStreamPlayOptions Object the NetStreamPlayOptions object to enable dynamic stream switching
*/
public function switchStream(event : ClipEvent, clip : Clip, netStreamPlayOptions : Object = null) : void {
CONFIG::LOGGING {
Log.info("switchStream()");
}
return;
}
}
}
|
/* 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.flowplayer {
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.utils.Params2Settings;
import flash.display.DisplayObject;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.utils.Dictionary;
import flash.media.Video;
import org.mangui.hls.HLS;
import org.mangui.hls.constant.HLSPlayStates;
import org.flowplayer.model.Plugin;
import org.flowplayer.model.PluginModel;
import org.flowplayer.view.Flowplayer;
import org.flowplayer.controller.StreamProvider;
import org.flowplayer.controller.TimeProvider;
import org.flowplayer.controller.VolumeController;
import org.flowplayer.model.Clip;
import org.flowplayer.model.ClipType;
import org.flowplayer.model.ClipEvent;
import org.flowplayer.model.ClipEventType;
import org.flowplayer.model.Playlist;
import org.flowplayer.view.StageVideoWrapper;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSStreamProvider implements StreamProvider,Plugin {
private var _volumecontroller : VolumeController;
private var _playlist : Playlist;
private var _timeProvider : TimeProvider;
private var _model : PluginModel;
private var _player : Flowplayer;
private var _clip : Clip;
private var _video : Video;
/** reference to the framework. **/
private var _hls : HLS;
// event values
private var _position : Number = 0;
private var _duration : Number = 0;
private var _bufferedTime : Number = 0;
private var _videoWidth : int = -1;
private var _videoHeight : int = -1;
private var _isManifestLoaded : Boolean = false;
private var _pauseAfterStart : Boolean;
private var _seekable : Boolean = false;
public function getDefaultConfig() : Object {
return null;
}
public function onConfig(model : PluginModel) : void {
CONFIG::LOGGING {
Log.info("onConfig()");
}
_model = model;
}
public function onLoad(player : Flowplayer) : void {
CONFIG::LOGGING {
Log.info("onLoad()");
}
_player = player;
_hls = new HLS();
_hls.stage = player.screen.getDisplayObject().stage;
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _completeHandler);
_hls.addEventListener(HLSEvent.ERROR, _errorHandler);
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestHandler);
_hls.addEventListener(HLSEvent.MEDIA_TIME, _mediaTimeHandler);
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateHandler);
_hls.addEventListener(HLSEvent.ID3_UPDATED, _ID3Handler);
var cfg : Object = _model.config;
for (var object : String in cfg) {
var subidx : int = object.indexOf("hls_");
if (subidx != -1) {
Params2Settings.set(object.substr(4), cfg[object]);
}
}
_model.dispatchOnLoad();
}
private function _completeHandler(event : HLSEvent) : void {
// dispatch a before event because the finish has default behavior that can be prevented by listeners
_clip.dispatchBeforeEvent(new ClipEvent(ClipEventType.FINISH));
};
private function _errorHandler(event : HLSEvent) : void {
};
private function _ID3Handler(event : HLSEvent) : void {
_clip.dispatch(ClipEventType.NETSTREAM_EVENT, "onID3", event.ID3Data);
};
private function _manifestHandler(event : HLSEvent) : void {
_duration = event.levels[_hls.startlevel].duration;
_isManifestLoaded = true;
_clip.duration = _duration;
_clip.stopLiveOnPause = false;
_clip.dispatch(ClipEventType.METADATA);
_seekable = true;
// if (_hls.type == HLSTypes.LIVE) {
// _seekable = false;
// } else {
// _seekable = true;
// }
_hls.stream.play();
_clip.dispatch(ClipEventType.SEEK,0);
if (_pauseAfterStart) {
pause(new ClipEvent(ClipEventType.PAUSE));
}
};
private function _mediaTimeHandler(event : HLSEvent) : void {
_position = Math.max(0, event.mediatime.position);
_duration = event.mediatime.duration;
_clip.duration = _duration;
_bufferedTime = event.mediatime.buffer + event.mediatime.position;
var videoWidth : int = _video.videoWidth;
var videoHeight : int = _video.videoHeight;
if (videoWidth && videoHeight) {
var changed : Boolean = _videoWidth != videoWidth || _videoHeight != videoHeight;
if (changed) {
CONFIG::LOGGING {
Log.info("video size changed to " + videoWidth + "/" + videoHeight);
}
_videoWidth = videoWidth;
_videoHeight = videoHeight;
_clip.originalWidth = videoWidth;
_clip.originalHeight = videoHeight;
_clip.dispatch(ClipEventType.START);
_clip.dispatch(ClipEventType.METADATA_CHANGED);
}
}
};
private function _stateHandler(event : HLSEvent) : void {
// CONFIG::LOGGING {
// Log.txt("state:"+ event.state);
// }
switch(event.state) {
case HLSPlayStates.IDLE:
case HLSPlayStates.PLAYING:
case HLSPlayStates.PAUSED:
_clip.dispatch(ClipEventType.BUFFER_FULL);
break;
case HLSPlayStates.PLAYING_BUFFERING:
case HLSPlayStates.PAUSED_BUFFERING:
_clip.dispatch(ClipEventType.BUFFER_EMPTY);
break;
default:
break;
}
};
/**
* Starts loading the specified clip. Once video data is available the provider
* must set it to the clip using <code>clip.setContent()</code>. Typically the video
* object passed to the clip is an instance of <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">flash.media.Video</a>.
*
* @param event the event that this provider should dispatch once loading has successfully started,
* once dispatched the player will call <code>getVideo()</code>
* @param clip the clip to load
* @param pauseAfterStart if <code>true</code> the playback is paused on first frame and
* buffering is continued
* @see Clip#setContent()
* @see #getVideo()
*/
public function load(event : ClipEvent, clip : Clip, pauseAfterStart : Boolean = true) : void {
_clip = clip;
CONFIG::LOGGING {
Log.info("load()" + clip.completeUrl);
}
_hls.load(clip.completeUrl);
_pauseAfterStart = pauseAfterStart;
clip.type = ClipType.VIDEO;
clip.dispatch(ClipEventType.BEGIN);
clip.setNetStream(_hls.stream);
return;
}
/**
* Gets the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Video.html">Video</a> object.
* A stream will be attached to the returned video object using <code>attachStream()</code>.
* @param clip the clip for which the Video object is queried for
* @see #attachStream()
*/
public function getVideo(clip : Clip) : DisplayObject {
CONFIG::LOGGING {
Log.debug("getVideo()");
}
if (_video == null) {
if (clip.useStageVideo) {
CONFIG::LOGGING {
Log.debug("useStageVideo");
}
_video = new StageVideoWrapper(clip);
} else {
_video = new Video();
_video.smoothing = clip.smoothing;
}
}
return _video;
}
/**
* Attaches a stream to the specified display object.
* @param video the video object that was originally retrieved using <code>getVideo()</code>.
* @see #getVideo()
*/
public function attachStream(video : DisplayObject) : void {
CONFIG::LOGGING {
Log.debug("attachStream()");
}
Video(video).attachNetStream(_hls.stream);
return;
}
/**
* Pauses playback.
* @param event the event that this provider should dispatch once loading has been successfully paused
*/
public function pause(event : ClipEvent) : void {
CONFIG::LOGGING {
Log.info("pause()");
}
_hls.stream.pause();
if (event) {
_clip.dispatch(ClipEventType.PAUSE);
}
return;
}
/**
* Resumes playback.
* @param event the event that this provider should dispatch once loading has been successfully resumed
*/
public function resume(event : ClipEvent) : void {
CONFIG::LOGGING {
Log.info("resume()");
}
_hls.stream.resume();
_clip.dispatch(ClipEventType.RESUME);
return;
}
/**
* Stops and rewinds to the beginning of current clip.
* @param event the event that this provider should dispatch once loading has been successfully stopped
*/
public function stop(event : ClipEvent, closeStream : Boolean = false) : void {
CONFIG::LOGGING {
Log.info("stop()");
}
_hls.stream.close();
return;
}
/**
* Seeks to the specified point in the timeline.
* @param event the event that this provider should dispatch once the seek is in target
* @param seconds the target point in the timeline
*/
public function seek(event : ClipEvent, seconds : Number) : void {
CONFIG::LOGGING {
Log.info("seek()");
}
_hls.stream.seek(seconds);
_position = seconds;
_bufferedTime = seconds;
_clip.dispatch(ClipEventType.SEEK, seconds);
return;
}
/**
* File size in bytes.
*/
public function get fileSize() : Number {
return 0;
}
/**
* Current playhead time in seconds.
*/
public function get time() : Number {
return _position;
}
/**
* The point in timeline where the buffered data region begins, in seconds.
*/
public function get bufferStart() : Number {
return 0;
}
/**
* The point in timeline where the buffered data region ends, in seconds.
*/
public function get bufferEnd() : Number {
return _bufferedTime;
}
/**
* Does this provider support random seeking to unbuffered areas in the timeline?
*/
public function get allowRandomSeek() : Boolean {
// CONFIG::LOGGING {
// Log.info("allowRandomSeek()");
// }
return _seekable;
}
/**
* Volume controller used to control the video volume.
*/
public function set volumeController(controller : VolumeController) : void {
_volumecontroller = controller;
_volumecontroller.netStream = _hls.stream;
return;
}
/**
* Is this provider in the process of stopping the stream?
* When stopped the provider should not dispatch any events resulting from events that
* might get triggered by the underlying streaming implementation.
*/
public function get stopping() : Boolean {
CONFIG::LOGGING {
Log.info("stopping()");
}
return false;
}
/**
* The playlist instance.
*/
public function set playlist(playlist : Playlist) : void {
// CONFIG::LOGGING {
// Log.debug("set playlist()");
// }
_playlist = playlist;
return;
}
public function get playlist() : Playlist {
CONFIG::LOGGING {
Log.debug("get playlist()");
}
return _playlist;
}
/**
* Adds a callback public function to the NetConnection instance. This public function will fire ClipEvents whenever
* the callback is invoked in the connection.
* @param name
* @param listener
* @return
* @see ClipEventType#CONNECTION_EVENT
*/
public function addConnectionCallback(name : String, listener : Function) : void {
CONFIG::LOGGING {
Log.debug("addConnectionCallback()");
}
return;
}
/**
* Adds a callback public function to the NetStream object. This public function will fire a ClipEvent of type StreamEvent whenever
* the callback has been invoked on the stream. The invokations typically come from a server-side app running
* on RTMP server.
* @param name
* @param listener
* @return
* @see ClipEventType.NETSTREAM_EVENT
*/
public function addStreamCallback(name : String, listener : Function) : void {
CONFIG::LOGGING {
Log.debug("addStreamCallback()");
}
return;
}
/**
* Get the current stream callbacks.
* @return a dictionary of callbacks, keyed using callback names and values being the callback functions
*/
public function get streamCallbacks() : Dictionary {
CONFIG::LOGGING {
Log.debug("get streamCallbacks()");
}
return null;
}
/**
* Gets the underlying NetStream object.
* @return the netStream currently in use, or null if this provider has not started streaming yet
*/
public function get netStream() : NetStream {
CONFIG::LOGGING {
Log.debug("get netStream()");
}
return _hls.stream;
}
/**
* Gets the underlying netConnection object.
* @return the netConnection currently in use, or null if this provider has not started streaming yet
*/
public function get netConnection() : NetConnection {
CONFIG::LOGGING {
Log.debug("get netConnection()");
}
return null;
}
/**
* Sets a time provider to be used by this StreamProvider. Normally the playhead time is queried from
* the NetStream.time property.
*
* @param timeProvider
*/
public function set timeProvider(timeProvider : TimeProvider) : void {
CONFIG::LOGGING {
Log.debug("set timeProvider()");
}
_timeProvider = timeProvider;
return;
}
/**
* Gets the type of StreamProvider either http, rtmp, psuedo.
*/
public function get type() : String {
return "httpstreaming";
}
/**
* Switch the stream in realtime with / without dynamic stream switching support
*
* @param event ClipEvent the clip event
* @param clip Clip the clip to switch to
* @param netStreamPlayOptions Object the NetStreamPlayOptions object to enable dynamic stream switching
*/
public function switchStream(event : ClipEvent, clip : Clip, netStreamPlayOptions : Object = null) : void {
CONFIG::LOGGING {
Log.info("switchStream()");
}
return;
}
}
}
|
fix seek bar not being updated when replaying a video
|
flashlsFlowPlayer.swf: fix seek bar not being updated when replaying a video
|
ActionScript
|
mpl-2.0
|
mangui/flashls,suuhas/flashls,JulianPena/flashls,ryanhefner/flashls,aevange/flashls,neilrackett/flashls,dighan/flashls,hola/flashls,School-Improvement-Network/flashls,vidible/vdb-flashls,Peer5/flashls,clappr/flashls,suuhas/flashls,mangui/flashls,Peer5/flashls,NicolasSiver/flashls,loungelogic/flashls,viktorot/flashls,thdtjsdn/flashls,tedconf/flashls,Peer5/flashls,suuhas/flashls,JulianPena/flashls,School-Improvement-Network/flashls,Boxie5/flashls,ryanhefner/flashls,clappr/flashls,viktorot/flashls,Peer5/flashls,ryanhefner/flashls,vidible/vdb-flashls,Boxie5/flashls,fixedmachine/flashls,suuhas/flashls,NicolasSiver/flashls,tedconf/flashls,dighan/flashls,neilrackett/flashls,Corey600/flashls,jlacivita/flashls,fixedmachine/flashls,hola/flashls,School-Improvement-Network/flashls,aevange/flashls,aevange/flashls,Corey600/flashls,jlacivita/flashls,viktorot/flashls,aevange/flashls,ryanhefner/flashls,codex-corp/flashls,codex-corp/flashls,thdtjsdn/flashls,loungelogic/flashls
|
bfe8760ce10fe3d9215c7d14a644ae7c90911bea
|
src/aerys/minko/type/vertex/format/VertexFormat.as
|
src/aerys/minko/type/vertex/format/VertexFormat.as
|
package aerys.minko.type.vertex.format
{
public class VertexFormat
{
public static const XYZ : VertexFormat = new VertexFormat(VertexComponent.XYZ);
public static const XYZ_RGB : VertexFormat = new VertexFormat(VertexComponent.XYZ,
VertexComponent.RGB);
public static const XYZ_UV : VertexFormat = new VertexFormat(VertexComponent.XYZ,
VertexComponent.UV);
public static const XYZ_UV_ST : VertexFormat = new VertexFormat(VertexComponent.XYZ,
VertexComponent.UV,
VertexComponent.ST);
protected var _components : Object;
private var _dwordsPerVertex : int = 0;
private var _componentOffsets : Object = new Object();
private var _fieldOffsets : Object = new Object();
public function get components() : Object { return _components; }
public function get dwordsPerVertex() : int { return _dwordsPerVertex; }
public function VertexFormat(...components)
{
_components = new Object();
if (components)
initialize(components);
}
private function initialize(components : Array) : void
{
for each (var component : VertexComponent in components)
addComponent(component);
}
private function addComponent(component : VertexComponent) : void
{
_components[component.implodedFields] = component;
_componentOffsets[component.implodedFields] = _dwordsPerVertex;
for (var fieldName : String in component.offsets)
_fieldOffsets[fieldName] = _dwordsPerVertex + component.offsets[fieldName];
_dwordsPerVertex += component.dwords;
}
/**
* Determine if this Vertex3DFormat has the specified component
*/
public function hasComponent(component : VertexComponent) : Boolean
{
return _components.hasOwnProperty(component.implodedFields);
}
/**
* Determine if this Vertex3DFormat is a subset of the Vertex3DFormat passed in attribute
*/
public function isSubsetOf(otherVertexFormat : VertexFormat) : Boolean
{
for (var implodedFields : String in _components)
if (!otherVertexFormat._components.hasOwnProperty(implodedFields))
return false;
return true;
}
/**
* Add the components from the vertex format passed in attribute that we don't have in this one.
*/
public function unionWith(otherVertexFormat : VertexFormat) : void
{
for each (var component : VertexComponent in otherVertexFormat._components)
addComponent(component);
}
public function getOffsetForComponent(component : VertexComponent) : int
{
return _componentOffsets[component.implodedFields];
}
public function getOffsetForField(fieldName:String) : int
{
return _fieldOffsets[fieldName];
}
}
}
|
package aerys.minko.type.vertex.format
{
public class VertexFormat
{
public static const XYZ : VertexFormat = new VertexFormat(VertexComponent.XYZ);
public static const XYZ_RGB : VertexFormat = new VertexFormat(VertexComponent.XYZ,
VertexComponent.RGB);
public static const XYZ_UV : VertexFormat = new VertexFormat(VertexComponent.XYZ,
VertexComponent.UV);
public static const XYZ_UV_ST : VertexFormat = new VertexFormat(VertexComponent.XYZ,
VertexComponent.UV,
VertexComponent.ST);
protected var _components : Object;
private var _dwordsPerVertex : int = 0;
private var _componentOffsets : Object = new Object();
private var _fieldOffsets : Object = new Object();
public function get components() : Object { return _components; }
public function get dwordsPerVertex() : int { return _dwordsPerVertex; }
public function VertexFormat(...components)
{
_components = new Object();
if (components)
initialize(components);
}
private function initialize(components : Array) : void
{
for each (var component : VertexComponent in components)
addComponent(component);
}
public function addComponent(component : VertexComponent) : void
{
_components[component.implodedFields] = component;
_componentOffsets[component.implodedFields] = _dwordsPerVertex;
for (var fieldName : String in component.offsets)
_fieldOffsets[fieldName] = _dwordsPerVertex + component.offsets[fieldName];
_dwordsPerVertex += component.dwords;
}
/**
* Determine if this Vertex3DFormat has the specified component
*/
public function hasComponent(component : VertexComponent) : Boolean
{
return _components.hasOwnProperty(component.implodedFields);
}
/**
* Determine if this Vertex3DFormat is a subset of the Vertex3DFormat passed in attribute
*/
public function isSubsetOf(otherVertexFormat : VertexFormat) : Boolean
{
for (var implodedFields : String in _components)
if (!otherVertexFormat._components.hasOwnProperty(implodedFields))
return false;
return true;
}
/**
* Add the components from the vertex format passed in attribute that we don't have in this one.
*/
public function unionWith(otherVertexFormat : VertexFormat) : void
{
for each (var component : VertexComponent in otherVertexFormat._components)
addComponent(component);
}
public function getOffsetForComponent(component : VertexComponent) : int
{
return _componentOffsets[component.implodedFields];
}
public function getOffsetForField(fieldName : String) : int
{
return _fieldOffsets[fieldName];
}
}
}
|
Change the visibility of the "addComponent" method in VertexFormat
|
Change the visibility of the "addComponent" method in VertexFormat
|
ActionScript
|
mit
|
aerys/minko-as3
|
02cc2de354764098af01057ff12b8944c4fc6c4c
|
src/common/mvc/model/base/BaseModel.as
|
src/common/mvc/model/base/BaseModel.as
|
package common.mvc.model.base
{
import hu.vizoli.common.mvc.actor.BaseActor;
/**
* Base Model.
*
* @author vizoli
*/
public class BaseModel extends BaseActor
{
public function BaseModel()
{
}
}
}
|
package common.mvc.model.base
{
import common.mvc.actor.BaseActor;
/**
* Base Model.
*
* @author vizoli
*/
public class BaseModel extends BaseActor
{
public function BaseModel()
{
}
}
}
|
Fix import
|
Fix import
|
ActionScript
|
apache-2.0
|
goc-flashplusplus/ageofai
|
dd860851e773df1ee92b5cb2c9a77899d0042d51
|
tamarin-central/thane/as3src/flash/utils/Timer.as
|
tamarin-central/thane/as3src/flash/utils/Timer.as
|
//
// $Id: $
package flash.utils {
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import de.polygonal.ds.Heap;
public class Timer extends EventDispatcher
{
public function Timer (delay :Number, repeatCount :int = 0)
{
if (_heap == null) {
_heap = new Heap(10000, compareTimers);
Thane.requestHeartbeat(heartbeat);
}
_delay = delay;
_repeatCount = repeatCount;
reset();
}
public function get currentCount () :int
{
return _currentCount;
}
public function get delay () :Number
{
return _delay;
}
public function set delay (value :Number) :void
{
_delay = value;
if (running) {
stop();
start();
}
}
public function get repeatCount () :int
{
return _repeatCount;
}
public function get running () :Boolean
{
return _buddy != null;
}
public function start () :void
{
if (_buddy != null) {
return;
}
scheduleBuddy(new Buddy(this));
}
public function stop () :void
{
// cut any current enqueued buddy adrift
if (_buddy != null) {
_buddy.budette = null;
_buddy = null;
}
}
public function reset () :void
{
stop();
_currentCount = 0;
}
protected function expire (buddy :Buddy) :void
{
if (buddy !== _buddy) {
// the timer was stopped since this buddy was enqueued
return;
}
_currentCount ++;
dispatchEvent(new TimerEvent(TimerEvent.TIMER));
if (_buddy == null) {
// the timer was stopped in the TIMER event itself - do not requeue!
return;
}
if (repeatCount == 0 || _currentCount < _repeatCount) {
scheduleBuddy(_buddy);
} else {
dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
_buddy = null;
}
}
private function scheduleBuddy (buddy :Buddy) :void
{
_buddy = buddy;
_buddy.expiration = getTimer() + Math.max(_delay, 5);
if (_heap.enqueue(_buddy)) {
return;
}
// TODO: formalize this as a quota rather than an implementation deficiency?
throw new Error("Too many simultaneous running flash.utils.Timer objects");
}
private static function compareTimers (a :Buddy, b :Buddy) :int
{
// b-a rather than a-b so as to order low values before high
return b.expiration - a.expiration;
}
protected static function heartbeat () :void
{
var now :int = getTimer();
// see if we should pop one timer off the queue and expire it; we could pop all the
// outstanding ones, but this solution puts the onus on developers to make their event
// handlers light-weight, and protects the socket code from starvation
if (_heap.size > 0 && _heap.front.expiration <= now) {
var buddy :Buddy = _heap.dequeue();
if (buddy.budette != null) {
buddy.budette.expire(buddy);
}
}
}
static function createTimer (closure :Function, delay :Number,
timeout :Boolean, args :Array) :uint
{
var timer :Timer = new Timer(delay, timeout ? 1 : 0);
var thisIx = _timerIx;
var fun :Function = function (event :TimerEvent) :void {
if (timeout) {
destroyTimer(thisIx);
}
closure.apply(null, args);
};
timer.addEventListener(TimerEvent.TIMER, fun);
_timers[_timerIx] = [ timer, fun ];
timer.start();
return _timerIx ++;
}
static function destroyTimer (id :uint) :void
{
var bits :Array = _timers[id];
if (bits) {
bits[0].removeEventListener(TimerEvent.TIMER, bits[1]);
bits[0].stop();
delete _timers[id];
}
}
private var _currentCount :int;
private var _delay :Number;
private var _repeatCount :int;
private var _buddy :Buddy;
private static var _heap :Heap;
private static var _timers :Dictionary = new Dictionary();
private static var _timerIx :uint = 1;
}
}
import flash.utils.Timer;
import flash.utils.getTimer;
class Buddy {
public var budette :Timer;
public var expiration :int;
public function Buddy (timer :Timer)
{
this.budette = timer;
}
}
|
//
// $Id: $
package flash.utils {
import flash.events.EventDispatcher;
import flash.events.TimerEvent;
import de.polygonal.ds.Heap;
public class Timer extends EventDispatcher
{
public function Timer (delay :Number, repeatCount :int = 0)
{
if (_heap == null) {
_heap = new Heap(10000, compareTimers);
Thane.requestHeartbeat(heartbeat);
}
_delay = delay;
_repeatCount = repeatCount;
reset();
}
/** The total number of times the timer has fired since it started at zero. */
public function get currentCount () :int
{
return _currentCount;
}
/** The delay, in milliseconds, between timer events. */
public function get delay () :Number
{
return _delay;
}
/** The delay, in milliseconds, between timer events. */
public function set delay (value :Number) :void
{
_delay = value;
if (running) {
stop();
start();
}
}
/** The total number of times the timer is set to run. */
public function get repeatCount () :int
{
return _repeatCount;
}
/** The total number of times the timer is set to run. */
public function set repeatCount (count :int) :void
{
_repeatCount = count;
if (_repeatCount > 0 && _repeatCount < _currentCount) {
stop();
}
}
/** The timer's current state; true if the timer is running, otherwise false. */
public function get running () :Boolean
{
return _buddy != null;
}
/**
* Starts the timer, if it is not already running.
*/
public function start () :void
{
if (_buddy != null) {
return;
}
scheduleBuddy(new Buddy(this));
}
/**
* Stops the timer.
*/
public function stop () :void
{
// cut any current enqueued buddy adrift
if (_buddy != null) {
_buddy.budette = null;
_buddy = null;
}
}
/**
* Stops the timer, if it is running, and sets the currentCount property back to 0,
* like the reset button of a stopwatch.
*/
public function reset () :void
{
stop();
_currentCount = 0;
}
protected function expire (buddy :Buddy) :void
{
if (buddy !== _buddy) {
// the timer was stopped since this buddy was enqueued
return;
}
_currentCount ++;
dispatchEvent(new TimerEvent(TimerEvent.TIMER));
// if the timer was stop()'ed in the TIMER event itself, do not requeue!
if (_buddy == null) {
return;
}
// if we're repeating forever, or still got a ways to go, reschedule, else finish
if (repeatCount == 0 || _currentCount < _repeatCount) {
scheduleBuddy(_buddy);
} else {
dispatchEvent(new TimerEvent(TimerEvent.TIMER_COMPLETE));
_buddy = null;
}
}
private function scheduleBuddy (buddy :Buddy) :void
{
_buddy = buddy;
_buddy.expiration = getTimer() + Math.max(_delay, 5);
if (_heap.enqueue(_buddy)) {
return;
}
// TODO: formalize this as a quota rather than an implementation deficiency?
throw new Error("Too many simultaneous running flash.utils.Timer objects");
}
private static function compareTimers (a :Buddy, b :Buddy) :int
{
// b-a rather than a-b so as to order low values before high
return b.expiration - a.expiration;
}
protected static function heartbeat () :void
{
var now :int = getTimer();
// see if we should pop one timer off the queue and expire it; we could pop all the
// outstanding ones, but this solution puts the onus on developers to make their event
// handlers light-weight, and protects the socket code from starvation
if (_heap.size > 0 && _heap.front.expiration <= now) {
var buddy :Buddy = _heap.dequeue();
if (buddy.budette != null) {
buddy.budette.expire(buddy);
}
}
}
static function createTimer (closure :Function, delay :Number,
timeout :Boolean, args :Array) :uint
{
var timer :Timer = new Timer(delay, timeout ? 1 : 0);
var thisIx = _timerIx;
var fun :Function = function (event :TimerEvent) :void {
if (timeout) {
destroyTimer(thisIx);
}
closure.apply(null, args);
};
timer.addEventListener(TimerEvent.TIMER, fun);
_timers[_timerIx] = [ timer, fun ];
timer.start();
return _timerIx ++;
}
static function destroyTimer (id :uint) :void
{
var bits :Array = _timers[id];
if (bits) {
bits[0].removeEventListener(TimerEvent.TIMER, bits[1]);
bits[0].stop();
delete _timers[id];
}
}
private var _currentCount :int;
private var _delay :Number;
private var _repeatCount :int;
private var _buddy :Buddy;
private static var _heap :Heap;
private static var _timers :Dictionary = new Dictionary();
private static var _timerIx :uint = 1;
}
}
import flash.utils.Timer;
import flash.utils.getTimer;
class Buddy {
public var budette :Timer;
public var expiration :int;
public function Buddy (timer :Timer)
{
this.budette = timer;
}
}
|
Make Timer.repeatCount writeable (and mimic Flash Player's behaviour when you set it to a value higher than the currentCount).
|
Make Timer.repeatCount writeable (and mimic Flash Player's behaviour when you set it to a value higher than the currentCount).
|
ActionScript
|
bsd-2-clause
|
greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane,greyhavens/thane
|
36b41428489a8381419ead4061118f3c4c79b3ac
|
src/com/google/analytics/core/DomainNameMode.as
|
src/com/google/analytics/core/DomainNameMode.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.core
{
/**
* The domain name mode enumeration class.
*/
public class DomainNameMode
{
/**
* @private
*/
private var _value:int;
/**
* @private
*/
private var _name:String;
/**
* Creates a new DomainNameMode instance.
* @param value The enumeration value representation.
* @param name The enumeration name representation.
*/
public function DomainNameMode( value:int = 0, name:String = "" )
{
_value = value;
_name = name;
}
/**
* Returns the primitive value of the object.
* @return the primitive value of the object.
*/
public function valueOf():int
{
return _value;
}
/**
* Returns the String representation of the object.
* @return the String representation of the object.
*/
public function toString():String
{
return _name;
}
/**
* Determinates the "none" DomainNameMode value.
* <p>"none" is used in the following two situations :</p>
* <p>- You want to disable tracking across hosts.</p>
* <p>- You want to set up tracking across two separate domains.</p>
* <p>Cross- domain tracking requires configuration of the setAllowLinker() and link() methods.</p>
*/
public static const none:DomainNameMode = new DomainNameMode( 0, "none" );
/**
* Attempts to automaticaly resolve the domain name.
*/
public static const auto:DomainNameMode = new DomainNameMode( 1, "auto" );
/**
* Custom is used to set explicitly to your domain name if your website spans multiple hostnames,
* and you want to track visitor behavior across all hosts.
* <p>For example, if you have two hosts : <code>server1.example.com</code> and <code>server2.example.com</code>,
* you would set the domain name as follows :
* <pre class="prettyprint">
* pageTracker.setDomainName( new Domain( DomainName.custom, ".example.com" ) ) ;
* </pre>
*/
public static const custom:DomainNameMode = new DomainNameMode( 2, "custom" );
}
}
|
/*
* 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.core
{
/**
* The domain name mode enumeration class.
*/
public class DomainNameMode
{
/**
* @private
*/
private var _value:int;
/**
* @private
*/
private var _name:String;
/**
* Creates a new DomainNameMode instance.
* @param value The enumeration value representation.
* @param name The enumeration name representation.
*/
public function DomainNameMode( value:int = 0, name:String = "" )
{
_value = value;
_name = name;
}
/**
* Returns the primitive value of the object.
* @return the primitive value of the object.
*/
public function valueOf():int
{
return _value;
}
/**
* Returns the String representation of the object.
* @return the String representation of the object.
*/
public function toString():String
{
return _name;
}
/**
* Determinates the "none" DomainNameMode value.
* <p>"none" is used in the following two situations :</p>
* <p>- You want to disable tracking across hosts.</p>
* <p>- You want to set up tracking across two separate domains.</p>
* <p>Cross- domain tracking requires configuration of the setAllowLinker() and link() methods.</p>
*/
public static const none:DomainNameMode = new DomainNameMode( 0, "none" );
/**
* Attempts to automaticaly resolve the domain name.
*/
public static const auto:DomainNameMode = new DomainNameMode( 1, "auto" );
/**
* Custom is used to set explicitly to your domain name if your website spans multiple hostnames,
* and you want to track visitor behavior across all hosts.
* <p>For example, if you have two hosts : <code>server1.example.com</code> and <code>server2.example.com</code>,
* you would set the domain name as follows :
* <pre class="prettyprint">
* pageTracker.setDomainName( new Domain( DomainName.custom, ".example.com" ) ) ;
* </p>
*/
public static const custom:DomainNameMode = new DomainNameMode( 2, "custom" );
}
}
|
fix comment for asdoc
|
fix comment for asdoc
|
ActionScript
|
apache-2.0
|
minimedj/gaforflash,nsdevaraj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash
|
163e46ec27304c06b1ea3a0dc91c803094f77a36
|
asx_test/src/asx/fn/DebounceTest.as
|
asx_test/src/asx/fn/DebounceTest.as
|
package asx.fn
{
import flash.events.EventDispatcher;
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.getTimer;
import flash.utils.Timer;
import org.flexunit.async.Async;
import org.flexunit.assertThat;
import org.hamcrest.object.equalTo;
import org.hamcrest.object.isFalse;
import org.hamcrest.number.greaterThan;
public class DebounceTest
{
[Test(async)]
public function invokes_the_original_function_after_debounced_function_stops_being_called_for_wait_milliseconds():void
{
var dispatcher:EventDispatcher = new EventDispatcher();
Async.proceedOnEvent(this, dispatcher, Event.COMPLETE, 1000);
var start:int = getTimer();
var complete:Function = function():void {
assertThat(getTimer() - start, greaterThan(700));
dispatcher.dispatchEvent(new Event(Event.COMPLETE));
};
var timer:Timer = new Timer(50, 8);
timer.addEventListener(TimerEvent.TIMER, debounce(complete, 300));
timer.start();
}
}
}
|
package asx.fn
{
import flash.events.EventDispatcher;
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.getTimer;
import flash.utils.Timer;
import org.flexunit.async.Async;
import org.flexunit.assertThat;
import org.hamcrest.object.equalTo;
import org.hamcrest.object.isFalse;
import org.hamcrest.number.greaterThan;
public class DebounceTest
{
[Test(async)]
public function invokes_the_original_function_after_debounced_function_stops_being_called_for_wait_milliseconds():void
{
var dispatcher:EventDispatcher = new EventDispatcher();
Async.proceedOnEvent(this, dispatcher, Event.COMPLETE, 1500);
var start:int = getTimer();
var complete:Function = function():void {
assertThat(getTimer() - start, greaterThan(700));
dispatcher.dispatchEvent(new Event(Event.COMPLETE));
};
var timer:Timer = new Timer(50, 8);
timer.addEventListener(TimerEvent.TIMER, debounce(complete, 300));
timer.start();
}
}
}
|
increase DebounceTest timeout due to imprecision of flash.utils.Timer
|
increase DebounceTest timeout due to imprecision of flash.utils.Timer
|
ActionScript
|
mit
|
drewbourne/asx,drewbourne/asx
|
4fde46f3629a18eed389730578eedfd831c08a20
|
src/as/com/threerings/io/streamers/ArrayStreamer.as
|
src/as/com/threerings/io/streamers/ArrayStreamer.as
|
package com.threerings.io.streamers {
import com.threerings.util.ClassUtil;
import com.threerings.io.ArrayMask;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamer;
import com.threerings.io.Translations;
import com.threerings.io.TypedArray;
/**
* A Streamer for Array objects.
*/
public class ArrayStreamer extends Streamer
{
public function ArrayStreamer (jname :String = "[Ljava.lang.Object;")
{
super(TypedArray, jname);
var secondChar :String = jname.charAt(1);
if (secondChar === "[") {
// if we're a multi-dimensional array then we need a delegate
_delegate = Streamer.getStreamerByJavaName(jname.substring(1));
_isFinal = true; // it just is
} else if (secondChar === "L") {
// form is "[L<class>;"
var baseClass :String = jname.substring(2, jname.length - 1);
baseClass = Translations.getFromServer(baseClass);
_elementType = ClassUtil.getClassByName(baseClass);
_isFinal = ClassUtil.isFinal(_elementType);
} else if (secondChar === "I") {
_elementType = int;
} else {
Log.getLog(this).warning("Other array types are " +
"currently not handled yet [jname=" + jname + "].");
throw new Error("Unimplemented bit");
}
}
override public function isStreamerFor (obj :Object) :Boolean
{
if (obj is TypedArray) {
// TypedArrays need the same element type
return ((obj as TypedArray).getJavaType() === _jname);
} else {
// any other array is streamed as Object[]
return (obj is Array) && (_jname === "[Ljava.lang.Object;");
}
}
override public function isStreamerForClass (clazz :Class) :Boolean
{
if (clazz == TypedArray) {
return false; // TODO: we're kinda fucked for finding a streamer
// by class for TypedArrays here. The caller should be passing
// the java name.
} else {
return ClassUtil.isAssignableAs(Array, clazz) &&
(_jname === "[Ljava.lang.Object;");
}
}
override public function createObject (ins :ObjectInputStream) :Object
{
var ta :TypedArray = new TypedArray(_jname);
ta.length = ins.readInt();
return ta;
}
override public function writeObject (obj :Object, out :ObjectOutputStream)
:void
{
var arr :Array = (obj as Array);
var ii :int;
out.writeInt(arr.length);
if (_elementType == int) {
for (ii = 0; ii < arr.length; ii++) {
out.writeInt(arr[ii] as int);
}
} else if (_isFinal) {
var mask :ArrayMask = new ArrayMask(arr.length);
for (ii = 0; ii < arr.length; ii++) {
if (arr[ii] != null) {
mask.setBit(ii);
}
}
mask.writeTo(out);
// now write the populated elements
for (ii = 0; ii < arr.length; ii++) {
var element :Object = arr[ii];
if (element != null) {
out.writeBareObjectImpl(element, _delegate);
}
}
} else {
for (ii = 0; ii < arr.length; ii++) {
out.writeObject(arr[ii]);
}
}
}
override public function readObject (obj :Object, ins :ObjectInputStream)
:void
{
var arr :Array = (obj as Array);
var ii :int;
if (_elementType == int) {
for (ii = 0; ii < arr.length; ii++) {
arr[ii] = ins.readInt();
}
} else if (_isFinal) {
var mask :ArrayMask = new ArrayMask();
mask.readFrom(ins);
for (ii = 0; ii < length; ii++) {
if (mask.isSet(ii)) {
var target :Object;
if (_delegate == null) {
target = new _elementType();
} else {
target = _delegate.createObject(ins);
}
ins.readBareObjectImpl(target, _delegate);
this[ii] = target;
}
}
} else {
for (ii = 0; ii < arr.length; ii++) {
arr[ii] = ins.readObject();
}
}
}
/** A streamer for our elements. */
protected var _delegate :Streamer;
/** If this is the final dimension of the array, the element type. */
protected var _elementType :Class;
/** Whether we're final or not: true if we're not the final dimension
* or if the element type is final. */
protected var _isFinal :Boolean;
}
}
|
package com.threerings.io.streamers {
import com.threerings.util.ClassUtil;
import com.threerings.io.ArrayMask;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.Streamer;
import com.threerings.io.Translations;
import com.threerings.io.TypedArray;
/**
* A Streamer for Array objects.
*/
public class ArrayStreamer extends Streamer
{
public function ArrayStreamer (jname :String = "[Ljava.lang.Object;")
{
super(TypedArray, jname);
var secondChar :String = jname.charAt(1);
if (secondChar === "[") {
// if we're a multi-dimensional array then we need a delegate
_delegate = Streamer.getStreamerByJavaName(jname.substring(1));
_isFinal = true; // it just is
} else if (secondChar === "L") {
// form is "[L<class>;"
var baseClass :String = jname.substring(2, jname.length - 1);
baseClass = Translations.getFromServer(baseClass);
_elementType = ClassUtil.getClassByName(baseClass);
_isFinal = ClassUtil.isFinal(_elementType);
} else if (secondChar === "I") {
_elementType = int;
} else if (secondChar === "B") {
_elementType = Boolean;
} else {
Log.getLog(this).warning("Other array types are " +
"currently not handled yet [jname=" + jname + "].");
throw new Error("Unimplemented bit");
}
}
override public function isStreamerFor (obj :Object) :Boolean
{
if (obj is TypedArray) {
// TypedArrays need the same element type
return ((obj as TypedArray).getJavaType() === _jname);
} else {
// any other array is streamed as Object[]
return (obj is Array) && (_jname === "[Ljava.lang.Object;");
}
}
override public function isStreamerForClass (clazz :Class) :Boolean
{
if (clazz == TypedArray) {
return false; // TODO: we're kinda fucked for finding a streamer
// by class for TypedArrays here. The caller should be passing
// the java name.
} else {
return ClassUtil.isAssignableAs(Array, clazz) &&
(_jname === "[Ljava.lang.Object;");
}
}
override public function createObject (ins :ObjectInputStream) :Object
{
var ta :TypedArray = new TypedArray(_jname);
ta.length = ins.readInt();
return ta;
}
override public function writeObject (obj :Object, out :ObjectOutputStream)
:void
{
var arr :Array = (obj as Array);
var ii :int;
out.writeInt(arr.length);
if (_elementType == int) {
for (ii = 0; ii < arr.length; ii++) {
out.writeInt(arr[ii] as int);
}
} else if (_isFinal) {
var mask :ArrayMask = new ArrayMask(arr.length);
for (ii = 0; ii < arr.length; ii++) {
if (arr[ii] != null) {
mask.setBit(ii);
}
}
mask.writeTo(out);
// now write the populated elements
for (ii = 0; ii < arr.length; ii++) {
var element :Object = arr[ii];
if (element != null) {
out.writeBareObjectImpl(element, _delegate);
}
}
} else {
for (ii = 0; ii < arr.length; ii++) {
out.writeObject(arr[ii]);
}
}
}
override public function readObject (obj :Object, ins :ObjectInputStream)
:void
{
var arr :Array = (obj as Array);
var ii :int;
if (_elementType == int) {
for (ii = 0; ii < arr.length; ii++) {
arr[ii] = ins.readInt();
}
} else if (_isFinal) {
var mask :ArrayMask = new ArrayMask();
mask.readFrom(ins);
for (ii = 0; ii < length; ii++) {
if (mask.isSet(ii)) {
var target :Object;
if (_delegate == null) {
target = new _elementType();
} else {
target = _delegate.createObject(ins);
}
ins.readBareObjectImpl(target, _delegate);
this[ii] = target;
}
}
} else {
for (ii = 0; ii < arr.length; ii++) {
arr[ii] = ins.readObject();
}
}
}
/** A streamer for our elements. */
protected var _delegate :Streamer;
/** If this is the final dimension of the array, the element type. */
protected var _elementType :Class;
/** Whether we're final or not: true if we're not the final dimension
* or if the element type is final. */
protected var _isFinal :Boolean;
}
}
|
Handle boolean arrays from the server.
|
Handle boolean arrays from the server.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4310 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
186e7407699b7e27ed3f72850c2756ab1fe3dc0a
|
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_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 mesh
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 mesh
var mesh:MeshMatrix = frameVO.matrix != null ? new MeshMatrix( 0, 0,
frameVO.matrix.tx,
frameVO.matrix.ty
//TODO calculate scale and skew
) : null;
var index:int = mesh == null ? -1 : layer.meshes.push(mesh);
var framesArray:Array = this.createFramesInfo(index, frameVO.name,
frameVO.duration, frameVO.type == "motion");
layer.frames = layer.frames.concat(framesArray);
}
data.layers.push(layer);
}
trace(JSON.stringify(data));
return data;
}
[Inline]
private function createFramesInfo(meshIndex:int, polygonName:String,
duration:int, motion:Boolean):Array {
var result:Array = new Array(duration);
if(duration < 2){
motion = false;
}
if(meshIndex > -1){
var t:Number = 1 / (duration - 1);
for(var i:int = 0; i < duration; i++){
var frameInfoData:FrameInfoData = new FrameInfoData();
frameInfoData.meshIndex = meshIndex;
frameInfoData.polygonName = polygonName;
frameInfoData.motion = motion;
frameInfoData.t = motion ? t * i : 0;
result[i] = frameInfoData;
}
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
class Layer{
public var meshes:Array;
public var frames:Array;
public function Layer() {
this.frames = [];
this.meshes = [];
}
}
class FrameInfoData{
public var polygonName:String;
public var motion:Boolean;
public var meshIndex: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 matrix:MeshMatrix = frameVO.matrix != null ? new MeshMatrix( 0, 0,
frameVO.matrix.tx,
frameVO.matrix.ty
//TODO calculate scale and skew
) : null;
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);
}
data.layers.push(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 - 1);
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;
}
//} 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;
}
|
change format
|
change format
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
bdbe9dab3c7364bca0f6df946116abfe634b3fbb
|
src/as/com/threerings/flex/ChatControl.as
|
src/as/com/threerings/flex/ChatControl.as
|
//
// $Id$
package com.threerings.flex {
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.TextEvent;
import flash.ui.Keyboard;
import mx.containers.HBox;
import mx.core.Application;
import mx.controls.TextInput;
import mx.events.FlexEvent;
import com.threerings.util.ArrayUtil;
import com.threerings.util.StringUtil;
import com.threerings.flex.CommandButton;
import com.threerings.flex.CommandMenu;
import com.threerings.crowd.chat.client.ChatDirector;
import com.threerings.crowd.chat.data.ChatCodes;
import com.threerings.crowd.util.CrowdContext;
/**
* The chat control widget.
*/
public class ChatControl extends HBox
{
/**
* Request focus for the oldest ChatControl.
*/
public static function grabFocus () :void
{
if (_controls.length > 0) {
(_controls[0] as ChatControl).setFocus();
}
}
public function ChatControl (
ctx :CrowdContext, sendButtonLabel :String = "send",
height :Number = NaN, controlHeight :Number = NaN)
{
_ctx = ctx;
_chatDtr = _ctx.getChatDirector();
this.height = height;
styleName = "chatControl";
addChild(_txt = new ChatInput());
_txt.addEventListener(FlexEvent.ENTER, sendChat, false, 0, true);
_txt.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp);
_but = new CommandButton(sendButtonLabel, sendChat);
addChild(_but);
if (!isNaN(controlHeight)) {
_txt.height = controlHeight;
_but.height = controlHeight;
}
addEventListener(Event.ADDED_TO_STAGE, handleAddRemove);
addEventListener(Event.REMOVED_FROM_STAGE, handleAddRemove);
}
/**
* Provides access to the text field we use to accept chat.
*/
public function get chatInput () :ChatInput
{
return _txt;
}
/**
* Provides access to the send button.
*/
public function get sendButton () :CommandButton
{
return _but;
}
override public function set enabled (en :Boolean) :void
{
super.enabled = en;
if (_txt != null) {
_txt.enabled = en;
_but.enabled = en;
}
}
/**
* Request focus to this chat control.
*/
override public function setFocus () :void
{
_txt.setFocus();
}
/**
* Configures the chat director to which we should send our chat. Pass null to restore our
* default chat director.
*/
public function setChatDirector (chatDtr :ChatDirector) :void
{
_chatDtr = (chatDtr == null) ? _ctx.getChatDirector() : chatDtr;
}
/**
* Configures the background color of the text entry area.
*/
public function setChatColor (color :int) :void
{
_txt.setStyle("backgroundColor", color);
}
/**
* Handles FlexEvent.ENTER and the action from the send button.
*/
protected function sendChat (... ignored) :void
{
var message :String = StringUtil.trim(_txt.text);
if ("" == message) {
return;
}
var result :String = _chatDtr.requestChat(null, message, true);
if (result != ChatCodes.SUCCESS) {
_chatDtr.displayFeedback(null, result);
return;
}
// if there was no error, clear the entry area in prep for the next entry event
_txt.text = "";
_histidx = -1;
}
protected function scrollHistory (next :Boolean) :void
{
var size :int = _chatDtr.getCommandHistorySize();
if ((_histidx == -1) || (_histidx == size)) {
_curLine = _txt.text;
_histidx = size;
}
_histidx = (next) ? Math.min(_histidx + 1, size)
: Math.max(_histidx - 1, 0);
var text :String = (_histidx == size) ? _curLine : _chatDtr.getCommandHistory(_histidx);
_txt.text = text;
_txt.setSelection(text.length, text.length);
}
/**
* Handles Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE.
*/
protected function handleAddRemove (event :Event) :void
{
if (event.type == Event.ADDED_TO_STAGE) {
// set up any already-configured text
_txt.text = _curLine;
_histidx = -1;
// request focus
callLater(_txt.setFocus);
_controls.push(this);
} else {
_curLine = _txt.text;
ArrayUtil.removeAll(_controls, this);
}
}
protected function handleKeyUp (event :KeyboardEvent) :void
{
switch (event.keyCode) {
case Keyboard.UP: scrollHistory(false); break;
case Keyboard.DOWN: scrollHistory(true); break;
}
}
/** Our client-side context. */
protected var _ctx :CrowdContext;
/** The director to which we are sending chat requests. */
protected var _chatDtr :ChatDirector;
/** The place where the user may enter chat. */
protected var _txt :ChatInput;
/** The current index in the chat command history. */
protected var _histidx :int = -1;
/** The button for sending chat. */
protected var _but :CommandButton;
/** An array of the currently shown-controls. */
protected static var _controls :Array = [];
/** The preserved current line of text when traversing history or carried between instances of
* ChatControl. */
protected static var _curLine :String;
}
}
|
//
// $Id$
package com.threerings.flex {
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import mx.containers.HBox;
import mx.core.Application;
import mx.controls.TextInput;
import mx.events.FlexEvent;
import com.threerings.util.ArrayUtil;
import com.threerings.util.MethodQueue;
import com.threerings.util.StringUtil;
import com.threerings.flex.CommandButton;
import com.threerings.flex.CommandMenu;
import com.threerings.crowd.chat.client.ChatDirector;
import com.threerings.crowd.chat.data.ChatCodes;
import com.threerings.crowd.util.CrowdContext;
/**
* The chat control widget.
*/
public class ChatControl extends HBox
{
/**
* Request focus for the oldest ChatControl.
*/
public static function grabFocus () :void
{
if (_controls.length > 0) {
(_controls[0] as ChatControl).setFocus();
}
}
public function ChatControl (
ctx :CrowdContext, sendButtonLabel :String = "send",
height :Number = NaN, controlHeight :Number = NaN)
{
_ctx = ctx;
_chatDtr = _ctx.getChatDirector();
this.height = height;
styleName = "chatControl";
addChild(_txt = new ChatInput());
_txt.addEventListener(FlexEvent.ENTER, sendChat, false, 0, true);
_txt.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp);
_but = new CommandButton(sendButtonLabel, sendChat);
addChild(_but);
if (!isNaN(controlHeight)) {
_txt.height = controlHeight;
_but.height = controlHeight;
}
addEventListener(Event.ADDED_TO_STAGE, handleAddRemove);
addEventListener(Event.REMOVED_FROM_STAGE, handleAddRemove);
}
/**
* Provides access to the text field we use to accept chat.
*/
public function get chatInput () :ChatInput
{
return _txt;
}
/**
* Provides access to the send button.
*/
public function get sendButton () :CommandButton
{
return _but;
}
override public function set enabled (en :Boolean) :void
{
super.enabled = en;
if (_txt != null) {
_txt.enabled = en;
_but.enabled = en;
}
}
/**
* Request focus to this chat control.
*/
override public function setFocus () :void
{
_txt.setFocus();
}
/**
* Configures the chat director to which we should send our chat. Pass null to restore our
* default chat director.
*/
public function setChatDirector (chatDtr :ChatDirector) :void
{
_chatDtr = (chatDtr == null) ? _ctx.getChatDirector() : chatDtr;
}
/**
* Configures the background color of the text entry area.
*/
public function setChatColor (color :int) :void
{
_txt.setStyle("backgroundColor", color);
}
/**
* Handles FlexEvent.ENTER and the action from the send button.
*/
protected function sendChat (... ignored) :void
{
var message :String = StringUtil.trim(_txt.text);
if ("" == message) {
return;
}
var result :String = _chatDtr.requestChat(null, message, true);
if (result != ChatCodes.SUCCESS) {
_chatDtr.displayFeedback(null, result);
return;
}
// If there was no error, clear the entry area in prep for the next entry event
MethodQueue.callLater(function () : void {
// WORKAROUND
// Originally we cleared the text immediately, but with flex 3.2 this broke
// for *some* people. Weird! We're called from the event dispatcher for the
// enter key, so it's possible that the default action is booching it?
// In any case, this could possibly be removed in the future by the ambitious.
// Note also: Flex's built-in callLater() doesn't work, but MethodQueue does. WTF?!?
_txt.text = "";
});
_histidx = -1;
}
protected function scrollHistory (next :Boolean) :void
{
var size :int = _chatDtr.getCommandHistorySize();
if ((_histidx == -1) || (_histidx == size)) {
_curLine = _txt.text;
_histidx = size;
}
_histidx = (next) ? Math.min(_histidx + 1, size)
: Math.max(_histidx - 1, 0);
var text :String = (_histidx == size) ? _curLine : _chatDtr.getCommandHistory(_histidx);
_txt.text = text;
_txt.setSelection(text.length, text.length);
}
/**
* Handles Event.ADDED_TO_STAGE and Event.REMOVED_FROM_STAGE.
*/
protected function handleAddRemove (event :Event) :void
{
if (event.type == Event.ADDED_TO_STAGE) {
// set up any already-configured text
_txt.text = _curLine;
_histidx = -1;
// request focus
callLater(_txt.setFocus);
_controls.push(this);
} else {
_curLine = _txt.text;
ArrayUtil.removeAll(_controls, this);
}
}
protected function handleKeyUp (event :KeyboardEvent) :void
{
switch (event.keyCode) {
case Keyboard.UP: scrollHistory(false); break;
case Keyboard.DOWN: scrollHistory(true); break;
}
}
/** Our client-side context. */
protected var _ctx :CrowdContext;
/** The director to which we are sending chat requests. */
protected var _chatDtr :ChatDirector;
/** The place where the user may enter chat. */
protected var _txt :ChatInput;
/** The current index in the chat command history. */
protected var _histidx :int = -1;
/** The button for sending chat. */
protected var _but :CommandButton;
/** An array of the currently shown-controls. */
protected static var _controls :Array = [];
/** The preserved current line of text when traversing history or carried between instances of
* ChatControl. */
protected static var _curLine :String;
}
}
|
Fix the chat input bug. It's a mystery wrapped in a heisenbug inside sunspots.
|
Fix the chat input bug.
It's a mystery wrapped in a heisenbug inside sunspots.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@774 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
69830db24f3e191859dae37e664326bc98aa5a48
|
src/flash/events/Event.as
|
src/flash/events/Event.as
|
/*
* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package flash.events {
[native(cls='EventClass')]
public class Event {
public static const ACTIVATE:String = "activate";
public static const ADDED:String = "added";
public static const ADDED_TO_STAGE:String = "addedToStage";
public static const CANCEL:String = "cancel";
public static const CHANGE:String = "change";
public static const CLEAR:String = "clear";
public static const CLOSE:String = "close";
public static const COMPLETE:String = "complete";
public static const CONNECT:String = "connect";
public static const COPY:String = "copy";
public static const CUT:String = "cut";
public static const DEACTIVATE:String = "deactivate";
public static const ENTER_FRAME:String = "enterFrame";
public static const FRAME_CONSTRUCTED:String = "frameConstructed";
public static const EXIT_FRAME:String = "exitFrame";
public static const FRAME_LABEL:String = "frameLabel";
public static const ID3:String = "id3";
public static const INIT:String = "init";
public static const MOUSE_LEAVE:String = "mouseLeave";
public static const OPEN:String = "open";
public static const PASTE:String = "paste";
public static const REMOVED:String = "removed";
public static const REMOVED_FROM_STAGE:String = "removedFromStage";
public static const RENDER:String = "render";
public static const RESIZE:String = "resize";
public static const SCROLL:String = "scroll";
public static const TEXT_INTERACTION_MODE_CHANGE:String = "textInteractionModeChange";
public static const SELECT:String = "select";
public static const SELECT_ALL:String = "selectAll";
public static const SOUND_COMPLETE:String = "soundComplete";
public static const TAB_CHILDREN_CHANGE:String = "tabChildrenChange";
public static const TAB_ENABLED_CHANGE:String = "tabEnabledChange";
public static const TAB_INDEX_CHANGE:String = "tabIndexChange";
public static const UNLOAD:String = "unload";
public static const FULLSCREEN:String = "fullScreen";
public static const CONTEXT3D_CREATE:String = "context3DCreate";
public static const TEXTURE_READY:String = "textureReady";
public static const VIDEO_FRAME:String = "videoFrame";
public static const SUSPEND:String = "suspend";
public static const CHANNEL_MESSAGE:String = "channelMessage";
public static const CHANNEL_STATE:String = "channelState";
public static const WORKER_STATE:String = "workerState";
public function Event(type:String, bubbles:Boolean = false, cancelable:Boolean = false) {
ctor(type, bubbles, cancelable);
}
public native function get type():String;
public native function get bubbles():Boolean;
public native function get cancelable():Boolean;
public native function get target():Object;
public native function get currentTarget():Object;
public native function get eventPhase():uint;
public function formatToString(className:String, ...args):String {
var str = '[' + className;
for (var i:uint = 0; i < args.length; i++) {
var field:String = args[i];
var value:Object = this[field];
str += ' ' + field + '=' + value is String ? '"' + value + '"' : value;
}
return str + ']';
}
public function clone():Event {
return new Event(type, bubbles, cancelable);
}
public function toString():String {
return formatToString('Event', 'bubbles', 'cancelable', 'eventPhase');
}
public native function stopPropagation():void;
public native function stopImmediatePropagation():void;
public native function preventDefault():void;
public native function isDefaultPrevented():Boolean;
private native function ctor(type:String, bubbles:Boolean, cancelable:Boolean):void;
}
}
|
/*
* 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 {
[native(cls='EventClass')]
public class Event {
public static const ACTIVATE:String = "activate";
public static const ADDED:String = "added";
public static const ADDED_TO_STAGE:String = "addedToStage";
public static const CANCEL:String = "cancel";
public static const CHANGE:String = "change";
public static const CLEAR:String = "clear";
public static const CLOSE:String = "close";
public static const COMPLETE:String = "complete";
public static const CONNECT:String = "connect";
public static const COPY:String = "copy";
public static const CUT:String = "cut";
public static const DEACTIVATE:String = "deactivate";
public static const ENTER_FRAME:String = "enterFrame";
public static const FRAME_CONSTRUCTED:String = "frameConstructed";
public static const EXIT_FRAME:String = "exitFrame";
public static const FRAME_LABEL:String = "frameLabel";
public static const ID3:String = "id3";
public static const INIT:String = "init";
public static const MOUSE_LEAVE:String = "mouseLeave";
public static const OPEN:String = "open";
public static const PASTE:String = "paste";
public static const REMOVED:String = "removed";
public static const REMOVED_FROM_STAGE:String = "removedFromStage";
public static const RENDER:String = "render";
public static const RESIZE:String = "resize";
public static const SCROLL:String = "scroll";
public static const TEXT_INTERACTION_MODE_CHANGE:String = "textInteractionModeChange";
public static const SELECT:String = "select";
public static const SELECT_ALL:String = "selectAll";
public static const SOUND_COMPLETE:String = "soundComplete";
public static const TAB_CHILDREN_CHANGE:String = "tabChildrenChange";
public static const TAB_ENABLED_CHANGE:String = "tabEnabledChange";
public static const TAB_INDEX_CHANGE:String = "tabIndexChange";
public static const UNLOAD:String = "unload";
public static const FULLSCREEN:String = "fullScreen";
public static const CONTEXT3D_CREATE:String = "context3DCreate";
public static const TEXTURE_READY:String = "textureReady";
public static const VIDEO_FRAME:String = "videoFrame";
public static const SUSPEND:String = "suspend";
public static const CHANNEL_MESSAGE:String = "channelMessage";
public static const CHANNEL_STATE:String = "channelState";
public static const WORKER_STATE:String = "workerState";
public function Event(type:String, bubbles:Boolean = false, cancelable:Boolean = false) {
ctor(type, bubbles, cancelable);
}
public native function get type():String;
public native function get bubbles():Boolean;
public native function get cancelable():Boolean;
public native function get target():Object;
public native function get currentTarget():Object;
public native function get eventPhase():uint;
public function formatToString(className:String, ...args):String {
var str = '[' + className;
for (var i:uint = 0; i < args.length; i++) {
var field:String = args[i];
var value:Object = this[field];
if (value is String) {
value = '"' + value + '"';
}
str += ' ' + field + '=' + value;
}
return str + ']';
}
public function clone():Event {
return new Event(type, bubbles, cancelable);
}
public function toString():String {
return formatToString('Event', 'bubbles', 'cancelable', 'eventPhase');
}
public native function stopPropagation():void;
public native function stopImmediatePropagation():void;
public native function preventDefault():void;
public native function isDefaultPrevented():Boolean;
private native function ctor(type:String, bubbles:Boolean, cancelable:Boolean):void;
}
}
|
Fix Event#formatToString's output
|
Fix Event#formatToString's output
|
ActionScript
|
apache-2.0
|
mbebenita/shumway,mozilla/shumway,mbebenita/shumway,mbebenita/shumway,mbebenita/shumway,mozilla/shumway,mozilla/shumway,mozilla/shumway,tschneidereit/shumway,mbebenita/shumway,mozilla/shumway,yurydelendik/shumway,mozilla/shumway,yurydelendik/shumway,tschneidereit/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,mozilla/shumway,mbebenita/shumway,tschneidereit/shumway,yurydelendik/shumway,mbebenita/shumway,yurydelendik/shumway,yurydelendik/shumway,tschneidereit/shumway,tschneidereit/shumway,mbebenita/shumway,yurydelendik/shumway,tschneidereit/shumway,mozilla/shumway,yurydelendik/shumway
|
dfc61bfae69b2db8647e5b6f499ac7fd6ddab5d6
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import dolly.utils.PropertyUtil;
import flash.utils.Dictionary;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.AccessorAccess;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
use namespace dolly_internal;
public class Cloner {
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function failIfTypeIsNotCloneable(type:Type):void {
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
}
dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> {
failIfTypeIsNotCloneable(type);
const result:Vector.<Field> = new Vector.<Field>();
for each(var field:Field in type.properties) {
if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) {
result.push(field);
}
}
return result;
}
dolly_internal static function doClone(source:*, deep:int, clonedObjectsMap:Dictionary = null, type:Type = null):* {
if (!clonedObjectsMap) {
clonedObjectsMap = new Dictionary();
}
if (!type) {
type = Type.forInstance(source);
}
const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type);
const clonedInstance:* = new (type.clazz)();
for each(var field:Field in fieldsToClone) {
PropertyUtil.cloneProperty(source, clonedInstance, field.name);
}
return clonedInstance;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
failIfTypeIsNotCloneable(type);
const deep:int = 2;
return doClone(source, deep, null, type);
}
}
}
|
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);
}
}
}
|
Switch Cloner class to cloning of objects by using ByteArray.
|
Switch Cloner class to cloning of objects by using ByteArray.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
2558e82959cb10a696037b268f8ce61c3403621a
|
src/as/com/threerings/parlor/client/TableDirector.as
|
src/as/com/threerings/parlor/client/TableDirector.as
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.parlor.client {
import com.threerings.util.ArrayUtil;
import com.threerings.util.ObserverList;
import com.threerings.util.Util;
import com.threerings.presents.client.BasicDirector;
import com.threerings.presents.client.Client;
import com.threerings.presents.client.ClientEvent;
import com.threerings.presents.client.InvocationService_ResultListener;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.EntryAddedEvent;
import com.threerings.presents.dobj.EntryRemovedEvent;
import com.threerings.presents.dobj.EntryUpdatedEvent;
import com.threerings.presents.dobj.SetListener;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.parlor.data.Table;
import com.threerings.parlor.data.TableConfig;
import com.threerings.parlor.data.TableLobbyObject;
import com.threerings.parlor.game.data.GameConfig;
import com.threerings.parlor.util.ParlorContext;
/**
* As tables are created and managed within the scope of a place (a lobby), we want to fold the
* table management functionality into the standard hierarchy of place controllers that deal with
* place-related functionality on the client. Thus, instead of forcing places that expect to have
* tables to extend a <code>TableLobbyController</code> or something similar, we instead provide
* the table director which can be instantiated by the place controller (or specific table related
* views) to handle the table matchmaking services.
*
* <p> Entites that do so, will need to implement the {@link TableObserver} interface so that the
* table director can notify them when table related things happen.
*
* <p> The table services expect that the place object being used as a lobby in which the table
* matchmaking takes place implements the {@link TableLobbyObject} interface.
*/
public class TableDirector extends BasicDirector
implements SetListener, InvocationService_ResultListener
{
protected static const log :Log = Log.getLog(TableDirector);
/**
* Creates a new table director to manage tables with the specified observer which will receive
* callbacks when interesting table related things happen.
*
* @param ctx the parlor context in use by the client.
* @param tableField the field name of the distributed set that contains the tables we will be
* managing.
* @param observer the entity that will receive callbacks when things happen to the tables.
*/
public function TableDirector (ctx :ParlorContext, tableField :String)
{
super(ctx);
// keep track of this stuff
_pctx = ctx;
_tableField = tableField;
}
/**
* This must be called by the entity that uses the table director when the using entity
* prepares to enter and display a "place".
*/
public function setTableObject (tlobj :DObject) :void
{
// the distributed object should be a TableLobbyObject
_tlobj = TableLobbyObject(tlobj);
// listen for table set updates
tlobj.addListener(this);
}
/**
* This must be called by the entity that uses the table director when the using entity has
* left and is done displaying the "place".
*/
public function clearTableObject () :void
{
// remove our listenership and clear out
if (_tlobj != null) {
(_tlobj as DObject).removeListener(this);
_tlobj = null;
}
}
/**
* Requests that the specified observer be added to the list of observers that are notified
* of table updates
*/
public function addTableObserver (observer :TableObserver) :void
{
_tableObservers.add(observer);
}
/**
* Requests that the specified observer be removed from to the list of observers that are
* notified of table updates
*/
public function removeTableObserver (observer :TableObserver) :void
{
_tableObservers.remove(observer);
}
/**
* Requests that the specified observer be added to the list of observers that are notified
* when this client sits down at or stands up from a table.
*/
public function addSeatednessObserver (observer :SeatednessObserver) :void
{
_seatedObservers.add(observer);
}
/**
* Requests that the specified observer be removed from to the list of observers that are
* notified when this client sits down at or stands up from a table.
*/
public function removeSeatednessObserver (observer :SeatednessObserver) :void
{
_seatedObservers.remove(observer);
}
/**
* Returns true if this client is currently seated at a table, false if they are not.
*/
public function isSeated () :Boolean
{
return (_ourTable != null);
}
/**
* Returns the table this client is currently seated at, or null.
*/
public function getSeatedTable () :Table
{
return _ourTable;
}
/**
* Sends a request to create a table with the specified game configuration. This user will
* become the owner of this table and will be added to the first position in the table. The
* response will be communicated via the {@link TableObserver} interface.
*/
public function createTable (tableConfig :TableConfig, config :GameConfig) :void
{
// if we're already in a table, refuse the request
if (_ourTable != null) {
log.warning("Ignoring request to create table as we're " +
"already in a table [table=" + _ourTable + "].");
return;
}
// make sure we're currently in a place
if (_tlobj == null) {
log.warning("Requested to create a table but we're not " +
"currently in a place [config=" + config + "].");
return;
}
// go ahead and issue the create request
_tlobj.getTableService().createTable(_pctx.getClient(), tableConfig, config, this);
}
/**
* Sends a request to join the specified table at the specified position. The response will be
* communicated via the {@link TableObserver} interface.
*/
public function joinTable (tableId :int, position :int) :void
{
// if we're already in a table, refuse the request
if (_ourTable != null) {
log.warning("Ignoring request to join table as we're " +
"already in a table [table=" + _ourTable + "].");
return;
}
// make sure we're currently in a place
if (_tlobj == null) {
log.warning("Requested to join a table but we're not " +
"currently in a place [tableId=" + tableId + "].");
return;
}
// issue the join request
log.info("Joining table [tid=" + tableId + ", pos=" + position + "].");
_tlobj.getTableService().joinTable(_pctx.getClient(), tableId, position, this);
}
/**
* Sends a request to leave the specified table at which we are presumably seated. The response
* will be communicated via the {@link TableObserver} interface.
*/
public function leaveTable (tableId :int) :void
{
// make sure we're currently in a place
if (_tlobj == null) {
log.warning("Requested to leave a table but we're not " +
"currently in a place [tableId=" + tableId + "].");
return;
}
// issue the leave request
_tlobj.getTableService().leaveTable(_pctx.getClient(), tableId, this);
}
/**
* Sends a request to have the specified table start now, even if all the seats have not yet
* been filled.
*/
public function startTableNow (tableId :int) :void
{
if (_tlobj == null) {
log.warning("Requested to start a table but we're not " +
"currently in a place [tableId=" + tableId + "].");
return;
}
_tlobj.getTableService().startTableNow(_ctx.getClient(), tableId, this);
}
// documentation inherited
override public function clientDidLogoff (event :ClientEvent) :void
{
super.clientDidLogoff(event);
_tlobj = null;
_ourTable = null;
}
// documentation inherited
override protected function fetchServices (client :Client) :void
{
}
// documentation inherited
public function entryAdded (event :EntryAddedEvent) :void
{
if (event.getName() == _tableField) {
var table :Table = (event.getEntry() as Table);
// check to see if we just joined a table
checkSeatedness(table);
// now let the observers know what's up
_tableObservers.apply(function (to :TableObserver) :void {
to.tableAdded(table);
});
}
}
// documentation inherited
public function entryUpdated (event :EntryUpdatedEvent) :void
{
if (event.getName() == _tableField) {
var table :Table = (event.getEntry() as Table);
// check to see if we just joined or left a table
checkSeatedness(table);
// now let the observers know what's up
_tableObservers.apply(function (to :TableObserver) :void {
to.tableUpdated(table);
});
}
}
// documentation inherited
public function entryRemoved (event :EntryRemovedEvent) :void
{
if (event.getName() == _tableField) {
var tableId :int = (event.getKey() as int);
// check to see if our table just disappeared
if (_ourTable != null && tableId == _ourTable.tableId) {
_ourTable = null;
notifySeatedness(false);
}
// now let the observer know what's up
_tableObservers.apply(function (to :TableObserver) :void {
to.tableRemoved(tableId);
});
}
}
// documentation inherited from interface
public function requestProcessed (result :Object) :void
{
var tableId :int = int(result);
if (_tlobj == null) {
// we've left, it's none of our concern anymore
log.info("Table created, but no lobby. [tableId=" + tableId + "].");
return;
}
var table :Table = (_tlobj.getTables().get(tableId) as Table);
if (table == null) {
log.warning("Table created, but where is it? [tableId=" + tableId + "]");
return;
}
// All this to check to see if we created a party game (and should now enter).
if (table.gameOid != -1 && (table.occupants == null)) {
// let's boogie!
_pctx.getParlorDirector().gameIsReady(table.gameOid);
}
}
// documentation inherited from interface
public function requestFailed (reason :String) :void
{
log.warning("Table action failed [reason=" + reason + "].");
}
/**
* Checks to see if we're a member of this table and notes it as our table, if so.
*/
protected function checkSeatedness (table :Table) :void
{
var oldTable :Table = _ourTable;
// if this is the same table as our table, clear out our table reference and allow it to be
// added back if we are still in the table
if (table.equals(_ourTable)) {
_ourTable = null;
}
// look for our username in the occupants array
var self :BodyObject = (_pctx.getClient().getClientObject() as BodyObject);
if (ArrayUtil.contains(table.occupants, self.getVisibleName())) {
_ourTable = table;
}
// if nothing changed, bail now
if (Util.equals(oldTable, _ourTable)) {
return;
}
// otherwise notify the observers
notifySeatedness(_ourTable != null);
}
/**
* Notifies the seatedness observers of a seatedness change.
*/
protected function notifySeatedness (isSeated :Boolean) :void
{
_seatedObservers.apply(function (so :SeatednessObserver) :void {
so.seatednessDidChange(isSeated);
});
}
/** A context by which we can access necessary client services. */
protected var _pctx :ParlorContext;
/** The place object, cast as a TableLobbyObject. */
protected var _tlobj :TableLobbyObject;
/** The field name of the distributed set that contains our tables. */
protected var _tableField :String;
/** The table of which we are a member if any. */
protected var _ourTable :Table;
/** An array of entities that want to hear about table updates. */
protected var _tableObservers :ObserverList = new ObserverList();
/** An array of entities that want to hear about when we stand up or sit down. */
protected var _seatedObservers :ObserverList = new ObserverList();
}
}
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.parlor.client {
import com.threerings.util.ArrayUtil;
import com.threerings.util.ObserverList;
import com.threerings.util.Util;
import com.threerings.presents.client.BasicDirector;
import com.threerings.presents.client.Client;
import com.threerings.presents.client.ClientEvent;
import com.threerings.presents.client.InvocationService_ResultListener;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.EntryAddedEvent;
import com.threerings.presents.dobj.EntryRemovedEvent;
import com.threerings.presents.dobj.EntryUpdatedEvent;
import com.threerings.presents.dobj.SetListener;
import com.threerings.crowd.data.BodyObject;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.parlor.data.Table;
import com.threerings.parlor.data.TableConfig;
import com.threerings.parlor.data.TableLobbyObject;
import com.threerings.parlor.game.data.GameConfig;
import com.threerings.parlor.util.ParlorContext;
/**
* As tables are created and managed within the scope of a place (a lobby), we want to fold the
* table management functionality into the standard hierarchy of place controllers that deal with
* place-related functionality on the client. Thus, instead of forcing places that expect to have
* tables to extend a <code>TableLobbyController</code> or something similar, we instead provide
* the table director which can be instantiated by the place controller (or specific table related
* views) to handle the table matchmaking services.
*
* <p> Entites that do so, will need to implement the {@link TableObserver} interface so that the
* table director can notify them when table related things happen.
*
* <p> The table services expect that the place object being used as a lobby in which the table
* matchmaking takes place implements the {@link TableLobbyObject} interface.
*/
public class TableDirector extends BasicDirector
implements SetListener, InvocationService_ResultListener
{
protected static const log :Log = Log.getLog(TableDirector);
/**
* Creates a new table director to manage tables with the specified observer which will receive
* callbacks when interesting table related things happen.
*
* @param ctx the parlor context in use by the client.
* @param tableField the field name of the distributed set that contains the tables we will be
* managing.
* @param observer the entity that will receive callbacks when things happen to the tables.
*/
public function TableDirector (ctx :ParlorContext, tableField :String)
{
super(ctx);
// keep track of this stuff
_pctx = ctx;
_tableField = tableField;
}
/**
* This must be called by the entity that uses the table director when the using entity
* prepares to enter and display a "place".
*/
public function setTableObject (tlobj :DObject) :void
{
// the distributed object should be a TableLobbyObject
_tlobj = TableLobbyObject(tlobj);
// listen for table set updates
tlobj.addListener(this);
}
/**
* This must be called by the entity that uses the table director when the using entity has
* left and is done displaying the "place".
*/
public function clearTableObject () :void
{
// remove our listenership and clear out
if (_tlobj != null) {
(_tlobj as DObject).removeListener(this);
_tlobj = null;
_ourTable = null;
}
}
/**
* Requests that the specified observer be added to the list of observers that are notified
* of table updates
*/
public function addTableObserver (observer :TableObserver) :void
{
_tableObservers.add(observer);
}
/**
* Requests that the specified observer be removed from to the list of observers that are
* notified of table updates
*/
public function removeTableObserver (observer :TableObserver) :void
{
_tableObservers.remove(observer);
}
/**
* Requests that the specified observer be added to the list of observers that are notified
* when this client sits down at or stands up from a table.
*/
public function addSeatednessObserver (observer :SeatednessObserver) :void
{
_seatedObservers.add(observer);
}
/**
* Requests that the specified observer be removed from to the list of observers that are
* notified when this client sits down at or stands up from a table.
*/
public function removeSeatednessObserver (observer :SeatednessObserver) :void
{
_seatedObservers.remove(observer);
}
/**
* Returns true if this client is currently seated at a table, false if they are not.
*/
public function isSeated () :Boolean
{
return (_ourTable != null);
}
/**
* Returns the table this client is currently seated at, or null.
*/
public function getSeatedTable () :Table
{
return _ourTable;
}
/**
* Sends a request to create a table with the specified game configuration. This user will
* become the owner of this table and will be added to the first position in the table. The
* response will be communicated via the {@link TableObserver} interface.
*/
public function createTable (tableConfig :TableConfig, config :GameConfig) :void
{
// if we're already in a table, refuse the request
if (_ourTable != null) {
log.warning("Ignoring request to create table as we're " +
"already in a table [table=" + _ourTable + "].");
return;
}
// make sure we're currently in a place
if (_tlobj == null) {
log.warning("Requested to create a table but we're not " +
"currently in a place [config=" + config + "].");
return;
}
// go ahead and issue the create request
_tlobj.getTableService().createTable(_pctx.getClient(), tableConfig, config, this);
}
/**
* Sends a request to join the specified table at the specified position. The response will be
* communicated via the {@link TableObserver} interface.
*/
public function joinTable (tableId :int, position :int) :void
{
// if we're already in a table, refuse the request
if (_ourTable != null) {
log.warning("Ignoring request to join table as we're " +
"already in a table [table=" + _ourTable + "].");
return;
}
// make sure we're currently in a place
if (_tlobj == null) {
log.warning("Requested to join a table but we're not " +
"currently in a place [tableId=" + tableId + "].");
return;
}
// issue the join request
log.info("Joining table [tid=" + tableId + ", pos=" + position + "].");
_tlobj.getTableService().joinTable(_pctx.getClient(), tableId, position, this);
}
/**
* Sends a request to leave the specified table at which we are presumably seated. The response
* will be communicated via the {@link TableObserver} interface.
*/
public function leaveTable (tableId :int) :void
{
// make sure we're currently in a place
if (_tlobj == null) {
log.warning("Requested to leave a table but we're not " +
"currently in a place [tableId=" + tableId + "].");
return;
}
// issue the leave request
_tlobj.getTableService().leaveTable(_pctx.getClient(), tableId, this);
}
/**
* Sends a request to have the specified table start now, even if all the seats have not yet
* been filled.
*/
public function startTableNow (tableId :int) :void
{
if (_tlobj == null) {
log.warning("Requested to start a table but we're not " +
"currently in a place [tableId=" + tableId + "].");
return;
}
_tlobj.getTableService().startTableNow(_ctx.getClient(), tableId, this);
}
// documentation inherited
override public function clientDidLogoff (event :ClientEvent) :void
{
super.clientDidLogoff(event);
_tlobj = null;
_ourTable = null;
}
// documentation inherited
override protected function fetchServices (client :Client) :void
{
}
// documentation inherited
public function entryAdded (event :EntryAddedEvent) :void
{
if (event.getName() == _tableField) {
var table :Table = (event.getEntry() as Table);
// check to see if we just joined a table
checkSeatedness(table);
// now let the observers know what's up
_tableObservers.apply(function (to :TableObserver) :void {
to.tableAdded(table);
});
}
}
// documentation inherited
public function entryUpdated (event :EntryUpdatedEvent) :void
{
if (event.getName() == _tableField) {
var table :Table = (event.getEntry() as Table);
// check to see if we just joined or left a table
checkSeatedness(table);
// now let the observers know what's up
_tableObservers.apply(function (to :TableObserver) :void {
to.tableUpdated(table);
});
}
}
// documentation inherited
public function entryRemoved (event :EntryRemovedEvent) :void
{
if (event.getName() == _tableField) {
var tableId :int = (event.getKey() as int);
// check to see if our table just disappeared
if (_ourTable != null && tableId == _ourTable.tableId) {
_ourTable = null;
notifySeatedness(false);
}
// now let the observer know what's up
_tableObservers.apply(function (to :TableObserver) :void {
to.tableRemoved(tableId);
});
}
}
// documentation inherited from interface
public function requestProcessed (result :Object) :void
{
var tableId :int = int(result);
if (_tlobj == null) {
// we've left, it's none of our concern anymore
log.info("Table created, but no lobby. [tableId=" + tableId + "].");
return;
}
var table :Table = (_tlobj.getTables().get(tableId) as Table);
if (table == null) {
log.warning("Table created, but where is it? [tableId=" + tableId + "]");
return;
}
// All this to check to see if we created a party game (and should now enter).
if (table.gameOid != -1 && (table.occupants == null)) {
// let's boogie!
_pctx.getParlorDirector().gameIsReady(table.gameOid);
}
}
// documentation inherited from interface
public function requestFailed (reason :String) :void
{
log.warning("Table action failed [reason=" + reason + "].");
}
/**
* Checks to see if we're a member of this table and notes it as our table, if so.
*/
protected function checkSeatedness (table :Table) :void
{
var oldTable :Table = _ourTable;
// if this is the same table as our table, clear out our table reference and allow it to be
// added back if we are still in the table
if (table.equals(_ourTable)) {
_ourTable = null;
}
// look for our username in the occupants array
var self :BodyObject = (_pctx.getClient().getClientObject() as BodyObject);
if (ArrayUtil.contains(table.occupants, self.getVisibleName())) {
_ourTable = table;
}
// if nothing changed, bail now
if (Util.equals(oldTable, _ourTable)) {
return;
}
// otherwise notify the observers
notifySeatedness(_ourTable != null);
}
/**
* Notifies the seatedness observers of a seatedness change.
*/
protected function notifySeatedness (isSeated :Boolean) :void
{
_seatedObservers.apply(function (so :SeatednessObserver) :void {
so.seatednessDidChange(isSeated);
});
}
/** A context by which we can access necessary client services. */
protected var _pctx :ParlorContext;
/** The place object, cast as a TableLobbyObject. */
protected var _tlobj :TableLobbyObject;
/** The field name of the distributed set that contains our tables. */
protected var _tableField :String;
/** The table of which we are a member if any. */
protected var _ourTable :Table;
/** An array of entities that want to hear about table updates. */
protected var _tableObservers :ObserverList = new ObserverList();
/** An array of entities that want to hear about when we stand up or sit down. */
protected var _seatedObservers :ObserverList = new ObserverList();
}
}
|
Make sure our seatedness variable accurately reflects the departure of our table.
|
Make sure our seatedness variable accurately reflects the departure of our table.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@441 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
753bcb229e714c17f737e5cbaf8255e400533709
|
src/as/com/threerings/media/image/ColorPository.as
|
src/as/com/threerings/media/image/ColorPository.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.media.image {
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.StringUtil;
public class ColorPository
{
private const log :Log = Log.getLog(ColorPository);
public function getClasses () :Array
{
return _classes.values();
}
/**
* Returns an array containing the records for the colors in the
* specified class.
*/
public function getColors (className :String) :Array
{
// make sure the class exists
var record :ClassRecord = getClassRecordByName(className);
if (record == null) {
return null;
}
// create the array
return record.colors.values();
}
/**
* Returns an array containing the ids of the colors in the specified
* class.
*/
public function getColorIds (className :String) :Array
{
// make sure the class exists
var record :ClassRecord = getClassRecordByName(className);
if (record == null) {
return null;
}
return record.colors.values().map(
function(element :ColorRecord, index :int, arr :Array) :int {
return element.colorId;
});
}
/**
* Returns true if the specified color is legal for use at character creation time. false is
* always returned for non-existent colors or classes.
*/
public function isLegalStartColor (classId :int, colorId :int) :Boolean
{
var color :ColorRecord = getColorRecord(classId, colorId);
return (color == null) ? false : color.starter;
}
/**
* Returns a random starting color from the specified color class.
*/
public function getRandomStartingColor (className :String) :ColorRecord
{
// make sure the class exists
var record :ClassRecord = getClassRecordByName(className);
return (record == null) ? null : record.randomStartingColor();
}
/**
* Looks up a colorization by id.
*/
public function getColorization (classId :int, colorId :int) :Colorization
{
var color :ColorRecord = getColorRecord(classId, colorId);
return (color == null) ? null : color.getColorization();
}
/**
* Looks up a colorization by color print.
*/
public function getColorizationByPrint (colorPrint :int) :Colorization
{
return getColorization(colorPrint >> 8, colorPrint & 0xFF);
}
/**
* Looks up a colorization by class and color names.
*/
public function getColorizationByName (className :String, colorName :String) :Colorization
{
var crec :ClassRecord = getClassRecordByName(className);
if (crec != null) {
var colorId :int = crec.getColorId(colorName);
var color :ColorRecord = crec.colors.get(colorId);
if (color != null) {
return color.getColorization();
}
}
return null;
}
/**
* Looks up a colorization by class and color Id.
*/
public function getColorizationByNameAndId (className :String, colorId :int) :Colorization
{
var crec :ClassRecord = getClassRecordByName(className);
if (crec != null) {
var color :ColorRecord = crec.colors.get(colorId);
if (color != null) {
return color.getColorization();
}
}
return null;
}
/**
* Loads up a colorization class by name and logs a warning if it doesn't exist.
*/
public function getClassRecordByName (className :String) :ClassRecord
{
for each (var crec :ClassRecord in _classes.values()) {
if (crec.name == className) {
return crec;
}
}
log.warning("No such color class", "class", className, new Error());
return null;
}
/**
* Looks up the requested color class record.
*/
public function getClassRecord (classId :int) :ClassRecord
{
return _classes.get(classId);
}
/**
* Looks up the requested color record.
*/
public function getColorRecord (classId :int, colorId :int) :ColorRecord
{
var record :ClassRecord = getClassRecord(classId);
if (record == null) {
// if they request color class zero, we assume they're just
// decoding a blank colorprint, otherwise we complain
if (classId != 0) {
log.warning("Requested unknown color class",
"classId", classId, "colorId", colorId, new Error());
}
return null;
}
return record.colors.get(colorId);
}
/**
* Looks up the requested color record by class & color names.
*/
public function getColorRecordByName (className :String, colorName :String) :ColorRecord
{
var record :ClassRecord = getClassRecordByName(className);
if (record == null) {
log.warning("Requested unknown color class",
"className", className, "colorName", colorName, new Error());
return null;
}
var colorId :int = record.getColorId(colorName);
return record.colors.get(colorId);
}
/**
* Loads up a serialized color pository from the supplied resource
* manager.
*/
public static function fromXml (xml :XML) :ColorPository
{
var pos :ColorPository = new ColorPository();
for each (var classXml :XML in xml.elements("class")) {
pos._classes.put(classXml.@classId, ClassRecord.fromXml(classXml));
}
return pos;
}
/** Our mapping from class names to class records. */
protected var _classes :Map = Maps.newMapOf(int);
}
}
|
//
// 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.media.image {
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.StringUtil;
public class ColorPository
{
private const log :Log = Log.getLog(ColorPository);
public function getClasses () :Array
{
return _classes.values();
}
/**
* Returns an array containing the records for the colors in the
* specified class.
*/
public function getColors (className :String) :Array
{
// make sure the class exists
var record :ClassRecord = getClassRecordByName(className);
if (record == null) {
return null;
}
// create the array
return record.colors.values();
}
/**
* Returns an array containing the ids of the colors in the specified
* class.
*/
public function getColorIds (className :String) :Array
{
// make sure the class exists
var record :ClassRecord = getClassRecordByName(className);
if (record == null) {
return null;
}
return record.colors.values().map(
function(element :ColorRecord, index :int, arr :Array) :int {
return element.colorId;
});
}
/**
* Returns true if the specified color is legal for use at character creation time. false is
* always returned for non-existent colors or classes.
*/
public function isLegalStartColor (classId :int, colorId :int) :Boolean
{
var color :ColorRecord = getColorRecord(classId, colorId);
return (color == null) ? false : color.starter;
}
/**
* Returns a random starting color from the specified color class.
*/
public function getRandomStartingColor (className :String) :ColorRecord
{
// make sure the class exists
var record :ClassRecord = getClassRecordByName(className);
return (record == null) ? null : record.randomStartingColor();
}
/**
* Looks up a colorization by id.
*/
public function getColorization (classId :int, colorId :int) :Colorization
{
var color :ColorRecord = getColorRecord(classId, colorId);
return (color == null) ? null : color.getColorization();
}
/**
* Looks up a colorization by color print.
*/
public function getColorizationByPrint (colorPrint :int) :Colorization
{
return getColorization(colorPrint >> 8, colorPrint & 0xFF);
}
/**
* Looks up a colorization by class and color names.
*/
public function getColorizationByName (className :String, colorName :String) :Colorization
{
var crec :ClassRecord = getClassRecordByName(className);
if (crec != null) {
var colorId :int = crec.getColorId(colorName);
var color :ColorRecord = crec.colors.get(colorId);
if (color != null) {
return color.getColorization();
}
}
return null;
}
/**
* Looks up a colorization by class and color Id.
*/
public function getColorizationByNameAndId (className :String, colorId :int) :Colorization
{
var crec :ClassRecord = getClassRecordByName(className);
if (crec != null) {
var color :ColorRecord = crec.colors.get(colorId);
if (color != null) {
return color.getColorization();
}
}
return null;
}
/**
* Loads up a colorization class by name and logs a warning if it doesn't exist.
*/
public function getClassRecordByName (className :String) :ClassRecord
{
for each (var crec :ClassRecord in _classes.values()) {
if (crec.name == className) {
return crec;
}
}
log.warning("No such color class", "class", className, new Error());
return null;
}
/**
* Looks up the requested color class record.
*/
public function getClassRecord (classId :int) :ClassRecord
{
return _classes.get(classId);
}
/**
* Looks up the requested color record.
*/
public function getColorRecord (classId :int, colorId :int) :ColorRecord
{
var record :ClassRecord = getClassRecord(classId);
if (record == null) {
// if they request color class zero, we assume they're just
// decoding a blank colorprint, otherwise we complain
if (classId != 0) {
log.warning("Requested unknown color class",
"classId", classId, "colorId", colorId, new Error());
}
return null;
}
return record.colors.get(colorId);
}
/**
* Looks up the requested color record by class & color names.
*/
public function getColorRecordByName (className :String, colorName :String) :ColorRecord
{
var record :ClassRecord = getClassRecordByName(className);
if (record == null) {
log.warning("Requested unknown color class",
"className", className, "colorName", colorName, new Error());
return null;
}
var colorId :int = record.getColorId(colorName);
return record.colors.get(colorId);
}
/**
* Loads up a serialized color pository from the supplied resource
* manager.
*/
public static function fromXml (xml :XML) :ColorPository
{
var pos :ColorPository = new ColorPository();
for each (var classXml :XML in xml.elements("class")) {
pos._classes.put(int(classXml.@classId), ClassRecord.fromXml(classXml));
}
return pos;
}
/** Our mapping from class names to class records. */
protected var _classes :Map = Maps.newMapOf(int);
}
}
|
Fix bug in indexing the color classes map.
|
Fix bug in indexing the color classes map.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@993 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
83292799be58c6cfe3308b7a53459333cbbc7b2c
|
kdp3Lib/src/com/kaltura/kdpfl/model/vo/SequenceVO.as
|
kdp3Lib/src/com/kaltura/kdpfl/model/vo/SequenceVO.as
|
package com.kaltura.kdpfl.model.vo
{
import com.kaltura.kdpfl.plugin.IMidrollSequencePlugin;
[Bindable]
/**
* Class SequenceVO holds parameters related to the KDP sequence mechanism.
* @author Hila
*
*/
public class SequenceVO
{
/**
*Flag signifying whether we are currently playing in a sequence (pre or post)
*/
public var isInSequence : Boolean;
/**
* Array containing refereces to the PluginCode-s of the sequence plugins in the post sequence
*/
public var postSequenceArr : Array;
/**
* Array containing references to the PluginCode files of the sequence plugins in the pre-sequence
*/
public var preSequenceArr : Array;
/**
* Index of the current position in the pre sequence array, initially set to -1.
*/
public var preCurrentIndex : int = -1;
/**
*Index of the current position in the post sequence array, initially set to -1.
*/
public var postCurrentIndex : int = -1;
/**
* The original MediaVO for the main entry . Saved once in the bginning of the pre-sequence (or post-sequence)
*/
public var mainMediaVO : MediaVO;
/**
*The time remaining to the ad playing in the MediaPlayer
*/
public var timeRemaining : Number;
/**
*Property signifying whether the sequencePlugin lined up to play can be skipped;
*/
public var isAdSkip : Boolean = false;
/**
* Property signifying whether the sequencePlugin lined up to play has loaded.
*/
public var isAdLoaded : Boolean = false;
/**
* Flag indicating whether the post sequence is complete
*/
public var postSequenceComplete : Boolean = false;
/**
* Flag indicating whether the pre-sequence is complete
*/
public var preSequenceComplete : Boolean = false;
/**
* Number of pre-sequence ads.
*/
public var preSequenceCount : Number = 0;
/**
* Number of post-sequence ads.
*/
public var postSequenceCount : Number = 0;
//New Midroll-related properties - 12.22.2010
/**
* Array containing references to the PluginCode files of the sequence plugins in the midroll sequence
*/
public var midrollArr : Array;
/**
* Index of the current position in the midroll sequence array, initially set to -1.
*/
public var midCurrentIndex : int = -1;
/**
* Property containing the current midroll plugin playing in the player. The running assumptions are:
* a. There is only 1 midroll plugin playing at a given time
* b. The only way that this midroll is of interest to us is if it's playing in the KDP MediaPlayer.
*/
public var activeMidrollPlugin : IMidrollSequencePlugin;
/**
* New parameter allowing an <code>ISequencePluin</code> to set the metadata values of the ad that is currently playing.
* Added for analytics use.
*/
public var activePluginMetadata : AdMetadataVO;
/**
* In case we want to ignore prerolls, for example, when starting the media from the middle with "mediaProxy.mediaPlayFrom"
*/
public var skipPrerolls:Boolean = false;
}
}
|
package com.kaltura.kdpfl.model.vo
{
import com.kaltura.kdpfl.plugin.IMidrollSequencePlugin;
[Bindable]
/**
* Class SequenceVO holds parameters related to the KDP sequence mechanism.
* @author Hila
*
*/
public class SequenceVO
{
/**
*Flag signifying whether we are currently playing in a sequence (pre or post)
*/
public var isInSequence : Boolean;
/**
* Array containing refereces to the PluginCode-s of the sequence plugins in the post sequence
*/
public var postSequenceArr : Array;
/**
* Array containing references to the PluginCode files of the sequence plugins in the pre-sequence
*/
public var preSequenceArr : Array;
/**
* Index of the current position in the pre sequence array, initially set to -1.
*/
public var preCurrentIndex : int = -1;
/**
*Index of the current position in the post sequence array, initially set to -1.
*/
public var postCurrentIndex : int = -1;
/**
* The original MediaVO for the main entry . Saved once in the bginning of the pre-sequence (or post-sequence)
*/
public var mainMediaVO : MediaVO;
/**
*The time remaining to the ad playing in the MediaPlayer
*/
public var timeRemaining : Number;
/**
*Property signifying whether the sequencePlugin lined up to play can be skipped;
*/
public var isAdSkip : Boolean = false;
/**
* Property signifying whether the sequencePlugin lined up to play has loaded.
*/
public var isAdLoaded : Boolean = false;
/**
* Flag indicating whether the post sequence is complete
*/
public var postSequenceComplete : Boolean = false;
/**
* Flag indicating whether the pre-sequence is complete
*/
public var preSequenceComplete : Boolean = false;
/**
* Number of pre-sequence ads.
*/
public var preSequenceCount : Number = 0;
/**
* Number of post-sequence ads.
*/
public var postSequenceCount : Number = 0;
//New Midroll-related properties - 12.22.2010
/**
* Array containing references to the PluginCode files of the sequence plugins in the midroll sequence
*/
public var midrollArr : Array;
/**
* Index of the current position in the midroll sequence array, initially set to -1.
*/
public var midCurrentIndex : int = -1;
/**
* Property containing the current midroll plugin playing in the player. The running assumptions are:
* a. There is only 1 midroll plugin playing at a given time
* b. The only way that this midroll is of interest to us is if it's playing in the KDP MediaPlayer.
*/
public var activeMidrollPlugin : IMidrollSequencePlugin;
/**
* New parameter allowing an <code>ISequencePluin</code> to set the metadata values of the ad that is currently playing.
* Added for analytics use.
*/
public var activePluginMetadata : AdMetadataVO;
/**
* In case we want to ignore prerolls, for example, when starting the media from the middle with "mediaProxy.mediaPlayFrom"
*/
public var skipPrerolls:Boolean = false;
/**
* hodls the time remaining until skip ad will be available
*/
public var skipOffsetRemaining:int;
}
}
|
add "skipOffsetRemaining" parameter to sequenceVo
|
add "skipOffsetRemaining" parameter to sequenceVo
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp
|
be5316977523be13c5ae7c1f1ac7f59be3a2e258
|
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(_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)
);
}
}
}
|
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;
/**
* <p>The PhongEffect using the Phong lighting model to render the geometry according to
* the lighting setup of the scene. It supports an infinite number of lights/projected
* shadows and will automatically switch between singlepass and multipass rendering
* in order to give the best performances whenever possible.</p>
*
* </p>Because of the Stage3D restrictions regarding the number of shader operations or
* the number of available registers, the number of lights might be to big to allow them
* to be rendered in a single pass. In this situation, the PhongEffect will automatically
* fallback and use multipass rendering.</p>
*
* <p>Multipass rendering is done as follow:</p>
* <ul>
* <li>The "base" pass renders objects with one per-pixel directional lights with shadows,
* the lightmap and the ambient/emissive lighting.</li>
* <li>Each "additional" pass (one per light) will render a single light with shadows and
* blend it using additive blending.</li>
* </ul>
*
* The singlepass rendering will mimic this behavior in order to get preserve consistency.
*
* @author Jean-Marc Le Roux
*
*/
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)
);
}
}
}
|
add ASDoc to explain the behavior of PhongEffect
|
add ASDoc to explain the behavior of PhongEffect
|
ActionScript
|
mit
|
aerys/minko-as3
|
3825242b8cbf09fcd45251e882f42759e4b585dd
|
src/widgets/Geoprocessing/parameters/LinearUnitParameter.as
|
src/widgets/Geoprocessing/parameters/LinearUnitParameter.as
|
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 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 widgets.Geoprocessing.parameters
{
import com.esri.ags.tasks.supportClasses.LinearUnit;
import widgets.Geoprocessing.supportClasses.UnitMappingUtil;
public class LinearUnitParameter extends BaseParameter
{
//--------------------------------------------------------------------------
//
// Methods
//
//--------------------------------------------------------------------------
private function linearUnitString():String
{
return _defaultValue.distance + ":" + UnitMappingUtil.toPrettyUnits(_defaultValue.units);
}
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// defaultValue
//----------------------------------
private var _defaultValue:LinearUnit;
override public function get defaultValue():Object
{
return _defaultValue;
}
override public function set defaultValue(value:Object):void
{
_defaultValue = new LinearUnit(value.distance, value.units);
}
//----------------------------------
// type
//----------------------------------
override public function get type():String
{
return GPParameterTypes.LINEAR_UNIT;
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
override public function defaultValueFromString(description:String):void
{
var linearUnitTokens:Array = description.split(':');
_defaultValue = new LinearUnit(linearUnitTokens[0], UnitMappingUtil.toEsriUnits((linearUnitTokens[1])));
}
}
}
|
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 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 widgets.Geoprocessing.parameters
{
import com.esri.ags.tasks.supportClasses.LinearUnit;
import widgets.Geoprocessing.supportClasses.UnitMappingUtil;
public class LinearUnitParameter extends BaseParameter
{
//--------------------------------------------------------------------------
//
// Overridden properties
//
//--------------------------------------------------------------------------
//----------------------------------
// defaultValue
//----------------------------------
private var _defaultValue:LinearUnit;
override public function get defaultValue():Object
{
return _defaultValue;
}
override public function set defaultValue(value:Object):void
{
_defaultValue = new LinearUnit(value.distance, value.units);
}
//----------------------------------
// type
//----------------------------------
override public function get type():String
{
return GPParameterTypes.LINEAR_UNIT;
}
//--------------------------------------------------------------------------
//
// Overridden methods
//
//--------------------------------------------------------------------------
override public function defaultValueFromString(description:String):void
{
var linearUnitTokens:Array = description.split(':');
_defaultValue = new LinearUnit(linearUnitTokens[0], UnitMappingUtil.toEsriUnits((linearUnitTokens[1])));
}
}
}
|
Remove unused method.
|
Remove unused method.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex
|
d1a6b6ac3aba2a4aab668f8ff96ec390f7d4ae67
|
src/aerys/minko/type/loader/parser/ParserOptions.as
|
src/aerys/minko/type/loader/parser/ParserOptions.as
|
package aerys.minko.type.loader.parser
{
import aerys.minko.render.effect.Effect;
import aerys.minko.type.loader.ILoader;
import aerys.minko.type.loader.SceneLoader;
import aerys.minko.type.loader.TextureLoader;
import flash.net.URLRequest;
/**
* ParserOptions objects provide properties and function references
* to customize how a LoaderGroup object will load and interpret
* content.
*
* @author Jean-Marc Le Roux
*
*/
public final class ParserOptions
{
private var _loadDependencies : Boolean = false;
private var _dependencyLoaderClosure : Function = defaultDependencyLoaderClosure;
private var _mipmapTextures : Boolean = true;
private var _meshEffect : Effect = null;
private var _vertexStreamUsage : uint = 0;
private var _indexStreamUsage : uint = 0;
private var _parser : Class = null;
public function get parser():Class
{
return _parser;
}
public function set parser(value:Class):void
{
_parser = value;
}
public function get indexStreamUsage():uint
{
return _indexStreamUsage;
}
public function set indexStreamUsage(value:uint):void
{
_indexStreamUsage = value;
}
public function get vertexStreamUsage():uint
{
return _vertexStreamUsage;
}
public function set vertexStreamUsage(value:uint):void
{
_vertexStreamUsage = value;
}
public function get effect():Effect
{
return _meshEffect;
}
public function set effect(value:Effect):void
{
_meshEffect = value;
}
public function get mipmapTextures():Boolean
{
return _mipmapTextures;
}
public function set mipmapTextures(value:Boolean):void
{
_mipmapTextures = value;
}
public function get dependencyLoaderClosure():Function
{
return _dependencyLoaderClosure;
}
public function set dependencyLoaderClosure(value:Function):void
{
_dependencyLoaderClosure = value;
}
public function get loadDependencies():Boolean
{
return _loadDependencies;
}
public function set loadDependencies(value:Boolean):void
{
_loadDependencies = value;
}
public function ParserOptions(loadDependencies : Boolean = false,
dependencyLoaderClosure : Function = null,
mipmapTextures : Boolean = true,
meshEffect : Effect = null,
vertexStreamUsage : uint = 0,
indexStreamUsage : uint = 0,
parser : Class = null)
{
_loadDependencies = loadDependencies;
_dependencyLoaderClosure = _dependencyLoaderClosure || _dependencyLoaderClosure;
_mipmapTextures = mipmapTextures;
_meshEffect = meshEffect;
_vertexStreamUsage = vertexStreamUsage;
_indexStreamUsage = indexStreamUsage;
_parser = parser;
}
private function defaultDependencyLoaderClosure(dependencyPath : String,
isTexture : Boolean,
options : ParserOptions) : ILoader
{
var loader : ILoader;
if (isTexture)
{
loader = new TextureLoader(true);
loader.load(new URLRequest(dependencyPath));
}
else
{
loader = new SceneLoader(options);
loader.load(new URLRequest(dependencyPath));
}
return loader;
}
}
}
|
package aerys.minko.type.loader.parser
{
import aerys.minko.render.effect.Effect;
import aerys.minko.type.loader.ILoader;
import aerys.minko.type.loader.SceneLoader;
import aerys.minko.type.loader.TextureLoader;
import flash.net.URLRequest;
/**
* ParserOptions objects provide properties and function references
* to customize how a LoaderGroup object will load and interpret
* content.
*
* @author Jean-Marc Le Roux
*
*/
public final class ParserOptions
{
private var _loadDependencies : Boolean = false;
private var _dependencyLoaderClosure : Function = defaultDependencyLoaderClosure;
private var _mipmapTextures : Boolean = true;
private var _meshEffect : Effect = null;
private var _vertexStreamUsage : uint = 0;
private var _indexStreamUsage : uint = 0;
private var _parser : Class = null;
public function get parser():Class
{
return _parser;
}
public function set parser(value:Class):void
{
_parser = value;
}
public function get indexStreamUsage():uint
{
return _indexStreamUsage;
}
public function set indexStreamUsage(value:uint):void
{
_indexStreamUsage = value;
}
public function get vertexStreamUsage():uint
{
return _vertexStreamUsage;
}
public function set vertexStreamUsage(value:uint):void
{
_vertexStreamUsage = value;
}
public function get effect():Effect
{
return _meshEffect;
}
public function set effect(value:Effect):void
{
_meshEffect = value;
}
public function get mipmapTextures():Boolean
{
return _mipmapTextures;
}
public function set mipmapTextures(value:Boolean):void
{
_mipmapTextures = value;
}
public function get dependencyLoaderClosure():Function
{
return _dependencyLoaderClosure;
}
public function set dependencyLoaderClosure(value:Function):void
{
_dependencyLoaderClosure = value;
}
public function get loadDependencies():Boolean
{
return _loadDependencies;
}
public function set loadDependencies(value:Boolean):void
{
_loadDependencies = value;
}
public function ParserOptions(loadDependencies : Boolean = false,
dependencyLoaderClosure : Function = null,
mipmapTextures : Boolean = true,
meshEffect : Effect = null,
vertexStreamUsage : uint = 0,
indexStreamUsage : uint = 0,
parser : Class = null)
{
_loadDependencies = loadDependencies;
_dependencyLoaderClosure = dependencyLoaderClosure || _dependencyLoaderClosure;
_mipmapTextures = mipmapTextures;
_meshEffect = meshEffect;
_vertexStreamUsage = vertexStreamUsage;
_indexStreamUsage = indexStreamUsage;
_parser = parser;
}
private function defaultDependencyLoaderClosure(dependencyPath : String,
isTexture : Boolean,
options : ParserOptions) : ILoader
{
var loader : ILoader;
if (isTexture)
{
loader = new TextureLoader(true);
loader.load(new URLRequest(dependencyPath));
}
else
{
loader = new SceneLoader(options);
loader.load(new URLRequest(dependencyPath));
}
return loader;
}
}
}
|
Fix a typo in ParserOptions constructor
|
Fix a typo in ParserOptions constructor
|
ActionScript
|
mit
|
aerys/minko-as3
|
8eb7d7978dfd82a0b5f3b21ab5ec2a462bef3aa1
|
FlexUnit4/src/org/flexunit/events/UnknownError.as
|
FlexUnit4/src/org/flexunit/events/UnknownError.as
|
package org.flexunit.events
{
import flash.events.ErrorEvent;
import flash.events.Event;
public class UnknownError extends Error
{
public function UnknownError( event:Event )
{
var error:Error;
if ( event.hasOwnProperty( "error" ) ) {
var errorGeneric:* = event[ "error" ];
if ( errorGeneric is Error ) {
error = errorGeneric as Error;
} else if ( errorGeneric is ErrorEvent ) {
var errorEvent:ErrorEvent = errorGeneric as ErrorEvent;
error = new Error( "Top Level Error", errorEvent.errorID );
}
}
super( error.message, error.errorID );
}
}
}
|
package org.flexunit.events
{
import flash.events.ErrorEvent;
import flash.events.Event;
public class UnknownError extends Error
{
public function UnknownError( event:Event )
{
var error:Error;
if ( event.hasOwnProperty( "error" ) ) {
var errorGeneric:* = event[ "error" ];
if ( errorGeneric is Error ) {
error = errorGeneric as Error;
} else if ( errorGeneric is ErrorEvent ) {
var errorEvent:ErrorEvent = errorGeneric as ErrorEvent;
error = new Error( "Top Level Error", Object(errorEvent).errorID );
}
}
super( error.message, error.errorID );
}
}
}
|
Fix for build issue around unknown error
|
Fix for build issue around unknown error
|
ActionScript
|
apache-2.0
|
SlavaRa/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit
|
4d3a78c26f33458b42b1d88a1837d8145bce0a5e
|
src/org/flintparticles/integration/away3d/v4/A3D4Renderer.as
|
src/org/flintparticles/integration/away3d/v4/A3D4Renderer.as
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord & Michael Ivanov
* 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.integration.away3d.v4
{
import away3d.containers.ObjectContainer3D;
import away3d.core.base.Object3D;
import away3d.core.math.Vector3DUtils;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.common.renderers.RendererBase;
import org.flintparticles.common.utils.Maths;
import org.flintparticles.integration.away3d.v4.utils.Convert;
import org.flintparticles.threeD.particles.Particle3D;
import flash.geom.Vector3D;
/**
* Renders the particles in an Away3D4 scene.
*
* <p>To use this renderer, the particles' image properties should be
* Away3D v4(Molehill API based) objects, renderable in an Away3D scene. This renderer
* doesn't update the scene, but copies each particle's properties
* to its image object so next time the Away3D scene is rendered the
* image objects are drawn according to the state of the particle
* system.</p>
*/
public class A3D4Renderer extends RendererBase
{
private var _container:ObjectContainer3D;
/**
* The constructor creates an Away3D renderer for displaying the
* particles in an Away3D scene.
*
* @param container An Away3D object container. The particle display
* objects are created inside this object container.
*/
///Added by Michael--second param defines recycling mode
private var _recycleParticles:Boolean=false;
public function A3D4Renderer( container:ObjectContainer3D ,recycleParticles:Boolean=false)
{
super();
_container = container;
_recycleParticles=recycleParticles;
}
/**
* This method copies the particle's state to the associated image object.
*
* <p>This method is called internally by Flint and shouldn't need to be
* called by the user.</p>
*
* @param particles The particles to be rendered.
*/
override protected function renderParticles( particles:Array ):void
{
for each( var p:Particle3D in particles )
{
renderParticle( p );
}
}
protected function renderParticle( particle:Particle3D ):void
{
// N.B. Sprite3D is a subclass of Object3D so we don't need to treat it as a special case
if( particle.image is Object3D )
{
var obj:Object3D = particle.image as Object3D;
obj.x = particle.position.x;
obj.y = particle.position.y;
obj.z = particle.position.z;
obj.scaleX = obj.scaleY = obj.scaleZ = particle.scale;
var rotation:flash.geom.Vector3D = away3d.core.math.Vector3DUtils.quaternion2euler( Convert.QuaternionToA3D( particle.rotation ) );
obj.rotationX = Maths.asDegrees( rotation.x );
obj.rotationY = Maths.asDegrees( rotation.y );
obj.rotationZ = Maths.asDegrees( rotation.z );
if( obj.hasOwnProperty("material") )
{
var material:Object = obj["material"];
if( material.hasOwnProperty( "colorTransform" ) )
{
material["colorTransform"] = particle.colorTransform;
}
else
{
if( material.hasOwnProperty( "color" ) )
{
material["color"] = particle.color & 0xFFFFFF;
}
if( material.hasOwnProperty( "alpha" ) )
{
material["alpha"] = particle.alpha;
}
}
}
}
}
/**
* This method is called when a particle is added to an emitter -
* usually because the emitter has just created the particle. The
* method adds the particle's image to the container's display list.
* It is called internally by Flint and need not be called by the user.
*
* @param particle The particle being added to the emitter.
*/
override protected function addParticle( particle:Particle ):void
{
if( particle.image is ObjectContainer3D )
{
_container.addChild( ObjectContainer3D( particle.image ) );
renderParticle( Particle3D( particle ) );
}
}
/**
* This method is called when a particle is removed from an emitter -
* usually because the particle is dying. The method removes the
* particle's image from the container's display list. It is called
* internally by Flint and need not be called by the user.
*
* @param particle The particle being removed from the emitter.
*/
override protected function removeParticle( particle:Particle ):void
{
// We can't clean up the 3d object here because the particle may not be dead.
// We need to handle disposal elsewhere
if( particle.image is ObjectContainer3D )
{
_container.removeChild( ObjectContainer3D( particle.image ) );
}
}
}
}
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord & Michael Ivanov
* 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.integration.away3d.v4
{
import away3d.containers.ObjectContainer3D;
import away3d.core.base.Object3D;
import away3d.core.math.Vector3DUtils;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.common.renderers.RendererBase;
import org.flintparticles.common.utils.Maths;
import org.flintparticles.integration.away3d.v4.utils.Convert;
import org.flintparticles.threeD.particles.Particle3D;
import flash.geom.Vector3D;
/**
* Renders the particles in an Away3D4 scene.
*
* <p>To use this renderer, the particles' image properties should be
* Away3D v4(Molehill API based) objects, renderable in an Away3D scene. This renderer
* doesn't update the scene, but copies each particle's properties
* to its image object so next time the Away3D scene is rendered the
* image objects are drawn according to the state of the particle
* system.</p>
*/
public class A3D4Renderer extends RendererBase
{
private var _container:ObjectContainer3D;
/**
* The constructor creates an Away3D renderer for displaying the
* particles in an Away3D scene.
*
* @param container An Away3D object container. The particle display
* objects are created inside this object container.
*/
public function A3D4Renderer( container:ObjectContainer3D )
{
super();
_container = container;
}
/**
* This method copies the particle's state to the associated image object.
*
* <p>This method is called internally by Flint and shouldn't need to be
* called by the user.</p>
*
* @param particles The particles to be rendered.
*/
override protected function renderParticles( particles:Array ):void
{
for each( var p:Particle3D in particles )
{
renderParticle( p );
}
}
protected function renderParticle( particle:Particle3D ):void
{
// N.B. Sprite3D is a subclass of Object3D so we don't need to treat it as a special case
if( particle.image is Object3D )
{
var obj:Object3D = particle.image as Object3D;
obj.x = particle.position.x;
obj.y = particle.position.y;
obj.z = particle.position.z;
obj.scaleX = obj.scaleY = obj.scaleZ = particle.scale;
var rotation:flash.geom.Vector3D = away3d.core.math.Vector3DUtils.quaternion2euler( Convert.QuaternionToA3D( particle.rotation ) );
obj.rotationX = Maths.asDegrees( rotation.x );
obj.rotationY = Maths.asDegrees( rotation.y );
obj.rotationZ = Maths.asDegrees( rotation.z );
if( obj.hasOwnProperty("material") )
{
var material:Object = obj["material"];
if( material.hasOwnProperty( "colorTransform" ) )
{
material["colorTransform"] = particle.colorTransform;
}
else
{
if( material.hasOwnProperty( "color" ) )
{
material["color"] = particle.color & 0xFFFFFF;
}
if( material.hasOwnProperty( "alpha" ) )
{
material["alpha"] = particle.alpha;
}
}
}
}
}
/**
* This method is called when a particle is added to an emitter -
* usually because the emitter has just created the particle. The
* method adds the particle's image to the container's display list.
* It is called internally by Flint and need not be called by the user.
*
* @param particle The particle being added to the emitter.
*/
override protected function addParticle( particle:Particle ):void
{
if( particle.image is ObjectContainer3D )
{
_container.addChild( ObjectContainer3D( particle.image ) );
renderParticle( Particle3D( particle ) );
}
}
/**
* This method is called when a particle is removed from an emitter -
* usually because the particle is dying. The method removes the
* particle's image from the container's display list. It is called
* internally by Flint and need not be called by the user.
*
* @param particle The particle being removed from the emitter.
*/
override protected function removeParticle( particle:Particle ):void
{
// We can't clean up the 3d object here because the particle may not be dead.
// We need to handle disposal elsewhere
if( particle.image is ObjectContainer3D )
{
_container.removeChild( ObjectContainer3D( particle.image ) );
}
}
}
}
|
Remove unused local variable
|
Remove unused local variable
|
ActionScript
|
mit
|
richardlord/Flint
|
05a5b6c108400b7f32f8c904e88efc2ded82b736
|
src/GA_FLASH.as
|
src/GA_FLASH.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
{
import com.google.analytics.AnalyticsTracker;
import com.google.analytics.components.FlashTracker;
import com.google.analytics.events.AnalyticsEvent;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
/* Stub to test the AS3 API in pure ActionScript
but compiled with mxmlc
*/
[SWF(width="800", height="600", backgroundColor='0xffffff', frameRate='24', pageTitle='test', scriptRecursionLimit='1000', scriptTimeLimit='60')]
public class GA_FLASH extends Sprite
{
private var tracker:AnalyticsTracker;
public function GA_FLASH()
{
this.stage.align = StageAlign.TOP_LEFT;
this.stage.scaleMode = StageScaleMode.NO_SCALE;
addEventListener( Event.ADDED_TO_STAGE, onComplete );
}
public function onComplete( evt:Event ):void
{
/* note:
here we simulate the FlashTracker component
as if it was a Flash visual component
by adding it to the display list
*/
tracker = new FlashTracker();
tracker.trackPageview( "/test" );
tracker.addEventListener( AnalyticsEvent.READY, onAnalyticsReady );
tracker.account = "UA-4241494-2";
tracker.mode = "AS3";
tracker.visualDebug = true;
addChild( tracker as DisplayObject );
}
public function onAnalyticsReady( event:AnalyticsEvent ):void
{
//trace( "onAnalyticsReady()" );
var tracker:AnalyticsTracker = event.tracker;
tracker.debug.verbose = true;
tracker.trackPageview( "/hello/world" );
}
}
}
|
/*
* 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
{
import com.google.analytics.AnalyticsTracker;
import com.google.analytics.components.FlashTracker;
import com.google.analytics.events.AnalyticsEvent;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
/* Stub to test the AS3 API in pure ActionScript
but compiled with mxmlc
*/
[SWF(width="800", height="600", backgroundColor='0xffffff', frameRate='24', pageTitle='test', scriptRecursionLimit='1000', scriptTimeLimit='60')]
public class GA_FLASH extends Sprite
{
private var tracker:AnalyticsTracker;
public function GA_FLASH()
{
this.stage.align = StageAlign.TOP_LEFT;
this.stage.scaleMode = StageScaleMode.NO_SCALE;
addEventListener( Event.ADDED_TO_STAGE, onComplete );
}
public function onComplete( evt:Event ):void
{
/* note:
here we simulate the FlashTracker component
as if it was a Flash visual component
by adding it to the display list
*/
tracker = new FlashTracker();
tracker.trackPageview( "/test" ); //test cache
tracker.addEventListener( AnalyticsEvent.READY, onAnalyticsReady );
tracker.account = "UA-111-222";
tracker.mode = "AS3";
tracker.visualDebug = true;
addChild( tracker as DisplayObject );
}
public function onAnalyticsReady( event:AnalyticsEvent ):void
{
//trace( "onAnalyticsReady()" );
var tracker:AnalyticsTracker = event.tracker;
tracker.debug.verbose = true;
tracker.trackPageview( "/hello/world" );
}
}
}
|
clean up GA_FLASH
|
clean up GA_FLASH
|
ActionScript
|
apache-2.0
|
soumavachakraborty/gaforflash,Miyaru/gaforflash,dli-iclinic/gaforflash,DimaBaliakin/gaforflash,nsdevaraj/gaforflash,jeremy-wischusen/gaforflash,drflash/gaforflash,Vigmar/gaforflash,jisobkim/gaforflash,DimaBaliakin/gaforflash,dli-iclinic/gaforflash,Miyaru/gaforflash,minimedj/gaforflash,minimedj/gaforflash,mrthuanvn/gaforflash,soumavachakraborty/gaforflash,jisobkim/gaforflash,jeremy-wischusen/gaforflash,drflash/gaforflash,nsdevaraj/gaforflash,mrthuanvn/gaforflash,Vigmar/gaforflash
|
3f71f1857123a1c58c0dd68bd830b874d475e751
|
src/renderers/FlashCommon.as
|
src/renderers/FlashCommon.as
|
/*
* Copyright 2016 Google Inc. 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 {
import flash.external.ExternalInterface;
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.display.BlendMode;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.UncaughtErrorEvent;
import flash.text.TextField;
import flash.system.Security;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.geom.Matrix3D;
import flash.geom.Vector3D;
import flash.geom.PerspectiveProjection;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.setTimeout;
import flash.net.URLRequest;
public class FlashCommon extends Sprite {
private var imageLoadedCallback:String = null;
public function FlashCommon() {
// Install event handler for uncaught errors.
loaderInfo.uncaughtErrorEvents.addEventListener(
UncaughtErrorEvent.UNCAUGHT_ERROR, handleError);
// Declare external interface.
ExternalInterface.marshallExceptions = true
ExternalInterface.addCallback('isReady', isReady);
ExternalInterface.addCallback('createLayer', createLayer);
ExternalInterface.addCallback('destroyLayer', destroyLayer);
ExternalInterface.addCallback('loadImage', loadImage);
ExternalInterface.addCallback('cancelImage', cancelImage);
ExternalInterface.addCallback('unloadImage', unloadImage);
ExternalInterface.addCallback('createTexture', createTexture);
ExternalInterface.addCallback('destroyTexture', destroyTexture);
ExternalInterface.addCallback('drawCubeTiles', drawCubeTiles);
ExternalInterface.addCallback('drawFlatTiles', drawFlatTiles);
var callbacksObjName:String = root.loaderInfo.parameters.callbacksObjName as String;
imageLoadedCallback = callbacksObjName + '.imageLoaded';
Security.allowDomain("*");
if (stage) {
init();
} else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
private function handleError(event:UncaughtErrorEvent):void {
var message:String;
if (event.error is Error) {
message = Error(event.error).message;
} else if (event.error is ErrorEvent) {
message = ErrorEvent(event.error).text;
} else {
message = event.error.toString();
}
debug('ERROR: ' + message);
};
private function debug(str:String):void {
ExternalInterface.call('console.log', str);
}
public function isReady():Boolean {
return true;
}
private function init():void {
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.frameRate = 60;
}
private function convertFov(fov:Number, thisDimension:Number, otherDimension:Number):Number {
return 2 * Math.atan(otherDimension * Math.tan(fov / 2) / thisDimension);
}
private function getLayer(id:Number):Sprite {
if (id in layerMap) {
return layerMap[id];
}
return null;
}
public function createLayer(id: Number):void {
if (id in layerMap) {
debug('createLayer: ' + id + ' already exists');
return;
}
var layer:Sprite = new Sprite();
layerMap[id] = layer;
layer.transform.perspectiveProjection = new PerspectiveProjection();
layer.blendMode = BlendMode.LAYER;
addChild(layer);
}
public function destroyLayer(id:Number):void {
if (!(id in layerMap)) {
debug('destroyLayer: ' + id + ' does not exist');
return;
}
var layer:Sprite = layerMap[id];
while (layer.numChildren > 0) {
layer.removeChildAt(0);
}
removeChild(layer);
delete layerMap[id];
}
public function drawCubeTiles(layerId:Number, width:Number, height:Number, left:Number, top:Number, alpha:Number, yaw:Number, pitch:Number, roll:Number, fov:Number, tiles:Array):void {
var layer:Sprite = getLayer(layerId);
if (!layer) {
debug('drawCubeTiles: layer ' + layerId + ' does not exist');
}
// Remove all current children.
while (layer.numChildren > 0) {
layer.removeChildAt(0);
}
// Set viewport.
layer.x = left;
layer.y = top;
layer.scrollRect = new Rectangle(0, 0, width, height);
// Set opacity.
layer.alpha = alpha;
// Set fov.
// Don't really know why this needs to be done; magic number adjusted from
// https://github.com/fieldOfView/CuTy/blob/master/com/fieldofview/cuty/CutyScene.as#L260
var fieldOfView:Number = convertFov(fov, 1, 500/height);
layer.transform.perspectiveProjection.fieldOfView = fieldOfView * 180/Math.PI;
var projectionCenter:Point = new Point(width/2, height/2);
layer.transform.perspectiveProjection.projectionCenter = projectionCenter;
var focalLength:Number = layer.transform.perspectiveProjection.focalLength;
var viewportCenter:Vector3D = new Vector3D(width/2, height/2, 0);
var focalCenter:Vector3D = new Vector3D(width/2, height/2, -focalLength);
for each (var t:Object in tiles) {
var texture:Sprite = textureMap[t.textureId];
if (!texture) {
debug('drawCubeTiles: texture ' + t.textureId + ' does not exist');
}
var m:Matrix3D = new Matrix3D();
// Set the perspective depth.
m.appendTranslation(0, 0, -focalLength);
// Center tile in viewport.
var offsetX:Number = width/2 - t.width/2;
var offsetY:Number = height/2 - t.height/2;
m.appendTranslation(offsetX, offsetY, 0);
// Set tile offset within cube face.
var translX:Number = t.centerX * t.levelSize - t.padLeft;
var translY:Number = -t.centerY * t.levelSize - t.padTop;
var translZ:Number = t.levelSize / 2;
m.appendTranslation(translX, translY, translZ);
// Set cube face rotation.
m.appendRotation(-t.rotY, Vector3D.Y_AXIS, focalCenter);
m.appendRotation(t.rotX, Vector3D.X_AXIS, focalCenter);
// Set camera rotation.
var rotX:Number = pitch*180/Math.PI;
var rotY:Number = -yaw*180/Math.PI;
var rotZ:Number = -roll*180/Math.PI;
m.appendRotation(rotY, Vector3D.Y_AXIS, focalCenter);
m.appendRotation(rotX, Vector3D.X_AXIS, focalCenter);
m.appendRotation(rotZ, Vector3D.Z_AXIS, focalCenter);
texture.transform.matrix3D = m;
layer.addChild(texture);
}
}
public function drawFlatTiles(layerId:Number, width:Number, height:Number, left:Number, top:Number, alpha:Number, x:Number, y:Number, zoomX:Number, zoomY:Number, tiles:Array):void {
var layer:Sprite = getLayer(layerId);
if (!layer) {
debug('drawFlatTiles: layer ' + layerId + ' does not exist');
}
// Remove all current children.
while (layer.numChildren > 0) {
layer.removeChildAt(0);
}
// Set viewport.
layer.x = left;
layer.y = top;
layer.scrollRect = new Rectangle(0, 0, width, height);
// Set opacity.
layer.alpha = alpha;
// Determine the zoom factor.
zoomX = width / zoomX;
zoomY = height / zoomY;
for each (var t:Object in tiles) {
var texture:Sprite = textureMap[t.textureId];
if (!texture) {
debug('drawFlatTiles: texture ' + t.textureId + ' does not exist');
}
var m:Matrix3D = new Matrix3D();
// Scale tile into correct size.
var scaleX:Number = zoomX / t.levelWidth;
var scaleY:Number = zoomY / t.levelHeight;
m.appendScale(scaleX, scaleY, 1);
// Place top left corner of tile at the center of the viewport.
var offsetX:Number = width/2;
var offsetY:Number = height/2;
m.appendTranslation(offsetX, offsetY, 0);
// Move tile into its position within the image.
var cornerX:Number = t.centerX - t.scaleX / 2 + 0.5;
var cornerY:Number = 0.5 - t.centerY - t.scaleY / 2;
var posX:Number = cornerX * zoomX;
var posY:Number = cornerY * zoomY;
m.appendTranslation(posX, posY, 0);
// Compensate for padding around the tile.
m.appendTranslation(-t.padLeft, -t.padTop, 0);
// Apply view offsets.
var translX:Number = -x * zoomX;
var translY:Number = -y * zoomY;
m.appendTranslation(translX, translY, 0);
texture.transform.matrix3D = m;
layer.addChild(texture);
}
}
private var imageMap:Dictionary = new Dictionary();
private var textureMap:Dictionary = new Dictionary();
private var layerMap:Dictionary = new Dictionary();
private var nextId:Number = 1;
public function loadImage(url:String, width:Number, height:Number, x:Number, y:Number):Number {
var id:Number = nextId++;
var loader:Loader = new Loader();
imageMap[id] = loader;
// TODO: Check if there are there other kinds of errors we can catch.
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadSuccess);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);
var urlRequest:URLRequest = new URLRequest(url);
loader.load(urlRequest);
return id;
function loadSuccess(e:Event):void {
if (!imageMap[id]) {
// Probably canceled before load was complete; ignore.
return;
}
var image:Bitmap = Bitmap(loader.content);
// Convert relative offset/size to absolute values.
x *= image.bitmapData.width;
y *= image.bitmapData.height;
width *= image.bitmapData.width;
height *= image.bitmapData.height;
var croppedData:BitmapData = new BitmapData(width, height);
croppedData.copyPixels(image.bitmapData, new Rectangle(x, y, width, height), new Point(0,0));
imageMap[id] = croppedData;
ExternalInterface.call(imageLoadedCallback, false, id);
}
function loadError(e:IOErrorEvent):void {
if (!imageMap[id]) {
// Probably canceled before load was complete; ignore.
return;
}
delete imageMap[id];
ExternalInterface.call(imageLoadedCallback, true, id);
}
}
public function cancelImage(id:Number):void {
if (!imageMap[id]) {
debug('cancelImage: image ' + id + ' does not exist');
return;
}
unloadImage(id);
}
public function unloadImage(id:Number):void {
var loaderOrBitmapData:Object = imageMap[id];
if (!loaderOrBitmapData) {
debug('unloadImage: image ' + id + ' does not exist');
return;
}
if (loaderOrBitmapData is Loader) {
var loader:Loader = loaderOrBitmapData as Loader;
// Calling close() after the load is complete seems to cause an error,
// so first check that we are still loading.
if (loader.contentLoaderInfo.bytesTotal != 0 && loader.contentLoaderInfo.bytesLoaded != loader.contentLoaderInfo.bytesTotal) {
loader.close();
}
}
delete imageMap[id];
}
public function createTexture(imageId:Number, width:Number, height:Number, padTop:Number, padBottom:Number, padLeft:Number, padRight:Number):Number {
var image:BitmapData = imageMap[imageId];
var i:Number;
var point:Point = new Point();
var rect:Rectangle = new Rectangle();
// Create new bitmap for texture.
var bitmap:BitmapData = new BitmapData(width + padLeft + padRight, height + padTop + padBottom, true, 0x00FFFFFF);
// Resize source image if the texture has a different size.
// TODO: it would be better to call draw() directly on the final bitmap
// with both a matrix and a clippingRect parameter; this would both be
// faster and allocate less memory. However, the clippingRect parameter
// for the draw() method doesn't seem to work as documented.
var scaled:BitmapData;
if (width !== image.width || height !== image.height) {
scaled = new BitmapData(width, height, true, 0x00FFFFFF);
var mat:Matrix = new Matrix(width / image.width, 0, 0, height / image.height, 0, 0);
scaled.draw(image, mat, null, null, null, true);
} else {
scaled = image;
}
// Draw image into texture.
rect.x = 0;
rect.y = 0;
rect.width = width;
rect.height = height;
point.x = padLeft;
point.y = padTop;
bitmap.copyPixels(scaled, rect, point);
// Draw top padding.
for (i = 0; i <= padTop; i++) {
rect.x = padLeft;
rect.y = padTop;
rect.width = width;
rect.height = 1;
point.x = padLeft;
point.y = i;
bitmap.copyPixels(bitmap, rect, point);
}
// Draw left padding.
for (i = 0; i <= padLeft; i++) {
rect.x = padLeft;
rect.y = padTop;
rect.width = 1;
rect.height = height;
point.x = i;
point.y = padTop;
bitmap.copyPixels(bitmap, rect, point);
}
// Draw bottom padding.
for (i = 0; i <= padBottom; i++) {
rect.x = padLeft;
rect.y = padTop + height - 1;
rect.width = width;
rect.height = 1;
point.x = padLeft;
point.y = padTop + height + i;
bitmap.copyPixels(bitmap, rect, point);
}
// Draw right padding.
for (i = 0; i <= padRight; i++) {
rect.x = padLeft + width - 1;
rect.y = padTop;
rect.width = 1;
rect.height = height;
point.x = padLeft + width + i;
point.y = padTop;
bitmap.copyPixels(bitmap, rect, point);
}
var texture:Sprite = new Sprite();
texture.addChild(new Bitmap(bitmap));
var textureId:Number = imageId;
textureMap[textureId] = texture;
return textureId;
}
public function destroyTexture(id:Number):void {
var texture:Sprite = textureMap[id];
if (!texture) {
debug('destroyTexture: texture ' + id + ' does not exist');
return;
}
if (texture.parent) {
texture.parent.removeChild(texture);
}
delete textureMap[id];
}
}
}
|
/*
* Copyright 2016 Google Inc. 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 {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BlendMode;
import flash.display.Loader;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.UncaughtErrorEvent;
import flash.external.ExternalInterface;
import flash.geom.Matrix;
import flash.geom.Matrix3D;
import flash.geom.PerspectiveProjection;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.geom.Vector3D;
import flash.net.URLRequest;
import flash.system.Security;
import flash.utils.Dictionary;
public class FlashCommon extends Sprite {
private var imageLoadedCallback:String = null;
public function FlashCommon() {
// Install event handler for uncaught errors.
loaderInfo.uncaughtErrorEvents.addEventListener(
UncaughtErrorEvent.UNCAUGHT_ERROR, handleError);
// Declare external interface.
ExternalInterface.marshallExceptions = true
ExternalInterface.addCallback('isReady', isReady);
ExternalInterface.addCallback('createLayer', createLayer);
ExternalInterface.addCallback('destroyLayer', destroyLayer);
ExternalInterface.addCallback('loadImage', loadImage);
ExternalInterface.addCallback('cancelImage', cancelImage);
ExternalInterface.addCallback('unloadImage', unloadImage);
ExternalInterface.addCallback('createTexture', createTexture);
ExternalInterface.addCallback('destroyTexture', destroyTexture);
ExternalInterface.addCallback('drawCubeTiles', drawCubeTiles);
ExternalInterface.addCallback('drawFlatTiles', drawFlatTiles);
var callbacksObjName:String = loaderInfo.parameters.callbacksObjName as String;
imageLoadedCallback = callbacksObjName + '.imageLoaded';
Security.allowDomain("*");
if (stage) {
init();
} else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
private function handleError(event:UncaughtErrorEvent):void {
var message:String;
if (event.error is Error) {
message = Error(event.error).message;
} else if (event.error is ErrorEvent) {
message = ErrorEvent(event.error).text;
} else {
message = event.error.toString();
}
debug('ERROR: ' + message);
};
private function debug(str:String):void {
ExternalInterface.call('console.log', str);
}
public function isReady():Boolean {
return true;
}
private function init():void {
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.frameRate = 60;
}
private function convertFov(fov:Number, thisDimension:Number, otherDimension:Number):Number {
return 2 * Math.atan(otherDimension * Math.tan(fov / 2) / thisDimension);
}
private function getLayer(id:Number):Sprite {
if (id in layerMap) {
return layerMap[id];
}
return null;
}
public function createLayer(id: Number):void {
if (id in layerMap) {
debug('createLayer: ' + id + ' already exists');
return;
}
var layer:Sprite = new Sprite();
layerMap[id] = layer;
layer.transform.perspectiveProjection = new PerspectiveProjection();
layer.blendMode = BlendMode.LAYER;
addChild(layer);
}
public function destroyLayer(id:Number):void {
if (!(id in layerMap)) {
debug('destroyLayer: ' + id + ' does not exist');
return;
}
var layer:Sprite = layerMap[id];
while (layer.numChildren > 0) {
layer.removeChildAt(0);
}
removeChild(layer);
delete layerMap[id];
}
public function drawCubeTiles(layerId:Number, width:Number, height:Number, left:Number, top:Number, alpha:Number, yaw:Number, pitch:Number, roll:Number, fov:Number, tiles:Array):void {
var layer:Sprite = getLayer(layerId);
if (!layer) {
debug('drawCubeTiles: layer ' + layerId + ' does not exist');
}
// Remove all current children.
while (layer.numChildren > 0) {
layer.removeChildAt(0);
}
// Set viewport.
layer.x = left;
layer.y = top;
layer.scrollRect = new Rectangle(0, 0, width, height);
// Set opacity.
layer.alpha = alpha;
// Set fov.
// Don't really know why this needs to be done; magic number adjusted from
// https://github.com/fieldOfView/CuTy/blob/master/com/fieldofview/cuty/CutyScene.as#L260
var fieldOfView:Number = convertFov(fov, 1, 500/height);
layer.transform.perspectiveProjection.fieldOfView = fieldOfView * 180/Math.PI;
var projectionCenter:Point = new Point(width/2, height/2);
layer.transform.perspectiveProjection.projectionCenter = projectionCenter;
var focalLength:Number = layer.transform.perspectiveProjection.focalLength;
var viewportCenter:Vector3D = new Vector3D(width/2, height/2, 0);
var focalCenter:Vector3D = new Vector3D(width/2, height/2, -focalLength);
for each (var t:Object in tiles) {
var texture:Sprite = textureMap[t.textureId];
if (!texture) {
debug('drawCubeTiles: texture ' + t.textureId + ' does not exist');
}
var m:Matrix3D = new Matrix3D();
// Set the perspective depth.
m.appendTranslation(0, 0, -focalLength);
// Center tile in viewport.
var offsetX:Number = width/2 - t.width/2;
var offsetY:Number = height/2 - t.height/2;
m.appendTranslation(offsetX, offsetY, 0);
// Set tile offset within cube face.
var translX:Number = t.centerX * t.levelSize - t.padLeft;
var translY:Number = -t.centerY * t.levelSize - t.padTop;
var translZ:Number = t.levelSize / 2;
m.appendTranslation(translX, translY, translZ);
// Set cube face rotation.
m.appendRotation(-t.rotY, Vector3D.Y_AXIS, focalCenter);
m.appendRotation(t.rotX, Vector3D.X_AXIS, focalCenter);
// Set camera rotation.
var rotX:Number = pitch*180/Math.PI;
var rotY:Number = -yaw*180/Math.PI;
var rotZ:Number = -roll*180/Math.PI;
m.appendRotation(rotY, Vector3D.Y_AXIS, focalCenter);
m.appendRotation(rotX, Vector3D.X_AXIS, focalCenter);
m.appendRotation(rotZ, Vector3D.Z_AXIS, focalCenter);
texture.transform.matrix3D = m;
layer.addChild(texture);
}
}
public function drawFlatTiles(layerId:Number, width:Number, height:Number, left:Number, top:Number, alpha:Number, x:Number, y:Number, zoomX:Number, zoomY:Number, tiles:Array):void {
var layer:Sprite = getLayer(layerId);
if (!layer) {
debug('drawFlatTiles: layer ' + layerId + ' does not exist');
}
// Remove all current children.
while (layer.numChildren > 0) {
layer.removeChildAt(0);
}
// Set viewport.
layer.x = left;
layer.y = top;
layer.scrollRect = new Rectangle(0, 0, width, height);
// Set opacity.
layer.alpha = alpha;
// Determine the zoom factor.
zoomX = width / zoomX;
zoomY = height / zoomY;
for each (var t:Object in tiles) {
var texture:Sprite = textureMap[t.textureId];
if (!texture) {
debug('drawFlatTiles: texture ' + t.textureId + ' does not exist');
}
var m:Matrix3D = new Matrix3D();
// Scale tile into correct size.
var scaleX:Number = zoomX / t.levelWidth;
var scaleY:Number = zoomY / t.levelHeight;
m.appendScale(scaleX, scaleY, 1);
// Place top left corner of tile at the center of the viewport.
var offsetX:Number = width/2;
var offsetY:Number = height/2;
m.appendTranslation(offsetX, offsetY, 0);
// Move tile into its position within the image.
var cornerX:Number = t.centerX - t.scaleX / 2 + 0.5;
var cornerY:Number = 0.5 - t.centerY - t.scaleY / 2;
var posX:Number = cornerX * zoomX;
var posY:Number = cornerY * zoomY;
m.appendTranslation(posX, posY, 0);
// Compensate for padding around the tile.
m.appendTranslation(-t.padLeft, -t.padTop, 0);
// Apply view offsets.
var translX:Number = -x * zoomX;
var translY:Number = -y * zoomY;
m.appendTranslation(translX, translY, 0);
texture.transform.matrix3D = m;
layer.addChild(texture);
}
}
private var imageMap:Dictionary = new Dictionary();
private var textureMap:Dictionary = new Dictionary();
private var layerMap:Dictionary = new Dictionary();
private var nextId:Number = 1;
public function loadImage(url:String, width:Number, height:Number, x:Number, y:Number):Number {
var id:Number = nextId++;
var loader:Loader = new Loader();
imageMap[id] = loader;
// TODO: Check if there are there other kinds of errors we can catch.
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadSuccess);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, loadError);
var urlRequest:URLRequest = new URLRequest(url);
loader.load(urlRequest);
return id;
function loadSuccess(e:Event):void {
if (!imageMap[id]) {
// Probably canceled before load was complete; ignore.
return;
}
var image:Bitmap = Bitmap(loader.content);
// Convert relative offset/size to absolute values.
x *= image.bitmapData.width;
y *= image.bitmapData.height;
width *= image.bitmapData.width;
height *= image.bitmapData.height;
var croppedData:BitmapData = new BitmapData(width, height);
croppedData.copyPixels(image.bitmapData, new Rectangle(x, y, width, height), new Point(0,0));
imageMap[id] = croppedData;
ExternalInterface.call(imageLoadedCallback, false, id);
}
function loadError(e:IOErrorEvent):void {
if (!imageMap[id]) {
// Probably canceled before load was complete; ignore.
return;
}
delete imageMap[id];
ExternalInterface.call(imageLoadedCallback, true, id);
}
}
public function cancelImage(id:Number):void {
if (!imageMap[id]) {
debug('cancelImage: image ' + id + ' does not exist');
return;
}
unloadImage(id);
}
public function unloadImage(id:Number):void {
var loaderOrBitmapData:Object = imageMap[id];
if (!loaderOrBitmapData) {
debug('unloadImage: image ' + id + ' does not exist');
return;
}
if (loaderOrBitmapData is Loader) {
var loader:Loader = loaderOrBitmapData as Loader;
// Calling close() after the load is complete seems to cause an error,
// so first check that we are still loading.
if (loader.contentLoaderInfo.bytesTotal != 0 && loader.contentLoaderInfo.bytesLoaded != loader.contentLoaderInfo.bytesTotal) {
loader.close();
}
}
delete imageMap[id];
}
public function createTexture(imageId:Number, width:Number, height:Number, padTop:Number, padBottom:Number, padLeft:Number, padRight:Number):Number {
var image:BitmapData = imageMap[imageId];
var i:Number;
var point:Point = new Point();
var rect:Rectangle = new Rectangle();
// Create new bitmap for texture.
var bitmap:BitmapData = new BitmapData(width + padLeft + padRight, height + padTop + padBottom, true, 0x00FFFFFF);
// Resize source image if the texture has a different size.
// TODO: it would be better to call draw() directly on the final bitmap
// with both a matrix and a clippingRect parameter; this would both be
// faster and allocate less memory. However, the clippingRect parameter
// for the draw() method doesn't seem to work as documented.
var scaled:BitmapData;
if (width !== image.width || height !== image.height) {
scaled = new BitmapData(width, height, true, 0x00FFFFFF);
var mat:Matrix = new Matrix(width / image.width, 0, 0, height / image.height, 0, 0);
scaled.draw(image, mat, null, null, null, true);
} else {
scaled = image;
}
// Draw image into texture.
rect.x = 0;
rect.y = 0;
rect.width = width;
rect.height = height;
point.x = padLeft;
point.y = padTop;
bitmap.copyPixels(scaled, rect, point);
// Draw top padding.
for (i = 0; i <= padTop; i++) {
rect.x = padLeft;
rect.y = padTop;
rect.width = width;
rect.height = 1;
point.x = padLeft;
point.y = i;
bitmap.copyPixels(bitmap, rect, point);
}
// Draw left padding.
for (i = 0; i <= padLeft; i++) {
rect.x = padLeft;
rect.y = padTop;
rect.width = 1;
rect.height = height;
point.x = i;
point.y = padTop;
bitmap.copyPixels(bitmap, rect, point);
}
// Draw bottom padding.
for (i = 0; i <= padBottom; i++) {
rect.x = padLeft;
rect.y = padTop + height - 1;
rect.width = width;
rect.height = 1;
point.x = padLeft;
point.y = padTop + height + i;
bitmap.copyPixels(bitmap, rect, point);
}
// Draw right padding.
for (i = 0; i <= padRight; i++) {
rect.x = padLeft + width - 1;
rect.y = padTop;
rect.width = 1;
rect.height = height;
point.x = padLeft + width + i;
point.y = padTop;
bitmap.copyPixels(bitmap, rect, point);
}
var texture:Sprite = new Sprite();
texture.addChild(new Bitmap(bitmap));
var textureId:Number = imageId;
textureMap[textureId] = texture;
return textureId;
}
public function destroyTexture(id:Number):void {
var texture:Sprite = textureMap[id];
if (!texture) {
debug('destroyTexture: texture ' + id + ' does not exist');
return;
}
if (texture.parent) {
texture.parent.removeChild(texture);
}
delete textureMap[id];
}
}
}
|
Remove unneeded imports from the Flash renderer.
|
Remove unneeded imports from the Flash renderer.
|
ActionScript
|
apache-2.0
|
google/marzipano,google/marzipano,google/marzipano
|
d2e85cb2b792a72d87a215871dbb0b90e6666df3
|
ageb/src/ageb/modules/avatar/timelineClasses/TimelinePanel.as
|
ageb/src/ageb/modules/avatar/timelineClasses/TimelinePanel.as
|
package ageb.modules.avatar.timelineClasses
{
import flash.events.Event;
import flash.events.MouseEvent;
import spark.events.IndexChangeEvent;
import age.assets.ObjectInfo;
import ageb.ageb_internal;
import ageb.modules.ae.ActionInfoEditable;
import ageb.modules.ae.FrameInfoEditable;
import ageb.modules.avatar.op.AddFrameLayer;
import ageb.modules.avatar.op.ChangeActionFPS;
import ageb.modules.avatar.op.RemoveFrameLayer;
import ageb.modules.avatar.op.SelectAction;
import ageb.modules.document.Document;
import nt.lib.util.assert;
/**
* 时间轴面板
* @author zhanghaocong
*
*/
public class TimelinePanel extends TimelinePanelTemplate
{
/**
* 创建一个新的 TimelinePanel
*
*/
public function TimelinePanel()
{
super();
}
/**
* @inheritDoc
*
*/
override protected function createChildren():void
{
super.createChildren();
framesGrid.onVerticalScrollPositionChange.add(framesGrid_onVerticalScrollPositionChange);
actionsField.addEventListener(IndexChangeEvent.CHANGE, actionsField_onChange);
actionsField.addEventListener(IndexChangeEvent.CHANGING, actionsField_onChanging);
nextFrameButton.addEventListener(MouseEvent.CLICK, frameButton_onClick);
playPauseButton.addEventListener(MouseEvent.CLICK, frameButton_onClick);
prevFrameButton.addEventListener(MouseEvent.CLICK, frameButton_onClick);
currentFrameField.addEventListener(Event.CHANGE, currentFrameField_onClick);
directionButtons.addEventListener(IndexChangeEvent.CHANGE, directionButtons_onChange);
layersField.addEventListener(MouseEvent.CLICK, layersField_onClick);
layersField.onMouseWheel.add(layersField_onMouseWheel);
fpsField.addEventListener(Event.CHANGE, fpsField_onChange);
addLayerButton.addEventListener(MouseEvent.CLICK, addLayerButton_onClick);
removeLayerButton.addEventListener(MouseEvent.CLICK, removeLayerButton_onClick);
}
private function layersField_onMouseWheel():void
{
framesGrid.grid.verticalScrollPosition = layersField.scroller.viewport.verticalScrollPosition;
}
/**
* @private
* @param event
*
*/
protected function fpsField_onChange(event:Event):void
{
new ChangeActionFPS(doc, fpsField.value).execute();
}
/**
* 点击列表任意项等于选择中该图层所有帧
* @param event
*
*/
protected function layersField_onClick(event:MouseEvent):void
{
var frames:Vector.<FrameInfoEditable> = new Vector.<FrameInfoEditable>;
if (layersField.selectedIndex != -1)
{
for each (var rowIndex:int in layersField.selectedIndices)
{
frames = frames.concat(Vector.<FrameInfoEditable>(actionInfo.layers[rowIndex].frames));
}
}
actionInfo.ageb_internal::setSelectedFrames(frames, this);
}
/**
* 更换方向
* @param event
*
*/
protected function directionButtons_onChange(event:IndexChangeEvent):void
{
objectInfo.direction = directionButtons.selectedItem.value;
}
/**
* 切换到指定帧
* @param event
*
*/
protected function currentFrameField_onClick(event:Event):void
{
objectInfo.gotoAndStop(currentFrameField.value);
}
/**
* 回放控制
* @param event
*
*/
protected function frameButton_onClick(event:MouseEvent):void
{
switch (event.currentTarget)
{
case playPauseButton:
{
if (objectInfo.isPlaying)
{
objectInfo.pause();
}
else
{
objectInfo.play();
}
break;
}
case nextFrameButton:
{
objectInfo.nextFrame();
break;
}
case prevFrameButton:
{
objectInfo.prevFrame();
break;
}
default:
{
throw new Error("不该进这里");
break;
}
}
}
/**
* @private
* @param event
*
*/
protected function actionsField_onChanging(event:IndexChangeEvent):void
{
// 拦截不存在的动作
if (!(actionsField.selectedItem is ActionInfoEditable))
{
event.preventDefault();
}
}
/**
* 更换渲染的动作
* @param event
*
*/
protected function actionsField_onChange(event:IndexChangeEvent):void
{
new SelectAction(doc, ActionInfoEditable(actionsField.selectedItem).name).execute();
}
/**
* 添加图层
* @param event
*
*/
protected function addLayerButton_onClick(event:MouseEvent):void
{
new AddFrameLayer(doc).execute();
}
/**
* 删除图层
* @param event
*
*/
protected function removeLayerButton_onClick(event:MouseEvent):void
{
new RemoveFrameLayer(doc, layersField.selectedIndices).execute();
}
/**
* 返回 objectInfo.currentFrame
* @return
*
*/
[Inline]
final protected function get currentFrame():int
{
return objectInfo.currentFrame;
}
/**
* @inheritDoc
* @param value
*
*/
override public function set doc(value:Document):void
{
if (avatarDoc)
{
objectInfo.onCurrentFrameChange.remove(onCurrentFrameChange);
// 动作列表
actionsField.dataProvider = null;
// 帧网格
framesGrid.avatarDoc = null;
// 当前动作
actionInfo = null;
}
super.doc = value;
if (avatarDoc)
{
assert(avatarDoc.avatar == objectInfo.avatarInfo);
actionsField.dataProvider = avatarDoc.avatar.actionsArrayList;
framesGrid.avatarDoc = avatarDoc;
objectInfo.onCurrentFrameChange.add(onCurrentFrameChange);
onCurrentFrameChange(objectInfo);
}
}
/**
* @inheritDoc
* @param value
*
*/
override public function set actionInfo(value:ActionInfoEditable):void
{
// 重设
if (actionInfo)
{
// 更新选中项
actionsField.selectedItem = null;
// 当前帧
currentFrameField.maximum = 0;
// FPS
fpsField.value = 0;
// 图层列表
layersField.dataProvider = null;
// 一些事件
actionInfo.onSelectedFramesChange.remove(onSelectedFramesChange);
actionInfo.onFPSChange.remove(onFPSChange);
}
super.actionInfo = value;
if (actionInfo)
{
// 更新选中项
actionsField.selectedItem = actionInfo;
// 当前帧
currentFrameField.maximum = actionInfo.numFrames - 1; // currentFrame 从 0 开始
// 图层列表
layersField.dataProvider = actionInfo.layersVectorList;
// 一些事件
actionInfo.onSelectedFramesChange.add(onSelectedFramesChange);
onSelectedFramesChange(null);
actionInfo.onFPSChange.add(onFPSChange);
onFPSChange();
}
}
/**
* @private
*
*/
private function onFPSChange():void
{
fpsField.value = actionInfo.fps;
}
/**
* @private
*
*/
private function onSelectedFramesChange(trigger:Object):void
{
if (trigger == this)
{
return;
}
const frames:Vector.<FrameInfoEditable> = actionInfo.selectedFrames;
var selectedIndices:Vector.<int> = new Vector.<int>;
for (var i:int = 0, n:int = frames.length; i < n; i++)
{
const layerIndex:int = frames[i].layerIndex;
if (selectedIndices.indexOf(layerIndex) == -1)
{
selectedIndices.push(layerIndex);
}
}
layersField.selectedIndices = selectedIndices;
}
/**
* 此为同步滚动条位置
* @param value
*
*/
private function framesGrid_onVerticalScrollPositionChange(value:Number):void
{
layersField.dataGroup.verticalScrollPosition = value;
}
/**
* 更新当前播放的帧
* @param target
*
*/
private function onCurrentFrameChange(target:ObjectInfo):void
{
currentFrameField.value = currentFrame;
currentTimeField.text = (currentFrame * actionInfo.defautFrameDuration).toFixed(3) + "s";
}
}
}
|
package ageb.modules.avatar.timelineClasses
{
import flash.events.Event;
import flash.events.MouseEvent;
import spark.events.IndexChangeEvent;
import age.assets.ObjectInfo;
import ageb.ageb_internal;
import ageb.modules.ae.ActionInfoEditable;
import ageb.modules.ae.FrameInfoEditable;
import ageb.modules.avatar.op.AddFrameLayer;
import ageb.modules.avatar.op.ChangeActionFPS;
import ageb.modules.avatar.op.RemoveFrameLayer;
import ageb.modules.avatar.op.SelectAction;
import ageb.modules.document.Document;
import nt.lib.util.assert;
/**
* 时间轴面板
* @author zhanghaocong
*
*/
public class TimelinePanel extends TimelinePanelTemplate
{
/**
* 创建一个新的 TimelinePanel
*
*/
public function TimelinePanel()
{
super();
}
/**
* @inheritDoc
*
*/
override protected function createChildren():void
{
super.createChildren();
framesGrid.onVerticalScrollPositionChange.add(framesGrid_onVerticalScrollPositionChange);
actionsField.addEventListener(IndexChangeEvent.CHANGE, actionsField_onChange);
actionsField.addEventListener(IndexChangeEvent.CHANGING, actionsField_onChanging);
nextFrameButton.addEventListener(MouseEvent.CLICK, frameButton_onClick);
playPauseButton.addEventListener(MouseEvent.CLICK, frameButton_onClick);
prevFrameButton.addEventListener(MouseEvent.CLICK, frameButton_onClick);
currentFrameField.addEventListener(Event.CHANGE, currentFrameField_onClick);
directionButtons.addEventListener(IndexChangeEvent.CHANGE, directionButtons_onChange);
layersField.addEventListener(MouseEvent.CLICK, layersField_onClick);
layersField.onMouseWheel.add(layersField_onMouseWheel);
fpsField.addEventListener(Event.CHANGE, fpsField_onChange);
addLayerButton.addEventListener(MouseEvent.CLICK, addLayerButton_onClick);
removeLayerButton.addEventListener(MouseEvent.CLICK, removeLayerButton_onClick);
}
private function layersField_onMouseWheel():void
{
framesGrid.grid.verticalScrollPosition = layersField.scroller.viewport.verticalScrollPosition;
}
/**
* @private
* @param event
*
*/
protected function fpsField_onChange(event:Event):void
{
new ChangeActionFPS(doc, fpsField.value).execute();
}
/**
* 点击列表任意项等于选择中该图层所有帧
* @param event
*
*/
protected function layersField_onClick(event:MouseEvent):void
{
var frames:Vector.<FrameInfoEditable> = new Vector.<FrameInfoEditable>;
if (layersField.selectedIndex != -1)
{
for each (var rowIndex:int in layersField.selectedIndices)
{
frames = frames.concat(Vector.<FrameInfoEditable>(actionInfo.layers[rowIndex].frames));
}
}
actionInfo.ageb_internal::setSelectedFrames(frames, this);
}
/**
* 更换方向
* @param event
*
*/
protected function directionButtons_onChange(event:IndexChangeEvent):void
{
objectInfo.direction = directionButtons.selectedItem.value;
}
/**
* 切换到指定帧
* @param event
*
*/
protected function currentFrameField_onClick(event:Event):void
{
objectInfo.gotoAndStop(currentFrameField.value);
}
/**
* 回放控制
* @param event
*
*/
protected function frameButton_onClick(event:MouseEvent):void
{
switch (event.currentTarget)
{
case playPauseButton:
{
if (objectInfo.isPlaying)
{
objectInfo.pause();
}
else
{
objectInfo.play();
}
break;
}
case nextFrameButton:
{
objectInfo.nextFrame();
break;
}
case prevFrameButton:
{
objectInfo.prevFrame();
break;
}
default:
{
throw new Error("不该进这里");
break;
}
}
}
/**
* @private
* @param event
*
*/
protected function actionsField_onChanging(event:IndexChangeEvent):void
{
// 拦截不存在的动作
if (!(actionsField.selectedItem is ActionInfoEditable))
{
event.preventDefault();
}
}
/**
* 更换渲染的动作
* @param event
*
*/
protected function actionsField_onChange(event:IndexChangeEvent):void
{
callLater(new SelectAction(doc, ActionInfoEditable(actionsField.selectedItem).name).execute);
}
/**
* 添加图层
* @param event
*
*/
protected function addLayerButton_onClick(event:MouseEvent):void
{
new AddFrameLayer(doc).execute();
}
/**
* 删除图层
* @param event
*
*/
protected function removeLayerButton_onClick(event:MouseEvent):void
{
new RemoveFrameLayer(doc, layersField.selectedIndices).execute();
}
/**
* 返回 objectInfo.currentFrame
* @return
*
*/
[Inline]
final protected function get currentFrame():int
{
return objectInfo.currentFrame;
}
/**
* @inheritDoc
* @param value
*
*/
override public function set doc(value:Document):void
{
if (avatarDoc)
{
objectInfo.onCurrentFrameChange.remove(onCurrentFrameChange);
// 动作列表
actionsField.dataProvider = null;
// 帧网格
framesGrid.avatarDoc = null;
// 当前动作
actionInfo = null;
}
super.doc = value;
if (avatarDoc)
{
assert(avatarDoc.avatar == objectInfo.avatarInfo);
actionsField.dataProvider = avatarDoc.avatar.actionsArrayList;
framesGrid.avatarDoc = avatarDoc;
objectInfo.onCurrentFrameChange.add(onCurrentFrameChange);
onCurrentFrameChange(objectInfo);
}
}
/**
* @inheritDoc
* @param value
*
*/
override public function set actionInfo(value:ActionInfoEditable):void
{
// 重设
if (actionInfo)
{
// 更新选中项
actionsField.selectedItem = null;
// 当前帧
currentFrameField.maximum = 0;
// FPS
fpsField.value = 0;
// 图层列表
layersField.dataProvider = null;
// 一些事件
actionInfo.onSelectedFramesChange.remove(onSelectedFramesChange);
actionInfo.onFPSChange.remove(onFPSChange);
}
super.actionInfo = value;
if (actionInfo)
{
// 更新选中项
actionsField.selectedItem = actionInfo;
// 当前帧
currentFrameField.maximum = actionInfo.numFrames - 1; // currentFrame 从 0 开始
// 图层列表
layersField.dataProvider = actionInfo.layersVectorList;
// 一些事件
actionInfo.onSelectedFramesChange.add(onSelectedFramesChange);
onSelectedFramesChange(null);
actionInfo.onFPSChange.add(onFPSChange);
onFPSChange();
}
}
/**
* @private
*
*/
private function onFPSChange():void
{
fpsField.value = actionInfo.fps;
}
/**
* @private
*
*/
private function onSelectedFramesChange(trigger:Object):void
{
if (trigger == this)
{
return;
}
const frames:Vector.<FrameInfoEditable> = actionInfo.selectedFrames;
var selectedIndices:Vector.<int> = new Vector.<int>;
for (var i:int = 0, n:int = frames.length; i < n; i++)
{
const layerIndex:int = frames[i].layerIndex;
if (selectedIndices.indexOf(layerIndex) == -1)
{
selectedIndices.push(layerIndex);
}
}
layersField.selectedIndices = selectedIndices;
}
/**
* 此为同步滚动条位置
* @param value
*
*/
private function framesGrid_onVerticalScrollPositionChange(value:Number):void
{
layersField.dataGroup.verticalScrollPosition = value;
}
/**
* 更新当前播放的帧
* @param target
*
*/
private function onCurrentFrameChange(target:ObjectInfo):void
{
currentFrameField.value = currentFrame;
currentTimeField.text = (currentFrame * actionInfo.defautFrameDuration).toFixed(3) + "s";
}
}
}
|
修复了在动作列表 Dropdown 按 ↑↓ 键翻阅动作时,列表内容切换不正确的 BUG
|
修复了在动作列表 Dropdown 按 ↑↓ 键翻阅动作时,列表内容切换不正确的 BUG
|
ActionScript
|
mit
|
nexttouches/age_client
|
c2c263143586459a99bc1ef071975a4d22bb213c
|
src/as/com/threerings/stage/client/StageSceneBlock.as
|
src/as/com/threerings/stage/client/StageSceneBlock.as
|
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.stage.client {
import flash.display.DisplayObject;
import com.threerings.miso.client.MisoScenePanel;
import com.threerings.miso.util.MisoContext;
import com.threerings.miso.util.MisoSceneMetrics;
import com.threerings.miso.client.SceneBlock;
import com.threerings.miso.data.MisoSceneModel;
import com.threerings.util.Iterator;
import com.threerings.util.MathUtil;
import com.threerings.whirled.spot.data.Portal;
import com.threerings.whirled.spot.data.SpotScene;
import com.threerings.whirled.spot.data.SpotSceneModel;
import com.threerings.stage.data.StageLocation;
import as3isolib.display.IsoSprite;
import as3isolib.display.IsoView;
import as3isolib.display.scene.IsoScene;
public class StageSceneBlock extends SceneBlock
{
public function StageSceneBlock (key :int, objScene :IsoScene, portalScene :IsoScene,
isoView :IsoView, metrics :MisoSceneMetrics, spotScene :SpotScene)
{
super(key, objScene, isoView, metrics);
_spotScene = spotScene;
_portalScene = portalScene;
}
override public function resolve (ctx :MisoContext, model :MisoSceneModel, panel :MisoScenePanel,
completeCallback :Function) :void
{
_tryingPortals = true;
super.resolve(ctx, model, panel, completeCallback);
var bx :int = getBlockX(_key);
var by :int = getBlockY(_key);
var iter :Iterator = _spotScene.getPortals();
while (iter.hasNext()) {
var portal :Portal = Portal(iter.next());
var x :int = fullToTile(StageLocation(portal.loc).x);
var y :int = fullToTile(StageLocation(portal.loc).y);
if (x < bx || x > bx + BLOCK_SIZE || y < by || y > by + BLOCK_SIZE) {
continue;
}
trace("MST loc: " + StageLocation(portal.loc).x + "," + StageLocation(portal.loc).y);
var fineX :int = StageLocation(portal.loc).x - FULL_TILE_FACTOR * x;
var fineY :int = StageLocation(portal.loc).y - FULL_TILE_FACTOR * y;
trace("MST part: " + fineX + "," + fineY);
// Grab the portal image, and center it.
var portalSprite :IsoSprite = new IsoSprite();
var img :DisplayObject =
StageScenePanel(panel).getPortalImage(StageLocation(portal.loc).orient);
img.x = -img.width/2 + int(_metrics.finehwid * (fineX - fineY));
img.y = -img.height/2 + int(_metrics.finehhei * (fineX + fineY));
portalSprite.sprites = [img];
portalSprite.setSize(1, 1, 1);
trace("MST Adding portal: " + x + "," + y);
portalSprite.moveTo(x, y, 0);
if (_portSprites == null) {
_portSprites = [];
}
_portSprites.push(portalSprite);
}
_tryingPortals = false;
maybeLoaded();
}
override public function render () :void
{
super.render();
for each (var sprite :IsoSprite in _portSprites) {
_portalScene.addChild(sprite);
}
}
override public function release () :void
{
super.release();
for each (var sprite :IsoSprite in _portSprites) {
_portalScene.removeChild(sprite);
}
}
override protected function maybeLoaded () :void
{
// If we're still working on getting our portals setup, skip it...
if (!_tryingPortals) {
super.maybeLoaded();
}
}
protected function fullToTile (fullCoord :int) :int
{
return MathUtil.floorDiv(fullCoord, FULL_TILE_FACTOR);
}
protected static const FULL_TILE_FACTOR :int = 100;
protected var _spotScene :SpotScene;
protected var _tryingPortals :Boolean;
protected var _portalScene :IsoScene;
protected var _portSprites :Array;
}
}
|
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.stage.client {
import flash.display.DisplayObject;
import com.threerings.miso.client.MisoScenePanel;
import com.threerings.miso.util.MisoContext;
import com.threerings.miso.util.MisoSceneMetrics;
import com.threerings.miso.client.SceneBlock;
import com.threerings.miso.data.MisoSceneModel;
import com.threerings.util.Iterator;
import com.threerings.util.MathUtil;
import com.threerings.whirled.spot.data.Portal;
import com.threerings.whirled.spot.data.SpotScene;
import com.threerings.whirled.spot.data.SpotSceneModel;
import com.threerings.stage.data.StageLocation;
import as3isolib.display.IsoSprite;
import as3isolib.display.IsoView;
import as3isolib.display.scene.IsoScene;
public class StageSceneBlock extends SceneBlock
{
public function StageSceneBlock (key :int, objScene :IsoScene, portalScene :IsoScene,
isoView :IsoView, metrics :MisoSceneMetrics, spotScene :SpotScene)
{
super(key, objScene, isoView, metrics);
_spotScene = spotScene;
_portalScene = portalScene;
}
override public function resolve (ctx :MisoContext, model :MisoSceneModel, panel :MisoScenePanel,
completeCallback :Function) :void
{
_tryingPortals = true;
super.resolve(ctx, model, panel, completeCallback);
var bx :int = getBlockX(_key);
var by :int = getBlockY(_key);
var iter :Iterator = _spotScene.getPortals();
while (iter.hasNext()) {
var portal :Portal = Portal(iter.next());
var x :int = fullToTile(StageLocation(portal.loc).x);
var y :int = fullToTile(StageLocation(portal.loc).y);
if (x < bx || x > bx + BLOCK_SIZE || y < by || y > by + BLOCK_SIZE) {
continue;
}
var fineX :int = StageLocation(portal.loc).x - FULL_TILE_FACTOR * x;
var fineY :int = StageLocation(portal.loc).y - FULL_TILE_FACTOR * y;
// Grab the portal image, and center it.
var portalSprite :IsoSprite = new IsoSprite();
var img :DisplayObject =
StageScenePanel(panel).getPortalImage(StageLocation(portal.loc).orient);
img.x = -img.width/2 + int(_metrics.finehwid * (fineX - fineY));
img.y = -img.height/2 + int(_metrics.finehhei * (fineX + fineY));
portalSprite.sprites = [img];
portalSprite.setSize(1, 1, 1);
portalSprite.moveTo(x, y, 0);
if (_portSprites == null) {
_portSprites = [];
}
_portSprites.push(portalSprite);
}
_tryingPortals = false;
maybeLoaded();
}
override public function render () :void
{
super.render();
for each (var sprite :IsoSprite in _portSprites) {
_portalScene.addChild(sprite);
}
}
override public function release () :void
{
super.release();
for each (var sprite :IsoSprite in _portSprites) {
_portalScene.removeChild(sprite);
}
}
override protected function maybeLoaded () :void
{
// If we're still working on getting our portals setup, skip it...
if (!_tryingPortals) {
super.maybeLoaded();
}
}
protected function fullToTile (fullCoord :int) :int
{
return MathUtil.floorDiv(fullCoord, FULL_TILE_FACTOR);
}
protected static const FULL_TILE_FACTOR :int = 100;
protected var _spotScene :SpotScene;
protected var _tryingPortals :Boolean;
protected var _portalScene :IsoScene;
protected var _portSprites :Array;
}
}
|
Remove some debug printouts.
|
Remove some debug printouts.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@941 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
c21f8ad735858b1de644b80c38f14af33823aac2
|
src/as/com/threerings/presents/client/Client.as
|
src/as/com/threerings/presents/client/Client.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.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.Timer;
import com.threerings.util.Log;
import com.threerings.util.MethodQueue;
import com.threerings.util.Throttle;
import com.threerings.presents.client.InvocationService_ConfirmListener;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.data.InvocationCodes;
import com.threerings.presents.data.TimeBaseMarshaller;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.net.AuthResponseData;
import com.threerings.presents.net.BootstrapData;
import com.threerings.presents.net.Credentials;
import com.threerings.presents.net.PingRequest;
import com.threerings.presents.net.PongResponse;
import com.threerings.presents.net.ThrottleUpdatedMessage;
public class Client extends EventDispatcher
{
/** The default port on which the server listens for client connections. */
public static const DEFAULT_SERVER_PORTS :Array = [ 47624 ];
/** Our default maximum outgoing message rate in messages per second. */
public static const DEFAULT_MSGS_PER_SECOND :int = 10;
private static const log :Log = Log.getLog(Client);
// statically reference classes we require
TimeBaseMarshaller;
public function Client (creds :Credentials)
{
_creds = creds;
}
/**
* Registers the supplied observer with this client. While registered the observer will receive
* notifications of state changes within the client. The function will refuse to register an
* already registered observer.
*
* @see ClientObserver
* @see SessionObserver
*/
public function addClientObserver (observer :SessionObserver) :void
{
addEventListener(ClientEvent.CLIENT_WILL_LOGON, observer.clientWillLogon);
addEventListener(ClientEvent.CLIENT_DID_LOGON, observer.clientDidLogon);
addEventListener(ClientEvent.CLIENT_OBJECT_CHANGED, observer.clientObjectDidChange);
addEventListener(ClientEvent.CLIENT_DID_LOGOFF, observer.clientDidLogoff);
if (observer is ClientObserver) {
var cliObs :ClientObserver = (observer as ClientObserver);
addEventListener(ClientEvent.CLIENT_FAILED_TO_LOGON, cliObs.clientFailedToLogon);
addEventListener(ClientEvent.CLIENT_CONNECTION_FAILED, cliObs.clientConnectionFailed);
addEventListener(ClientEvent.CLIENT_WILL_LOGOFF, cliObs.clientWillLogoff);
addEventListener(ClientEvent.CLIENT_DID_CLEAR, cliObs.clientDidClear);
}
}
/**
* Unregisters the supplied observer. Upon return of this function, the observer will no longer
* receive notifications of state changes within the client.
*/
public function removeClientObserver (observer :SessionObserver) :void
{
removeEventListener(ClientEvent.CLIENT_WILL_LOGON, observer.clientWillLogon);
removeEventListener(ClientEvent.CLIENT_DID_LOGON, observer.clientDidLogon);
removeEventListener(ClientEvent.CLIENT_OBJECT_CHANGED, observer.clientObjectDidChange);
removeEventListener(ClientEvent.CLIENT_DID_LOGOFF, observer.clientDidLogoff);
if (observer is ClientObserver) {
var cliObs :ClientObserver = (observer as ClientObserver);
removeEventListener(ClientEvent.CLIENT_FAILED_TO_LOGON, cliObs.clientFailedToLogon);
removeEventListener(
ClientEvent.CLIENT_CONNECTION_FAILED, cliObs.clientConnectionFailed);
removeEventListener(ClientEvent.CLIENT_WILL_LOGOFF, cliObs.clientWillLogoff);
removeEventListener(ClientEvent.CLIENT_DID_CLEAR, cliObs.clientDidClear);
}
}
public function setServer (hostname :String, ports :Array) :void
{
_hostname = hostname;
_ports = ports;
}
public function callLater (fn :Function, args :Array = null) :void
{
MethodQueue.callLater(fn, args);
}
public function getHostname () :String
{
return _hostname;
}
/**
* Returns the ports on which this client is configured to connect.
*/
public function getPorts () :Array
{
return _ports;
}
public function getCredentials () :Credentials
{
return _creds;
}
public function setCredentials (creds :Credentials) :void
{
_creds = creds;
}
public function getVersion () :String
{
return _version;
}
public function setVersion (version :String) :void
{
_version = version;
}
public function getAuthResponseData () :AuthResponseData
{
return _authData;
}
public function setAuthResponseData (data :AuthResponseData) :void
{
_authData = data;
}
public function getDObjectManager () :DObjectManager
{
return _omgr;
}
public function getClientOid () :int
{
return _cloid;
}
public function getClientObject () :ClientObject
{
return _clobj;
}
public function getInvocationDirector () :InvocationDirector
{
return _invdir;
}
/**
* Returns the set of bootstrap service groups needed by this client.
*/
public function getBootGroups () :Array
{
return _bootGroups;
}
/**
* Marks this client as interested in the specified bootstrap services group. Any services
* registered as bootstrap services with the supplied group name will be included in this
* clients bootstrap services set. This must be called before {@link #logon}.
*/
public function addServiceGroup (group :String) :void
{
if (isLoggedOn()) {
throw new Error("Services must be registered prior to logon().");
}
if (_bootGroups.indexOf(group) == -1) {
_bootGroups.push(group);
}
}
public function getService (clazz :Class) :InvocationService
{
if (_bstrap != null) {
for each (var isvc :InvocationService in _bstrap.services) {
if (isvc is clazz) {
return isvc;
}
}
}
return null;
}
public function requireService (clazz :Class) :InvocationService
{
var isvc :InvocationService = getService(clazz);
if (isvc == null) {
throw new Error(clazz + " isn't available. I can't bear to go on.");
}
return isvc;
}
public function getBootstrapData () :BootstrapData
{
return _bstrap;
}
public function isLoggedOn () :Boolean
{
return (_clobj != null);
}
/**
* Requests that this client connect and logon to the server with which it was previously
* configured.
*
* @return false if we're already logged on.
*/
public function logon () :Boolean
{
// if we have a communicator, we're already logged on
if (_comm != null) {
return false;
}
// let our observers know that we're logging on (this will give directors a chance to
// register invocation service groups)
notifyObservers(ClientEvent.CLIENT_WILL_LOGON);
// we need to wait for the CLIENT_WILL_LOGON to have been dispatched before we actually
// tell the communicator to logon, so we run this through the callLater pipeline
_comm = new Communicator(this);
callLater(_comm.logon);
return true;
}
/**
* Transitions a logged on client from its current server to the specified new server.
* Currently this simply logs the client off of its current server (if it is logged on) and
* logs it onto the new server, but in the future we may aim to do something fancier.
*
* <p> If we fail to connect to the new server, the client <em>will not</em> be automatically
* reconnected to the old server. It will be in a logged off state. However, it will be
* reconfigured with the hostname and ports of the old server so that the caller can notify the
* user of the failure and then simply call {@link #logon} to attempt to reconnect to the old
* server.
*
* @param observer an observer that will be notified when we have successfully logged onto the
* other server, or if the move failed.
*/
public function moveToServer (hostname :String, ports :Array,
obs :InvocationService_ConfirmListener) :void
{
// the server switcher will take care of everything for us
_switcher = new ServerSwitcher(this, hostname, ports, obs);
_switcher.switchServers();
}
/**
* Requests that the client log off of the server to which it is connected.
*
* @param abortable if true, the client will call clientWillDisconnect on allthe client
* observers and abort the logoff process if any of them return false. If false,
* clientWillDisconnect will not be called.
*
* @return true if the logoff succeeded, false if it failed due to a disagreeable observer.
*/
public function logoff (abortable :Boolean) :Boolean
{
if (_comm == null) {
log.warning("Ignoring request to log off: not logged on.");
return true;
}
// if this is an externally initiated logoff request, clear our active session status
if (_switcher == null) {
_activeSession = false;
}
// if the request is abortable, let's run it past the observers. if any of them call
// preventDefault() then the logoff will be cancelled
if (abortable && !notifyObservers(ClientEvent.CLIENT_WILL_LOGOFF)) {
_activeSession = true; // restore our active session status
return false;
}
if (_tickInterval != null) {
_tickInterval.stop();
_tickInterval = null;
}
_comm.logoff();
return true;
}
public function gotBootstrap (data :BootstrapData, omgr :DObjectManager) :void
{
// log.debug("Got bootstrap " + data + ".");
_bstrap = data;
_omgr = omgr;
_cloid = data.clientOid;
_invdir.init(omgr, _cloid, this);
// log.debug("TimeBaseService: " + requireService(TimeBaseService));
}
/**
* Called every five seconds; ensures that we ping the server if we haven't communicated in a
* long while.
*/
protected function tick (event :TimerEvent) :void
{
if (_comm == null) {
return;
}
var now :uint = flash.utils.getTimer();
if (now - _comm.getLastWrite() > PingRequest.PING_INTERVAL) {
_comm.postMessage(new PingRequest());
}
}
/**
* Called by the {@link Communicator} if it is experiencing trouble logging on but is still
* trying fallback strategies.
*/
internal function reportLogonTribulations (cause :LogonError) :void
{
notifyObservers(ClientEvent.CLIENT_FAILED_TO_LOGON, cause);
}
/**
* Called by the invocation director when it successfully subscribes to the client object
* immediately following logon.
*/
public function gotClientObject (clobj :ClientObject) :void
{
// keep our client object around
_clobj = clobj;
// and start up our tick interval (which will send pings when necessary)
if (_tickInterval == null) {
_tickInterval = new Timer(5000);
_tickInterval.addEventListener(TimerEvent.TIMER, tick);
_tickInterval.start();
}
notifyObservers(ClientEvent.CLIENT_DID_LOGON);
// now that we've logged on at least once, we're in the middle of an active session and
// will remain so until we receive an externally initiated logoff request
_activeSession = true;
}
/**
* Called by the invocation director if it fails to subscribe to the client object after logon.
*/
public function getClientObjectFailed (cause :Error) :void
{
notifyObservers(ClientEvent.CLIENT_FAILED_TO_LOGON, cause);
}
/**
* Called by the invocation director when it discovers that the client object has changed.
*/
protected function clientObjectDidChange (clobj :ClientObject) :void
{
_clobj = clobj;
_cloid = clobj.getOid();
notifyObservers(ClientEvent.CLIENT_OBJECT_CHANGED);
}
/**
* Convenience method to dispatch a client event to any listeners and return the result of
* dispatchEvent.
*/
public function notifyObservers (evtCode :String, cause :Error = null) :Boolean
{
return dispatchEvent(new ClientEvent(evtCode, this, _activeSession, cause));
}
/**
* Called by the omgr when we receive a pong packet.
*/
internal function gotPong (pong :PongResponse) :void
{
// TODO: compute time delta?
}
internal function setOutgoingMessageThrottle (messagesPerSec :int) :void
{
_comm.postMessage(new ThrottleUpdatedMessage(messagesPerSec));
}
internal function finalizeOutgoingMessageThrottle (messagesPerSec :int) :void
{
// when the throttle update message goes out to the server
_outThrottle.reinit(messagesPerSec, 1000);
log.info("Updated outgoing throttle", "messagesPerSec", messagesPerSec);
}
internal function getOutgoingMessageThrottle () :Throttle
{
return _outThrottle;
}
internal function cleanup (logonError :Error) :void
{
// clear out our references
_comm = null;
_omgr = null;
_clobj = null;
_cloid = -1;
// and let our invocation director know we're logged off
_invdir.cleanup();
// if this was due to a logon error, we can notify our listeners now that we're cleaned up:
// they may want to retry logon on another port, or something
if (logonError != null) {
notifyObservers(ClientEvent.CLIENT_FAILED_TO_LOGON, logonError);
} else {
notifyObservers(ClientEvent.CLIENT_DID_CLEAR, null);
}
// clear out any server switcher reference
_switcher = null;
}
/** The credentials we used to authenticate with the server. */
protected var _creds :Credentials;
/** The version string reported to the server at auth time. */
protected var _version :String = "";
/** The distributed object manager we're using during this session. */
protected var _omgr :DObjectManager;
/** The data associated with our authentication response. */
protected var _authData :AuthResponseData;
/** Our client distributed object id. */
protected var _cloid :int = -1;
/** Our client distributed object. */
protected var _clobj :ClientObject;
/** The game server host. */
protected var _hostname :String;
/** The port on which we connect to the game server. */
protected var _ports :Array; /* of int */
/** The entity that manages our network communications. */
protected var _comm :Communicator;
/** Our outgoing message throttle. */
protected var _outThrottle :Throttle = new Throttle(DEFAULT_MSGS_PER_SECOND, 1000);
/** The set of bootstrap service groups this client cares about. */
protected var _bootGroups :Array = new Array(InvocationCodes.GLOBAL_GROUP);
/** General startup information provided by the server. */
protected var _bstrap :BootstrapData;
/** Manages invocation services. */
protected var _invdir :InvocationDirector = new InvocationDirector();
/** Ticks. */
protected var _tickInterval :Timer;
/** This flag is used to distinguish our *first* willLogon/didLogon and a caller-initiated
* willLogoff/didLogoff from similar events generated during server switches. Thus it is true
* for most of a normal client session. */
protected var _activeSession :Boolean;
/** Used to temporarily track our server switcher so that we can tell when we're logging off
* whether or not we're switching servers or actually ending our session. */
protected var _switcher :ServerSwitcher;
}
}
|
//
// $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.events.EventDispatcher;
import flash.events.TimerEvent;
import flash.utils.Timer;
import com.threerings.util.Log;
import com.threerings.util.MethodQueue;
import com.threerings.util.Throttle;
import com.threerings.presents.client.InvocationService_ConfirmListener;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.data.InvocationCodes;
import com.threerings.presents.data.TimeBaseMarshaller;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.net.AuthResponseData;
import com.threerings.presents.net.BootstrapData;
import com.threerings.presents.net.Credentials;
import com.threerings.presents.net.PingRequest;
import com.threerings.presents.net.PongResponse;
import com.threerings.presents.net.ThrottleUpdatedMessage;
public class Client extends EventDispatcher
{
/** The default port on which the server listens for client connections. */
public static const DEFAULT_SERVER_PORTS :Array = [ 47624 ];
/** Our default maximum outgoing message rate in messages per second. */
public static const DEFAULT_MSGS_PER_SECOND :int = 10;
private static const log :Log = Log.getLog(Client);
// statically reference classes we require
TimeBaseMarshaller;
public function Client (creds :Credentials)
{
_creds = creds;
}
/**
* Registers the supplied observer with this client. While registered the observer will receive
* notifications of state changes within the client. The function will refuse to register an
* already registered observer.
*
* @see ClientObserver
* @see SessionObserver
*/
public function addClientObserver (observer :SessionObserver) :void
{
addEventListener(ClientEvent.CLIENT_WILL_LOGON, observer.clientWillLogon);
addEventListener(ClientEvent.CLIENT_DID_LOGON, observer.clientDidLogon);
addEventListener(ClientEvent.CLIENT_OBJECT_CHANGED, observer.clientObjectDidChange);
addEventListener(ClientEvent.CLIENT_DID_LOGOFF, observer.clientDidLogoff);
if (observer is ClientObserver) {
var cliObs :ClientObserver = (observer as ClientObserver);
addEventListener(ClientEvent.CLIENT_FAILED_TO_LOGON, cliObs.clientFailedToLogon);
addEventListener(ClientEvent.CLIENT_CONNECTION_FAILED, cliObs.clientConnectionFailed);
addEventListener(ClientEvent.CLIENT_WILL_LOGOFF, cliObs.clientWillLogoff);
addEventListener(ClientEvent.CLIENT_DID_CLEAR, cliObs.clientDidClear);
}
}
/**
* Unregisters the supplied observer. Upon return of this function, the observer will no longer
* receive notifications of state changes within the client.
*/
public function removeClientObserver (observer :SessionObserver) :void
{
removeEventListener(ClientEvent.CLIENT_WILL_LOGON, observer.clientWillLogon);
removeEventListener(ClientEvent.CLIENT_DID_LOGON, observer.clientDidLogon);
removeEventListener(ClientEvent.CLIENT_OBJECT_CHANGED, observer.clientObjectDidChange);
removeEventListener(ClientEvent.CLIENT_DID_LOGOFF, observer.clientDidLogoff);
if (observer is ClientObserver) {
var cliObs :ClientObserver = (observer as ClientObserver);
removeEventListener(ClientEvent.CLIENT_FAILED_TO_LOGON, cliObs.clientFailedToLogon);
removeEventListener(
ClientEvent.CLIENT_CONNECTION_FAILED, cliObs.clientConnectionFailed);
removeEventListener(ClientEvent.CLIENT_WILL_LOGOFF, cliObs.clientWillLogoff);
removeEventListener(ClientEvent.CLIENT_DID_CLEAR, cliObs.clientDidClear);
}
}
public function setServer (hostname :String, ports :Array) :void
{
_hostname = hostname;
_ports = ports;
}
public function callLater (fn :Function, args :Array = null) :void
{
MethodQueue.callLater(fn, args);
}
public function getHostname () :String
{
return _hostname;
}
/**
* Returns the ports on which this client is configured to connect.
*/
public function getPorts () :Array
{
return _ports;
}
public function getCredentials () :Credentials
{
return _creds;
}
public function setCredentials (creds :Credentials) :void
{
_creds = creds;
}
public function getVersion () :String
{
return _version;
}
public function setVersion (version :String) :void
{
_version = version;
}
public function getAuthResponseData () :AuthResponseData
{
return _authData;
}
public function setAuthResponseData (data :AuthResponseData) :void
{
_authData = data;
}
public function getDObjectManager () :DObjectManager
{
return _omgr;
}
public function getClientOid () :int
{
return _cloid;
}
public function getClientObject () :ClientObject
{
return _clobj;
}
public function getInvocationDirector () :InvocationDirector
{
return _invdir;
}
/**
* Returns the set of bootstrap service groups needed by this client.
*/
public function getBootGroups () :Array
{
return _bootGroups;
}
/**
* Marks this client as interested in the specified bootstrap services group. Any services
* registered as bootstrap services with the supplied group name will be included in this
* clients bootstrap services set. This must be called before {@link #logon}.
*/
public function addServiceGroup (group :String) :void
{
if (isLoggedOn()) {
throw new Error("Services must be registered prior to logon().");
}
if (_bootGroups.indexOf(group) == -1) {
_bootGroups.push(group);
}
}
public function getService (clazz :Class) :InvocationService
{
if (_bstrap != null) {
for each (var isvc :InvocationService in _bstrap.services) {
if (isvc is clazz) {
return isvc;
}
}
}
return null;
}
public function requireService (clazz :Class) :InvocationService
{
var isvc :InvocationService = getService(clazz);
if (isvc == null) {
throw new Error(clazz + " isn't available. I can't bear to go on.");
}
return isvc;
}
public function getBootstrapData () :BootstrapData
{
return _bstrap;
}
public function isLoggedOn () :Boolean
{
return (_clobj != null);
}
/**
* Requests that this client connect and logon to the server with which it was previously
* configured.
*
* @return false if we're already logged on.
*/
public function logon () :Boolean
{
// if we have a communicator, we're already logged on
if (_comm != null) {
return false;
}
// let our observers know that we're logging on (this will give directors a chance to
// register invocation service groups)
notifyObservers(ClientEvent.CLIENT_WILL_LOGON);
// we need to wait for the CLIENT_WILL_LOGON to have been dispatched before we actually
// tell the communicator to logon, so we run this through the callLater pipeline
_comm = new Communicator(this);
callLater(_comm.logon);
return true;
}
/**
* Transitions a logged on client from its current server to the specified new server.
* Currently this simply logs the client off of its current server (if it is logged on) and
* logs it onto the new server, but in the future we may aim to do something fancier.
*
* <p> If we fail to connect to the new server, the client <em>will not</em> be automatically
* reconnected to the old server. It will be in a logged off state. However, it will be
* reconfigured with the hostname and ports of the old server so that the caller can notify the
* user of the failure and then simply call {@link #logon} to attempt to reconnect to the old
* server.
*
* @param observer an observer that will be notified when we have successfully logged onto the
* other server, or if the move failed.
*/
public function moveToServer (hostname :String, ports :Array,
obs :InvocationService_ConfirmListener) :void
{
// the server switcher will take care of everything for us
_switcher = new ServerSwitcher(this, hostname, ports, obs);
_switcher.switchServers();
}
/**
* Requests that the client log off of the server to which it is connected.
*
* @param abortable if true, the client will call clientWillDisconnect on allthe client
* observers and abort the logoff process if any of them return false. If false,
* clientWillDisconnect will not be called.
*
* @return true if the logoff succeeded, false if it failed due to a disagreeable observer.
*/
public function logoff (abortable :Boolean) :Boolean
{
if (_comm == null) {
log.warning("Ignoring request to log off: not logged on.");
return true;
}
// if this is an externally initiated logoff request, clear our active session status
if (_switcher == null) {
_activeSession = false;
}
// if the request is abortable, let's run it past the observers. if any of them call
// preventDefault() then the logoff will be cancelled
if (abortable && !notifyObservers(ClientEvent.CLIENT_WILL_LOGOFF)) {
_activeSession = true; // restore our active session status
return false;
}
if (_tickInterval != null) {
_tickInterval.stop();
_tickInterval = null;
}
_comm.logoff();
return true;
}
public function gotBootstrap (data :BootstrapData, omgr :DObjectManager) :void
{
// log.debug("Got bootstrap " + data + ".");
_bstrap = data;
_omgr = omgr;
_cloid = data.clientOid;
_invdir.init(omgr, _cloid, this);
// log.debug("TimeBaseService: " + requireService(TimeBaseService));
}
/**
* Called every five seconds; ensures that we ping the server if we haven't communicated in a
* long while.
*/
protected function tick (event :TimerEvent) :void
{
if (_comm == null) {
return;
}
var now :uint = flash.utils.getTimer();
if (now - _comm.getLastWrite() > PingRequest.PING_INTERVAL) {
_comm.postMessage(new PingRequest());
}
}
/**
* Called by the {@link Communicator} if it is experiencing trouble logging on but is still
* trying fallback strategies.
*/
internal function reportLogonTribulations (cause :LogonError) :void
{
notifyObservers(ClientEvent.CLIENT_FAILED_TO_LOGON, cause);
}
/**
* Called by the invocation director when it successfully subscribes to the client object
* immediately following logon.
*/
public function gotClientObject (clobj :ClientObject) :void
{
// keep our client object around
_clobj = clobj;
// and start up our tick interval (which will send pings when necessary)
if (_tickInterval == null) {
_tickInterval = new Timer(5000);
_tickInterval.addEventListener(TimerEvent.TIMER, tick);
_tickInterval.start();
}
notifyObservers(ClientEvent.CLIENT_DID_LOGON);
// now that we've logged on at least once, we're in the middle of an active session and
// will remain so until we receive an externally initiated logoff request
_activeSession = true;
}
/**
* Called by the invocation director if it fails to subscribe to the client object after logon.
*/
public function getClientObjectFailed (cause :Error) :void
{
notifyObservers(ClientEvent.CLIENT_FAILED_TO_LOGON, cause);
}
/**
* Called by the invocation director when it discovers that the client object has changed.
*/
protected function clientObjectDidChange (clobj :ClientObject) :void
{
_clobj = clobj;
_cloid = clobj.getOid();
notifyObservers(ClientEvent.CLIENT_OBJECT_CHANGED);
}
/**
* Convenience method to dispatch a client event to any listeners and return the result of
* dispatchEvent.
*/
public function notifyObservers (evtCode :String, cause :Error = null) :Boolean
{
return dispatchEvent(new ClientEvent(evtCode, this, _activeSession, cause));
}
/**
* Called by the omgr when we receive a pong packet.
*/
internal function gotPong (pong :PongResponse) :void
{
// TODO: compute time delta?
}
internal function setOutgoingMessageThrottle (messagesPerSec :int) :void
{
_comm.postMessage(new ThrottleUpdatedMessage(messagesPerSec));
}
internal function finalizeOutgoingMessageThrottle (messagesPerSec :int) :void
{
// when the throttle update message goes out to the server
_outThrottle.reinit(messagesPerSec, 1000);
log.info("Updated outgoing throttle", "messagesPerSec", messagesPerSec);
}
internal function getOutgoingMessageThrottle () :Throttle
{
return _outThrottle;
}
internal function cleanup (logonError :Error) :void
{
// clear out our references
_comm = null;
_bstrap = null;
_omgr = null;
_clobj = null;
_cloid = -1;
// and let our invocation director know we're logged off
_invdir.cleanup();
// if this was due to a logon error, we can notify our listeners now that we're cleaned up:
// they may want to retry logon on another port, or something
if (logonError != null) {
notifyObservers(ClientEvent.CLIENT_FAILED_TO_LOGON, logonError);
} else {
notifyObservers(ClientEvent.CLIENT_DID_CLEAR, null);
}
// clear out any server switcher reference
_switcher = null;
}
/** The credentials we used to authenticate with the server. */
protected var _creds :Credentials;
/** The version string reported to the server at auth time. */
protected var _version :String = "";
/** The distributed object manager we're using during this session. */
protected var _omgr :DObjectManager;
/** The data associated with our authentication response. */
protected var _authData :AuthResponseData;
/** Our client distributed object id. */
protected var _cloid :int = -1;
/** Our client distributed object. */
protected var _clobj :ClientObject;
/** The game server host. */
protected var _hostname :String;
/** The port on which we connect to the game server. */
protected var _ports :Array; /* of int */
/** The entity that manages our network communications. */
protected var _comm :Communicator;
/** Our outgoing message throttle. */
protected var _outThrottle :Throttle = new Throttle(DEFAULT_MSGS_PER_SECOND, 1000);
/** The set of bootstrap service groups this client cares about. */
protected var _bootGroups :Array = new Array(InvocationCodes.GLOBAL_GROUP);
/** General startup information provided by the server. */
protected var _bstrap :BootstrapData;
/** Manages invocation services. */
protected var _invdir :InvocationDirector = new InvocationDirector();
/** Ticks. */
protected var _tickInterval :Timer;
/** This flag is used to distinguish our *first* willLogon/didLogon and a caller-initiated
* willLogoff/didLogoff from similar events generated during server switches. Thus it is true
* for most of a normal client session. */
protected var _activeSession :Boolean;
/** Used to temporarily track our server switcher so that we can tell when we're logging off
* whether or not we're switching servers or actually ending our session. */
protected var _switcher :ServerSwitcher;
}
}
|
Clear out our _bstrap reference after we logoff.
|
Clear out our _bstrap reference after we logoff.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5734 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
fed545943611be2ff83fb29cc8c456155333eb2d
|
src/aerys/minko/scene/node/light/DirectionalLight.as
|
src/aerys/minko/scene/node/light/DirectionalLight.as
|
package aerys.minko.scene.node.light
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.scene.controller.light.DirectionalLightController;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.ShadowMappingType;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
use namespace minko_scene;
/**
*
* @author Romain Gilliotte
* @author Jean-Marc Le Roux
*
*/
public class DirectionalLight extends AbstractLight
{
private static const LIGHT_TYPE : uint = 1;
public function get diffuse() : Number
{
return lightData.getLightProperty('diffuse') as Number;
}
public function set diffuse(v : Number) : void
{
lightData.setLightProperty('diffuse', v);
if (lightData.getLightProperty('diffuseEnabled') != (v != 0))
lightData.setLightProperty('diffuseEnabled', v != 0);
}
public function get specular() : Number
{
return lightData.getLightProperty('specular') as Number;
}
public function set specular(v : Number) : void
{
lightData.setLightProperty('specular', v);
if (lightData.getLightProperty('specularEnabled') != (v != 0))
lightData.setLightProperty('specularEnabled', v != 0);
}
public function get shininess() : Number
{
return lightData.getLightProperty('shininess') as Number;
}
public function set shininess(value : Number) : void
{
lightData.setLightProperty('shininess', value);
}
public function get shadowWidth() : Number
{
return lightData.getLightProperty('shadowWidth');
}
public function set shadowWidth(v : Number) : void
{
lightData.setLightProperty('shadowWidth', v);
}
public function get shadowZFar() : Number
{
return lightData.getLightProperty('shadowZFar');
}
public function set shadowZFar(v : Number) : void
{
lightData.setLightProperty('shadowZFar', v);
}
public function get shadowQuality() : uint
{
return lightData.getLightProperty('shadowQuality');
}
public function set shadowQuality(v : uint) : void
{
lightData.setLightProperty('shadowQuality', v);
}
public function get shadowSpread() : uint
{
return lightData.getLightProperty('shadowSpread');
}
public function set shadowSpread(v : uint) : void
{
lightData.setLightProperty('shadowSpread', v);
}
public function get shadowMapSize() : uint
{
return lightData.getLightProperty('shadowMapSize');
}
public function set shadowMapSize(v : uint) : void
{
lightData.setLightProperty('shadowMapSize', v);
}
public function get shadowCastingType() : uint
{
return lightData.getLightProperty('shadowCastingType');
}
public function set shadowCastingType(value : uint) : void
{
lightData.setLightProperty('shadowCastingType', value);
}
public function get shadowBias() : Number
{
return lightData.getLightProperty(PhongProperties.SHADOW_BIAS);
}
public function set shadowBias(value : Number) : void
{
lightData.setLightProperty(PhongProperties.SHADOW_BIAS, value);
}
public function DirectionalLight(color : uint = 0xFFFFFFFF,
diffuse : Number = .6,
specular : Number = .8,
shininess : Number = 64,
emissionMask : uint = 0x1,
shadowCastingType : uint = 0,
shadowMapSize : uint = 512,
shadowZFar : Number = 1000,
shadowWidth : Number = 20,
shadowQuality : uint = 0,
shadowSpread : uint = 1,
shadowBias : uint = .002)
{
super(
new DirectionalLightController(),
LIGHT_TYPE,
color,
emissionMask
);
this.diffuse = diffuse;
this.specular = specular;
this.shininess = shininess;
this.shadowCastingType = shadowCastingType;
this.shadowZFar = shadowZFar;
this.shadowWidth = shadowWidth;
this.shadowMapSize = shadowMapSize;
this.shadowQuality = shadowQuality;
this.shadowSpread = shadowSpread;
this.shadowBias = shadowBias;
transform.lookAt(Vector4.ZERO, new Vector4(1, -1, 1));
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var light : DirectionalLight = new DirectionalLight(
color,
diffuse,
specular,
shininess,
emissionMask,
shadowCastingType,
shadowMapSize,
shadowZFar,
shadowWidth,
shadowQuality,
shadowSpread,
shadowBias
);
light.name = this.name;
light.transform.copyFrom(this.transform);
return light;
}
}
}
|
package aerys.minko.scene.node.light
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.scene.controller.light.DirectionalLightController;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.enum.ShadowMappingType;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
use namespace minko_scene;
/**
*
* @author Romain Gilliotte
* @author Jean-Marc Le Roux
*
*/
public class DirectionalLight extends AbstractLight
{
private static const LIGHT_TYPE : uint = 1;
public function get diffuse() : Number
{
return lightData.getLightProperty('diffuse') as Number;
}
public function set diffuse(v : Number) : void
{
lightData.setLightProperty('diffuse', v);
if (lightData.getLightProperty('diffuseEnabled') != (v != 0))
lightData.setLightProperty('diffuseEnabled', v != 0);
}
public function get specular() : Number
{
return lightData.getLightProperty('specular') as Number;
}
public function set specular(v : Number) : void
{
lightData.setLightProperty('specular', v);
if (lightData.getLightProperty('specularEnabled') != (v != 0))
lightData.setLightProperty('specularEnabled', v != 0);
}
public function get shininess() : Number
{
return lightData.getLightProperty('shininess') as Number;
}
public function set shininess(value : Number) : void
{
lightData.setLightProperty('shininess', value);
}
public function get shadowWidth() : Number
{
return lightData.getLightProperty('shadowWidth');
}
public function set shadowWidth(v : Number) : void
{
lightData.setLightProperty('shadowWidth', v);
}
public function get shadowZFar() : Number
{
return lightData.getLightProperty('shadowZFar');
}
public function set shadowZFar(v : Number) : void
{
lightData.setLightProperty('shadowZFar', v);
}
public function get shadowQuality() : uint
{
return lightData.getLightProperty('shadowQuality');
}
public function set shadowQuality(v : uint) : void
{
lightData.setLightProperty('shadowQuality', v);
}
public function get shadowSpread() : uint
{
return lightData.getLightProperty('shadowSpread');
}
public function set shadowSpread(v : uint) : void
{
lightData.setLightProperty('shadowSpread', v);
}
public function get shadowMapSize() : uint
{
return lightData.getLightProperty('shadowMapSize');
}
public function set shadowMapSize(v : uint) : void
{
lightData.setLightProperty('shadowMapSize', v);
}
public function get shadowCastingType() : uint
{
return lightData.getLightProperty('shadowCastingType');
}
public function set shadowCastingType(value : uint) : void
{
lightData.setLightProperty('shadowCastingType', value);
}
public function get shadowBias() : Number
{
return lightData.getLightProperty(PhongProperties.SHADOW_BIAS);
}
public function set shadowBias(value : Number) : void
{
lightData.setLightProperty(PhongProperties.SHADOW_BIAS, value);
}
public function DirectionalLight(color : uint = 0xFFFFFFFF,
diffuse : Number = .6,
specular : Number = .8,
shininess : Number = 64,
emissionMask : uint = 0x1,
shadowCastingType : uint = 0,
shadowMapSize : uint = 512,
shadowZFar : Number = 1000,
shadowWidth : Number = 20,
shadowQuality : uint = 0,
shadowSpread : uint = 1,
shadowBias : uint = .002)
{
super(
new DirectionalLightController(),
LIGHT_TYPE,
color,
emissionMask
);
this.diffuse = diffuse;
this.specular = specular;
this.shininess = shininess;
this.shadowCastingType = shadowCastingType;
this.shadowZFar = shadowZFar;
this.shadowWidth = shadowWidth;
this.shadowMapSize = shadowMapSize;
this.shadowQuality = shadowQuality;
this.shadowSpread = shadowSpread;
this.shadowBias = shadowBias;
transform.lookAt(Vector4.ZERO, new Vector4(1, 1, 1));
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var light : DirectionalLight = new DirectionalLight(
color,
diffuse,
specular,
shininess,
emissionMask,
shadowCastingType,
shadowMapSize,
shadowZFar,
shadowWidth,
shadowQuality,
shadowSpread,
shadowBias
);
light.name = this.name;
light.transform.copyFrom(this.transform);
return light;
}
}
}
|
fix DirectionalLight position init
|
fix DirectionalLight position init
|
ActionScript
|
mit
|
aerys/minko-as3
|
fe5d4b47efd8b2b4c2efbf7f9d4b7a3b6327959a
|
src/as/com/threerings/crowd/data/OccupantInfo.as
|
src/as/com/threerings/crowd/data/OccupantInfo.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 {
import com.threerings.util.ClassUtil;
import com.threerings.util.Cloneable;
import com.threerings.util.Integer;
import com.threerings.util.Name;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.SimpleStreamableObject;
import com.threerings.presents.dobj.DSet_Entry;
import com.threerings.crowd.data.BodyObject;
/**
* The occupant info object contains all of the information about an
* occupant of a place that should be shared with other occupants of the
* place. These objects are stored in the place object itself and are
* updated when bodies enter and exit a place.
*
* <p> A system that builds upon the Crowd framework can extend this class to
* include extra information about their occupants. They will need to provide a
* derived {@link BodyObject} that creates and configures their occupant info
* in {@link BodyObject#createOccupantInfo}.
*
* <p> Note also that this class implements {@link Cloneable} which means
* that if derived classes add non-primitive attributes, they are
* responsible for adding the code to clone those attributes when a clone
* is requested.
*/
public class OccupantInfo extends SimpleStreamableObject
implements DSet_Entry, Cloneable
{
/** Constant value for {@link #status}. */
public static const ACTIVE :int = 0;
/** Constant value for {@link #status}. */
public static const IDLE :int = 1;
/** Constant value for {@link #status}. */
public static const DISCONNECTED :int = 2;
/** Maps status codes to human readable strings. */
public static const X_STATUS :Array = [ "active", "idle", "discon" ];
/** The body object id of this occupant (and our entry key). */
public var bodyOid :int;
/** The username of this occupant. */
public var username :Name;
/** The status of this occupant. */
public var status :int = ACTIVE;
/**
* Constructs an occupant info record, optionally obtaining data from the
* supplied BodyObject.
*/
public function OccupantInfo (body :BodyObject = null)
{
if (body != null) {
bodyOid = body.getOid();
username = body.getVisibleName();
status = body.status;
}
}
/** Access to the body object id as an int. */
public function getBodyOid () :int
{
return bodyOid;
}
/**
* Generates a cloned copy of this instance.
*/
public function clone () :Object
{
var that :OccupantInfo = ClassUtil.newInstance(this) as OccupantInfo;
that.bodyOid = this.bodyOid;
that.username = this.username;
that.status = this.status;
return that;
}
// documentation inherited from interface DSet_Entry
public function getKey () :Object
{
return bodyOid;
}
// from interface Streamable
override public function readObject (ins :ObjectInputStream) :void
{
super.readObject(ins);
bodyOid = (ins.readField(Integer) as Integer).value;
username = (ins.readObject() as Name);
status = ins.readByte();
}
// from interface Streamable
override public function writeObject (out :ObjectOutputStream) :void
{
super.writeObject(out);
out.writeObject(new Integer(bodyOid));
out.writeObject(username);
out.writeByte(status);
}
}
}
|
//
// $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 {
import flash.system.ApplicationDomain;
import com.threerings.util.ClassUtil;
import com.threerings.util.Cloneable;
import com.threerings.util.Integer;
import com.threerings.util.Name;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.SimpleStreamableObject;
import com.threerings.presents.dobj.DSet_Entry;
import com.threerings.crowd.data.BodyObject;
/**
* The occupant info object contains all of the information about an
* occupant of a place that should be shared with other occupants of the
* place. These objects are stored in the place object itself and are
* updated when bodies enter and exit a place.
*
* <p> A system that builds upon the Crowd framework can extend this class to
* include extra information about their occupants. They will need to provide a
* derived {@link BodyObject} that creates and configures their occupant info
* in {@link BodyObject#createOccupantInfo}.
*
* <p> Note also that this class implements {@link Cloneable} which means
* that if derived classes add non-primitive attributes, they are
* responsible for adding the code to clone those attributes when a clone
* is requested.
*/
public class OccupantInfo extends SimpleStreamableObject
implements DSet_Entry, Cloneable
{
/** Constant value for {@link #status}. */
public static const ACTIVE :int = 0;
/** Constant value for {@link #status}. */
public static const IDLE :int = 1;
/** Constant value for {@link #status}. */
public static const DISCONNECTED :int = 2;
/** Maps status codes to human readable strings. */
public static const X_STATUS :Array = [ "active", "idle", "discon" ];
/** The body object id of this occupant (and our entry key). */
public var bodyOid :int;
/** The username of this occupant. */
public var username :Name;
/** The status of this occupant. */
public var status :int = ACTIVE;
/**
* Constructs an occupant info record, optionally obtaining data from the
* supplied BodyObject.
*/
public function OccupantInfo (body :BodyObject = null)
{
if (body != null) {
bodyOid = body.getOid();
username = body.getVisibleName();
status = body.status;
}
}
/** Access to the body object id as an int. */
public function getBodyOid () :int
{
return bodyOid;
}
/**
* Generates a cloned copy of this instance.
*/
public function clone () :Object
{
var that :OccupantInfo =
ClassUtil.newInstance(this, ApplicationDomain.currentDomain) as OccupantInfo;
that.bodyOid = this.bodyOid;
that.username = this.username;
that.status = this.status;
return that;
}
// documentation inherited from interface DSet_Entry
public function getKey () :Object
{
return bodyOid;
}
// from interface Streamable
override public function readObject (ins :ObjectInputStream) :void
{
super.readObject(ins);
bodyOid = (ins.readField(Integer) as Integer).value;
username = (ins.readObject() as Name);
status = ins.readByte();
}
// from interface Streamable
override public function writeObject (out :ObjectOutputStream) :void
{
super.writeObject(out);
out.writeObject(new Integer(bodyOid));
out.writeObject(username);
out.writeByte(status);
}
}
}
|
Clone fix: pass in our ApplicationDomain.
|
Clone fix: pass in our ApplicationDomain.
This is sorta wacked. Grumble. I wish there was a pointer to the class always,
instead of the language letting anonymous functions be a "constructor".
This may not always work if a subclass of OccupantInfo is loaded into a sub-domain.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5227 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
cd8547153406fdce4299af9f13160858e887f921
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
package org.arisgames.editor.util
{
public class AppConstants
{
//Server URL
//public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://arisgames.org/stagingserver1"; //For other URL's to append to- Staging
public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server"; //For other URL's to append to- Dev
public static const APPLICATION_ENVIRONMENT_SERVICES_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris_1_4/"; //staging
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris_1_4/uploadhandler.php";
public static const APPLICATION_ENVIRONMENT_GATEWAY_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/gateway.php"; //services-config.xml
//Google API
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //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
// 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_HIGHLIGHTOBJECTPALETTEITEM:String = "HighlightObjectPaletteItem";
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_WEBPAGE:String = "WebPage";
public static const CONTENTTYPE_AUGBUBBLE:String = "AugBubble";
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_WEBPAGE_VAL:Number = 4;
public static const CONTENTTYPE_AUGBUBBLE_VAL:Number = 5;
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 CONTENTTYPE_WEBPAGE_DATABASE:String = "WebPage";
public static const CONTENTTYPE_AUGBUBBLE_DATABASE:String = "AugBubble";
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";
// Max allowed upload size for media.........MB....KB....Bytes
public static const MAX_UPLOAD_SIZE:Number = 10 * 1024 * 1024 //In bytes
// 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_SEPARATOR:String = " ";
public static const MEDIATYPE_UPLOADNEW:String = " ";
// Media-tree-icon Types
public static const MEDIATREEICON_SEPARATOR:String = "separatorIcon";
public static const MEDIATREEICON_UPLOAD:String = "uploadIcon";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_WEBPAGE:String = "VIEW_WEBPAGE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_AUGBUBBLE:String = "VIEW_AUGBUBBLE";
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_WEBPAGE_DATABASE:String = "PLAYER_VIEWED_WEBPAGE";
public static const REQUIREMENT_PLAYER_VIEWED_WEBPAGE_HUMAN:String = "Player Viewed Web Page";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_WEBPAGE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_WEBPAGE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_WEBPAGE_HUMAN:String = "Player Never Viewed Web Page";
public static const REQUIREMENT_PLAYER_VIEWED_AUGBUBBLE_DATABASE:String = "PLAYER_VIEWED_AUGBUBBLE";
public static const REQUIREMENT_PLAYER_VIEWED_AUGBUBBLE_HUMAN:String = "Player Viewed Aug Bubble";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_AUGBUBBLE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_AUGBUBBLE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_AUGBUBBLE_HUMAN:String = "Player Never Viewed Aug Bubble";
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_HUMAN: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;
public static const DEFAULT_ICON_MEDIA_ID_WEBPAGE:Number = 4;
public static const DEFAULT_ICON_MEDIA_ID_AUGBUBBLE:Number = 2;
// Palette Tree Stuff
public static const PALETTE_TREE_SELF_FOLDER_ID:Number = 0;
public static const PLAYER_GENERATED_MEDIA_FOLDER_ID:Number = -1;
public static const PLAYER_GENERATED_MEDIA_FOLDER_NAME:String = "New Player Created Items";
// Media Picker Stuff
public static const MEDIA_PICKER:Number = 0;
public static const ICON_PICKER:Number = 1;
public static const ALIGNMENT_PICKER:Number = 2;
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
package org.arisgames.editor.util
{
public class AppConstants
{
//Server URL
//public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://arisgames.org/stagingserver1"; //For other URL's to append to- Staging
public static const APPLICATION_ENVIRONMENT_ROOT_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server"; //For other URL's to append to- Dev
public static const APPLICATION_ENVIRONMENT_SERVICES_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris_1_4/"; //staging
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/services/aris_1_4/uploadhandler.php";
public static const APPLICATION_ENVIRONMENT_GATEWAY_URL:String = APPLICATION_ENVIRONMENT_ROOT_URL+"/gateway.php"; //services-config.xml
//Google API
//public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //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
// 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_HIGHLIGHTOBJECTPALETTEITEM:String = "HighlightObjectPaletteItem";
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_WEBPAGE:String = "WebPage";
public static const CONTENTTYPE_AUGBUBBLE:String = "AugBubble";
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_WEBPAGE_VAL:Number = 4;
public static const CONTENTTYPE_AUGBUBBLE_VAL:Number = 5;
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 CONTENTTYPE_WEBPAGE_DATABASE:String = "WebPage";
public static const CONTENTTYPE_AUGBUBBLE_DATABASE:String = "AugBubble";
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";
// Max allowed upload size for media.........MB....KB....Bytes
public static const MAX_UPLOAD_SIZE:Number = 10 * 1024 * 1024 //In bytes
// 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_SEPARATOR:String = " ";
public static const MEDIATYPE_UPLOADNEW:String = " ";
// Media-tree-icon Types
public static const MEDIATREEICON_SEPARATOR:String = "separatorIcon";
public static const MEDIATREEICON_UPLOAD:String = "uploadIcon";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_WEBPAGE:String = "VIEW_WEBPAGE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_AUGBUBBLE:String = "VIEW_AUGBUBBLE";
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_WEBPAGE_DATABASE:String = "PLAYER_VIEWED_WEBPAGE";
public static const REQUIREMENT_PLAYER_VIEWED_WEBPAGE_HUMAN:String = "Player Viewed Web Page";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_WEBPAGE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_WEBPAGE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_WEBPAGE_HUMAN:String = "Player Never Viewed Web Page";
public static const REQUIREMENT_PLAYER_VIEWED_AUGBUBBLE_DATABASE:String = "PLAYER_VIEWED_AUGBUBBLE";
public static const REQUIREMENT_PLAYER_VIEWED_AUGBUBBLE_HUMAN:String = "Player Viewed Aug Bubble";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_AUGBUBBLE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_AUGBUBBLE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_AUGBUBBLE_HUMAN:String = "Player Never Viewed Aug Bubble";
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_HUMAN: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;
public static const DEFAULT_ICON_MEDIA_ID_WEBPAGE:Number = 4;
public static const DEFAULT_ICON_MEDIA_ID_AUGBUBBLE:Number = 5;
// Palette Tree Stuff
public static const PALETTE_TREE_SELF_FOLDER_ID:Number = 0;
public static const PLAYER_GENERATED_MEDIA_FOLDER_ID:Number = -1;
public static const PLAYER_GENERATED_MEDIA_FOLDER_NAME:String = "New Player Created Items";
// Media Picker Stuff
public static const MEDIA_PICKER:Number = 0;
public static const ICON_PICKER:Number = 1;
public static const ALIGNMENT_PICKER:Number = 2;
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
update default augbubble icon
|
update default augbubble icon
|
ActionScript
|
mit
|
ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames
|
9098a6dd5ffd14bf619c521dac3fa78c3154005a
|
src/com/esri/builder/controllers/ApplicationCompleteController.as
|
src/com/esri/builder/controllers/ApplicationCompleteController.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers
{
import com.esri.ags.components.IdentityManager;
import com.esri.builder.components.LogFileTarget;
import com.esri.builder.components.SignInWindow;
import com.esri.builder.components.ToolTip;
import com.esri.builder.controllers.supportClasses.Settings;
import com.esri.builder.controllers.supportClasses.WellKnownDirectories;
import com.esri.builder.controllers.supportClasses.StartupWidgetTypeLoader;
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.controllers.supportClasses.MachineDisplayName;
import com.esri.builder.model.Model;
import com.esri.builder.model.PortalModel;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import com.esri.builder.views.popups.UnknownErrorPopUp;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.UncaughtErrorEvent;
import flash.filesystem.File;
import flash.net.SharedObject;
import flash.net.URLRequestDefaults;
import flash.system.Capabilities;
import mx.core.FlexGlobals;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.managers.ToolTipManager;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import spark.components.WindowedApplication;
public final class ApplicationCompleteController
{
private static const LOG:ILogger = LogUtil.createLogger(ApplicationCompleteController);
private var widgetTypeLoader:StartupWidgetTypeLoader;
private var startupSettings:Settings;
public function ApplicationCompleteController()
{
AppEvent.addListener(AppEvent.APPLICATION_COMPLETE, onApplicationComplete, false, 0, true);
}
private function onApplicationComplete(event:AppEvent):void
{
applicationComplete(event.data as WindowedApplication);
Model.instance.config.isDirty = false;
}
private function applicationComplete(app:WindowedApplication):void
{
if (Log.isInfo())
{
LOG.info('Starting up application.');
}
exportDependenciesToAppStorage();
loadUserPreferences();
loadWebMapSearchHistory();
// Disable HTTP cache for HTML component
URLRequestDefaults.cacheResponse = false;
// Setup some XML global properties
XML.ignoreComments = true;
XML.ignoreWhitespace = true;
XML.prettyIndent = 4;
IdentityManager.instance.enabled = true;
IdentityManager.instance.signInWindowClass = SignInWindow;
ToolTipManager.toolTipClass = com.esri.builder.components.ToolTip;
// Can only have access to 'loaderInfo' when the app is complete.
app.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
widgetTypeLoader = new StartupWidgetTypeLoader();
widgetTypeLoader.addEventListener(Event.COMPLETE, widgetTypeLoader_completeHandler);
widgetTypeLoader.loadWidgetTypes();
}
private function exportDependenciesToAppStorage():void
{
try
{
if (Log.isInfo())
{
LOG.info('Creating required folders.');
}
WellKnownDirectories.getInstance().customFlexViewer.createDirectory();
WellKnownDirectories.getInstance().customModules.createDirectory();
}
catch (error:Error)
{
BuilderAlert.show(ResourceManager.getInstance().getString('BuilderStrings', 'startup.couldNotCreateCustomDirectories'), ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
}
private function loadUserPreferences():void
{
if (Log.isInfo())
{
LOG.info('Loading user preferences...');
}
migratePreviousSettingsFolder();
const so:SharedObject = SharedObject.getLocal(Model.USER_PREF);
startupSettings = new Settings();
startupSettings.webServerURL = so.data.baseURL;
startupSettings.webServerFolder = so.data.baseLoc;
startupSettings.locale = so.data.locale ? so.data.locale : getPreferredLocale();
startupSettings.bingKey = so.data.bingKey;
startupSettings.proxyURL = so.data.httpProxy;
if (so.data.hasOwnProperty("userPortalURL"))
{
//updated property for v3.1+
startupSettings.portalURL = so.data.userPortalURL;
startupSettings.geocodeURL = so.data.geocodeURL;
startupSettings.directionsURL = so.data.directionsURL;
startupSettings.printTaskURL = so.data.printTaskURL;
}
else
{
startupSettings.portalURL = (so.data.portalURL) ? so.data.portalURL : PortalModel.DEFAULT_PORTAL_URL;
}
if (so.data.hasOwnProperty("userGeometryServiceURL"))
{
//updated property for v3.1+
startupSettings.geometryServiceURL = so.data.userGeometryServiceURL;
}
else
{
startupSettings.geometryServiceURL = so.data.userGeometryServiceURL = (so.data.geometryServiceURL) ? so.data.geometryServiceURL : "http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer";
}
if (so.data.hasOwnProperty("isTutorialModeEnabled"))
{
startupSettings.isTutorialModeEnabled = so.data.isTutorialModeEnabled;
}
else if (so.data.tutorialModeSettings)
{
startupSettings.isTutorialModeEnabled = so.data.tutorialModeSettings.isTutorialModeEnabled;
}
so.close();
if (!startupSettings.webServerFolder)
{
if (Capabilities.os.toLowerCase().indexOf('win') > -1)
{
startupSettings.webServerFolder = 'C:\\inetpub\\wwwroot\\flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('mac') > -1)
{
startupSettings.webServerFolder = File.userDirectory.nativePath + '/Sites/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('linux') > -1)
{
startupSettings.webServerFolder = '/var/httpd/wwwroot/flexviewers'; // TODO - check this !!
}
}
if (startupSettings.webServerURL)
{
applySettings();
}
else
{
tryGetHostName();
}
}
private function migratePreviousSettingsFolder():void
{
var previousBuilderSettingsFolder:File =
File.applicationStorageDirectory.resolvePath("#SharedObjects/AppBuilder.swf/");
if (!previousBuilderSettingsFolder.exists)
{
return;
}
var filesOrFolders:Array = previousBuilderSettingsFolder.getDirectoryListing();
if (filesOrFolders.length == 0)
{
return;
}
if (Log.isInfo())
{
LOG.info('Transferring previous settings folder');
}
var currentBuilderSettingsFolder:File =
File.applicationStorageDirectory.resolvePath("#SharedObjects/Builder.swf/");
try
{
for each (var fileOrFolder:File in filesOrFolders)
{
if (Log.isInfo())
{
LOG.info('Transferring {0}', fileOrFolder.name);
}
fileOrFolder.moveTo(currentBuilderSettingsFolder.resolvePath(fileOrFolder.name),
true);
}
}
catch (error:Error)
{
if (Log.isInfo())
{
LOG.info('Could not transfer previous settings folder: {0} - {1}',
error.errorID, error.toString());
}
}
}
private function applySettings():void
{
Model.instance.importSettings(startupSettings);
startupSettings = null;
}
private function tryGetHostName():void
{
MachineDisplayName.getInstance().resolve(new AsyncResponder(result, fault));
function result(hostname:String, token:Object):void
{
initBaseURL(hostname.toLowerCase());
applySettings();
}
function fault(fault:Object, token:Object):void
{
initBaseURL("localhost");
applySettings();
}
}
private function initBaseURL(hostname:String):void
{
if (Capabilities.os.toLowerCase().indexOf('win') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('mac') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/~' + File.userDirectory.name + '/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('linux') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/flexviewers'; // TODO - check this !!
}
}
private function getPreferredLocale():String
{
const preferredLocales:Array = ResourceManager.getInstance().getPreferredLocaleChain();
return (preferredLocales.length > 0) ? preferredLocales[0] : 'en_US';
}
private function loadWebMapSearchHistory():void
{
if (Log.isInfo())
{
LOG.info("Loading web map search history");
}
const so:SharedObject = SharedObject.getLocal(Model.USER_PREF);
var historyString:String = so.data.webMapSearchHistory;
if (historyString != null)
{
Model.instance.webMapSearchHistory = historyString.split("##");
}
so.close();
}
private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
{
event.preventDefault();
if (Log.isFatal())
{
if (event.error is Error) //could be ErrorEvent
{
LOG.fatal('Uncaught error: {0}', event.error.getStackTrace());
}
}
const logFile:File = File.applicationStorageDirectory.resolvePath(LogFileTarget.LOG_FILE_NAME);
const errorContent:String = ResourceManager.getInstance().getString('BuilderStrings', 'unknownErrorMessage',
[ event.error.toString(), logFile.nativePath ]);
const errorPopUp:UnknownErrorPopUp = new UnknownErrorPopUp();
errorPopUp.errorContent = errorContent;
errorPopUp.open(FlexGlobals.topLevelApplication as DisplayObjectContainer, true);
}
private function setStatusAndAlert(text:String):void
{
Model.instance.status = text;
BuilderAlert.show(text, ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
protected function widgetTypeLoader_completeHandler(event:Event):void
{
(event.currentTarget as StartupWidgetTypeLoader).removeEventListener(Event.COMPLETE, widgetTypeLoader_completeHandler);
validateSettings();
}
private function validateSettings():void
{
AppEvent.dispatch(AppEvent.SAVE_SETTINGS, Model.instance.exportSettings());
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers
{
import com.esri.ags.components.IdentityManager;
import com.esri.builder.components.LogFileTarget;
import com.esri.builder.components.SignInWindow;
import com.esri.builder.components.ToolTip;
import com.esri.builder.controllers.supportClasses.MachineDisplayName;
import com.esri.builder.controllers.supportClasses.Settings;
import com.esri.builder.controllers.supportClasses.StartupWidgetTypeLoader;
import com.esri.builder.controllers.supportClasses.WellKnownDirectories;
import com.esri.builder.eventbus.AppEvent;
import com.esri.builder.model.Model;
import com.esri.builder.model.PortalModel;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import com.esri.builder.views.popups.UnknownErrorPopUp;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.UncaughtErrorEvent;
import flash.filesystem.File;
import flash.net.SharedObject;
import flash.net.URLRequestDefaults;
import flash.system.Capabilities;
import mx.core.FlexGlobals;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.managers.ToolTipManager;
import mx.resources.ResourceManager;
import mx.rpc.AsyncResponder;
import spark.components.WindowedApplication;
public final class ApplicationCompleteController
{
private static const LOG:ILogger = LogUtil.createLogger(ApplicationCompleteController);
private var widgetTypeLoader:StartupWidgetTypeLoader;
private var startupSettings:Settings;
public function ApplicationCompleteController()
{
AppEvent.addListener(AppEvent.APPLICATION_COMPLETE, onApplicationComplete, false, 0, true);
}
private function onApplicationComplete(event:AppEvent):void
{
applicationComplete(event.data as WindowedApplication);
Model.instance.config.isDirty = false;
}
private function applicationComplete(app:WindowedApplication):void
{
if (Log.isInfo())
{
LOG.info('Starting up application.');
}
exportDependenciesToAppStorage();
loadUserPreferences();
loadWebMapSearchHistory();
// Disable HTTP cache for HTML component
URLRequestDefaults.cacheResponse = false;
// Setup some XML global properties
XML.ignoreComments = true;
XML.ignoreWhitespace = true;
XML.prettyIndent = 4;
IdentityManager.instance.enabled = true;
IdentityManager.instance.signInWindowClass = SignInWindow;
ToolTipManager.toolTipClass = com.esri.builder.components.ToolTip;
// Can only have access to 'loaderInfo' when the app is complete.
app.loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
widgetTypeLoader = new StartupWidgetTypeLoader();
widgetTypeLoader.addEventListener(Event.COMPLETE, widgetTypeLoader_completeHandler);
widgetTypeLoader.loadWidgetTypes();
}
private function exportDependenciesToAppStorage():void
{
try
{
if (Log.isInfo())
{
LOG.info('Creating required folders.');
}
WellKnownDirectories.getInstance().customFlexViewer.createDirectory();
WellKnownDirectories.getInstance().customModules.createDirectory();
}
catch (error:Error)
{
BuilderAlert.show(ResourceManager.getInstance().getString('BuilderStrings', 'startup.couldNotCreateCustomDirectories'), ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
}
private function loadUserPreferences():void
{
if (Log.isInfo())
{
LOG.info('Loading user preferences...');
}
migratePreviousSettingsFolder();
const so:SharedObject = SharedObject.getLocal(Model.USER_PREF);
startupSettings = new Settings();
startupSettings.webServerURL = so.data.baseURL;
startupSettings.webServerFolder = so.data.baseLoc;
startupSettings.locale = so.data.locale ? so.data.locale : getPreferredLocale();
startupSettings.bingKey = so.data.bingKey;
startupSettings.proxyURL = so.data.httpProxy;
if (so.data.hasOwnProperty("userPortalURL"))
{
//updated property for v3.1+
startupSettings.portalURL = so.data.userPortalURL;
startupSettings.geocodeURL = so.data.geocodeURL;
startupSettings.directionsURL = so.data.directionsURL;
startupSettings.printTaskURL = so.data.printTaskURL;
}
else
{
startupSettings.portalURL = (so.data.portalURL) ? so.data.portalURL : PortalModel.DEFAULT_PORTAL_URL;
}
if (so.data.hasOwnProperty("userGeometryServiceURL"))
{
//updated property for v3.1+
startupSettings.geometryServiceURL = so.data.userGeometryServiceURL;
}
else
{
startupSettings.geometryServiceURL = so.data.userGeometryServiceURL = (so.data.geometryServiceURL) ? so.data.geometryServiceURL : "http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer";
}
if (so.data.hasOwnProperty("isTutorialModeEnabled"))
{
startupSettings.isTutorialModeEnabled = so.data.isTutorialModeEnabled;
}
else if (so.data.tutorialModeSettings)
{
startupSettings.isTutorialModeEnabled = so.data.tutorialModeSettings.isTutorialModeEnabled;
}
so.close();
if (!startupSettings.webServerFolder)
{
if (Capabilities.os.toLowerCase().indexOf('win') > -1)
{
startupSettings.webServerFolder = 'C:\\inetpub\\wwwroot\\flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('mac') > -1)
{
startupSettings.webServerFolder = File.userDirectory.nativePath + '/Sites/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('linux') > -1)
{
startupSettings.webServerFolder = '/var/httpd/wwwroot/flexviewers'; // TODO - check this !!
}
}
if (startupSettings.webServerURL)
{
applySettings();
}
else
{
tryGetHostName();
}
}
private function migratePreviousSettingsFolder():void
{
var previousBuilderSettingsFolder:File =
File.applicationStorageDirectory.resolvePath("#SharedObjects/AppBuilder.swf/");
if (!previousBuilderSettingsFolder.exists)
{
return;
}
var filesOrFolders:Array = previousBuilderSettingsFolder.getDirectoryListing();
if (filesOrFolders.length == 0)
{
return;
}
if (Log.isInfo())
{
LOG.info('Transferring previous settings folder');
}
var currentBuilderSettingsFolder:File =
File.applicationStorageDirectory.resolvePath("#SharedObjects/Builder.swf/");
try
{
for each (var fileOrFolder:File in filesOrFolders)
{
if (Log.isInfo())
{
LOG.info('Transferring {0}', fileOrFolder.name);
}
fileOrFolder.moveTo(currentBuilderSettingsFolder.resolvePath(fileOrFolder.name),
true);
}
}
catch (error:Error)
{
if (Log.isInfo())
{
LOG.info('Could not transfer previous settings folder: {0} - {1}',
error.errorID, error.toString());
}
}
}
private function applySettings():void
{
Model.instance.importSettings(startupSettings);
startupSettings = null;
}
private function tryGetHostName():void
{
MachineDisplayName.getInstance().resolve(new AsyncResponder(result, fault));
function result(hostname:String, token:Object):void
{
initBaseURL(hostname.toLowerCase());
applySettings();
}
function fault(fault:Object, token:Object):void
{
initBaseURL("localhost");
applySettings();
}
}
private function initBaseURL(hostname:String):void
{
if (Capabilities.os.toLowerCase().indexOf('win') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('mac') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/~' + File.userDirectory.name + '/flexviewers';
}
else if (Capabilities.os.toLowerCase().indexOf('linux') > -1)
{
startupSettings.webServerURL = 'http://' + hostname + '/flexviewers'; // TODO - check this !!
}
}
private function getPreferredLocale():String
{
const preferredLocales:Array = ResourceManager.getInstance().getPreferredLocaleChain();
return (preferredLocales.length > 0) ? preferredLocales[0] : 'en_US';
}
private function loadWebMapSearchHistory():void
{
if (Log.isInfo())
{
LOG.info("Loading web map search history");
}
const so:SharedObject = SharedObject.getLocal(Model.USER_PREF);
var historyString:String = so.data.webMapSearchHistory;
if (historyString != null)
{
Model.instance.webMapSearchHistory = historyString.split("##");
}
so.close();
}
private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
{
event.preventDefault();
if (Log.isFatal())
{
if (event.error is Error) //could be ErrorEvent
{
LOG.fatal('Uncaught error: {0}', event.error.getStackTrace());
}
}
const logFile:File = File.applicationStorageDirectory.resolvePath(LogFileTarget.LOG_FILE_NAME);
const errorContent:String = ResourceManager.getInstance().getString('BuilderStrings', 'unknownErrorMessage',
[ event.error.toString(), logFile.nativePath ]);
const errorPopUp:UnknownErrorPopUp = new UnknownErrorPopUp();
errorPopUp.errorContent = errorContent;
errorPopUp.open(FlexGlobals.topLevelApplication as DisplayObjectContainer, true);
}
private function setStatusAndAlert(text:String):void
{
Model.instance.status = text;
BuilderAlert.show(text, ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
protected function widgetTypeLoader_completeHandler(event:Event):void
{
(event.currentTarget as StartupWidgetTypeLoader).removeEventListener(Event.COMPLETE, widgetTypeLoader_completeHandler);
validateSettings();
}
private function validateSettings():void
{
AppEvent.dispatch(AppEvent.SAVE_SETTINGS, Model.instance.exportSettings());
}
}
}
|
Apply formatting.
|
Apply formatting.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
23fa9407236d26723b345a46c9f028f1903e5c92
|
native_extension/src/com/tuarua/webview/AndroidSettings.as
|
native_extension/src/com/tuarua/webview/AndroidSettings.as
|
/*
* Copyright 2017 Tua Rua Ltd.
*
* 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.
*
* Additional Terms
* No part, or derivative of this Air Native Extensions's code is permitted
* to be sold as the basis of a commercially packaged Air Native Extension which
* undertakes the same purpose as this software. That is, a WebView for Windows,
* OSX and/or iOS and/or Android.
* All Rights Reserved. Tua Rua Ltd.
*/
/**
* Created by Eoin Landy on 26/03/2017.
*/
package com.tuarua.webview {
public class AndroidSettings {
/**
* <p>Sets whether the WebView requires a user gesture to play media.</p>
*/
public var mediaPlaybackRequiresUserGesture:Boolean = true;
/**
* <p>A Boolean value indicating whether JavaScript is enabled.</p>
*/
public var javaScriptEnabled:Boolean = true;
/**
* <p>A Boolean value indicating whether JavaScript can open windows without user interaction.</p>
*/
public var javaScriptCanOpenWindowsAutomatically:Boolean = true;
/**
* <p>A Boolean value indicating whether the WebView should not load image resources from the network.</p>
*/
public var blockNetworkImage:Boolean = false;
/**
* <p>Enables or disables file access within WebView.</p>
*/
public var allowFileAccess:Boolean = true;
/**
* <p>Sets whether JavaScript running in the context of a file scheme URL should be allowed to access
* content from other file scheme URLs.</p>
*/
public var allowFileAccessFromFileURLs:Boolean = true;
/**
* <p>Sets whether JavaScript running in the context of a file scheme URL should be allowed to access
* content from other file scheme URLs.</p>
*/
public var allowUniversalAccessFromFileURLs:Boolean = true;
/**
* <p>Enables or disables content URL access within WebView.</p>
*/
public var allowContentAccess:Boolean = true;
/**
* <p>Sets whether Geolocation is enabled.</p>
*/
public var geolocationEnabled:Boolean = false;
public function AndroidSettings() {
}
}
}
|
/*
* Copyright 2017 Tua Rua Ltd.
*
* 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.
*
* Additional Terms
* No part, or derivative of this Air Native Extensions's code is permitted
* to be sold as the basis of a commercially packaged Air Native Extension which
* undertakes the same purpose as this software. That is, a WebView for Windows,
* OSX and/or iOS and/or Android.
* All Rights Reserved. Tua Rua Ltd.
*/
/**
* Created by Eoin Landy on 26/03/2017.
*/
package com.tuarua.webview {
public class AndroidSettings {
/**
* <p>Sets whether the WebView requires a user gesture to play media.</p>
*/
public var mediaPlaybackRequiresUserGesture:Boolean = true;
/**
* <p>A Boolean value indicating whether JavaScript is enabled.</p>
*/
public var javaScriptEnabled:Boolean = true;
/**
* <p>A Boolean value indicating whether JavaScript can open windows without user interaction.</p>
*/
public var javaScriptCanOpenWindowsAutomatically:Boolean = true;
/**
* <p>A Boolean value indicating whether the WebView should not load image resources from the network.</p>
*/
public var blockNetworkImage:Boolean = false;
/**
* <p>Enables or disables file access within WebView.</p>
*/
public var allowFileAccess:Boolean = true;
/**
* <p>Sets whether JavaScript running in the context of a file scheme URL should be allowed to access
* content from other file scheme URLs.</p>
*/
public var allowFileAccessFromFileURLs:Boolean = true;
/**
* <p>Sets whether JavaScript running in the context of a file scheme URL should be allowed to access
* content from other file scheme URLs.</p>
*/
public var allowUniversalAccessFromFileURLs:Boolean = true;
/**
* <p>Enables or disables content URL access within WebView.</p>
*/
public var allowContentAccess:Boolean = true;
/**
* <p>Sets whether Geolocation is enabled.</p>
*/
public var geolocationEnabled:Boolean = false;
/**
* <p>Sets whether the database storage API is enabled.</p>
*/
public var databaseEnabled:Boolean = true;
/**
* <p>Sets whether the DOM storage API is enabled.</p>
*/
public var domStorageEnabled:Boolean = true;
public function AndroidSettings() {
}
}
}
|
Add 'databaseEnabled' and 'domStorageEnabled' properties to AndroidSettings object. Make them enabled by default to match the behaviour of AIR's StageWebView
|
Add 'databaseEnabled' and 'domStorageEnabled' properties to AndroidSettings object. Make them enabled by default to match the behaviour of AIR's StageWebView
|
ActionScript
|
apache-2.0
|
tuarua/WebViewANE,tuarua/WebViewANE,tuarua/WebViewANE,tuarua/WebViewANE,tuarua/WebViewANE,tuarua/WebViewANE,tuarua/WebViewANE
|
dc3ea8e844d76be4e605e631a3b508ff60c447fd
|
src/aerys/minko/scene/controller/debug/WireframeDebugController.as
|
src/aerys/minko/scene/controller/debug/WireframeDebugController.as
|
package aerys.minko.scene.controller.debug
{
import aerys.minko.render.geometry.primitive.LineGeometry;
import aerys.minko.render.geometry.stream.iterator.TriangleIterator;
import aerys.minko.render.geometry.stream.iterator.TriangleReference;
import aerys.minko.render.material.line.LineMaterial;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.Mesh;
import flash.utils.Dictionary;
public final class WireframeDebugController extends AbstractController
{
private var _wireframeMaterial : LineMaterial;
private var _targetToWireframe : Dictionary = new Dictionary();
public function get material() : LineMaterial
{
return _wireframeMaterial
|| (_wireframeMaterial = new LineMaterial({diffuseColor : 0xffffffff, lineThickness : 1.}));
}
public function WireframeDebugController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : WireframeDebugController,
target : Mesh) : void
{
if (target.scene)
addedHandler(target, target.parent);
else
target.added.add(addedHandler);
target.removed.add(removedHandler);
}
private function addedHandler(target : Mesh,
ancestor : Group) : void
{
if (!target.scene)
return ;
var triangles : TriangleIterator = new TriangleIterator(
target.geometry.getVertexStream(),
target.geometry.indexStream
);
var linesGeom : LineGeometry = new LineGeometry();
for each (var triangle : TriangleReference in triangles)
{
linesGeom.moveTo(triangle.v0.x, triangle.v0.y, triangle.v0.z)
.lineTo(triangle.v1.x, triangle.v1.y, triangle.v1.z)
.lineTo(triangle.v2.x, triangle.v2.y, triangle.v2.z)
.lineTo(triangle.v0.x, triangle.v0.y, triangle.v0.z);
}
var lines : Mesh = new Mesh(linesGeom, this.material);
_targetToWireframe[target] = lines;
target.parent.addChild(lines);
}
private function removeWireframes(target : Mesh) : void
{
if (_targetToWireframe[target])
_targetToWireframe[target].parent = null;
_targetToWireframe[target] = null;
}
private function targetRemovedHandler(ctrl : WireframeDebugController,
target : Mesh) : void
{
if (target.added.hasCallback(addedHandler))
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
removeWireframes(target);
}
private function removedHandler(target : Mesh, ancestor : Group) : void
{
removeWireframes(target);
}
}
}
|
package aerys.minko.scene.controller.debug
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.primitive.LineGeometry;
import aerys.minko.render.geometry.stream.iterator.TriangleIterator;
import aerys.minko.render.geometry.stream.iterator.TriangleReference;
import aerys.minko.render.material.line.LineMaterial;
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.type.math.Matrix4x4;
import flash.utils.Dictionary;
public final class WireframeDebugController extends AbstractController
{
private var _wireframeMaterial : LineMaterial;
private var _targetToWireframe : Dictionary = new Dictionary();
private var _geometryToMesh : Dictionary = new Dictionary();
public function get material() : LineMaterial
{
return _wireframeMaterial
|| (_wireframeMaterial = new LineMaterial({diffuseColor : 0xffffffff, lineThickness : 1.}));
}
public function WireframeDebugController()
{
super(Mesh);
initialize();
}
private function initialize() : void
{
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : WireframeDebugController,
target : Mesh) : void
{
if (target.scene)
addedHandler(target, target.parent);
else
target.added.add(addedHandler);
target.removed.add(removedHandler);
}
private function addedHandler(target : Mesh,
ancestor : Group) : void
{
if (!target.scene)
return ;
var triangles : TriangleIterator = new TriangleIterator(
target.geometry.getVertexStream(),
target.geometry.indexStream
);
var linesGeom : LineGeometry = new LineGeometry();
for each (var triangle : TriangleReference in triangles)
{
linesGeom.moveTo(triangle.v0.x, triangle.v0.y, triangle.v0.z)
.lineTo(triangle.v1.x, triangle.v1.y, triangle.v1.z)
.lineTo(triangle.v2.x, triangle.v2.y, triangle.v2.z)
.lineTo(triangle.v0.x, triangle.v0.y, triangle.v0.z);
}
var lines : Mesh = new Mesh(linesGeom, this.material);
_targetToWireframe[target] = lines;
target.localToWorldTransformChanged.add(updateTransform);
updateTransform(target, target.getLocalToWorldTransform());
target.scene.addChild(lines);
}
private function updateTransform(child : ISceneNode, childLocalToWorld : Matrix4x4) : void
{
var lineMesh : Mesh = _targetToWireframe[child];
lineMesh.transform.copyFrom(childLocalToWorld);
}
private function removeWireframes(target : Mesh) : void
{
if (_targetToWireframe[target])
_targetToWireframe[target].parent = null;
_targetToWireframe[target] = null;
}
private function targetRemovedHandler(ctrl : WireframeDebugController,
target : Mesh) : void
{
if (target.added.hasCallback(addedHandler))
target.added.remove(addedHandler);
target.removed.remove(removedHandler);
target.localToWorldTransformChanged.remove(updateTransform);
removeWireframes(target);
}
private function removedHandler(target : Mesh, ancestor : Group) : void
{
removeWireframes(target);
}
}
}
|
Update wireframe when the target move
|
Update wireframe when the target move
|
ActionScript
|
mit
|
aerys/minko-as3
|
48ecbdaf3cd534cce32a3c20319b96e97eaef720
|
conf/messages.as
|
conf/messages.as
|
playWithAFriend=বন্ধু'ৰ বিপক্ষে খেলক
playWithTheMachine=কম্পিউটাৰ'ৰ বিপক্ষে খেলক
toInviteSomeoneToPlayGiveThisUrl=অান এজনৰ বিপক্ষে খেলিবলৈ এই URLতু ব্যৱহাৰ কৰক
gameOver=খেল সমাপ্ত
gameOver=Khel Sesh
waitingForOpponent=বিৰোধী'ৰ অপেক্ষাত
waiting=অপেক্ষাত
yourTurn=আপোনাৰ পাল
white=বগা
black=ক’লা
randomColor=যাদৃচ্ছিক দল
createAGame=নতুন খেল আৰমভ কৰক
whiteIsVictorious=বগা দল বিজয়ী
blackIsVictorious=ক’লা দল বিজয়ী
kingInTheCenter=ৰজা আহিল মাজ'লৈ
whitePlays=বগা দলৰ পাল
blackPlays=ক’লা দলৰ পাল
|
playWithAFriend=বন্ধু'ৰ বিপক্ষে খেলক
playWithTheMachine=কম্পিউটাৰ'ৰ বিপক্ষে খেলক
toInviteSomeoneToPlayGiveThisUrl=অান এজনৰ বিপক্ষে খেলিবলৈ এই URLতু ব্যৱহাৰ কৰক
gameOver=Khel Sesh
waitingForOpponent=বিৰোধী'ৰ অপেক্ষাত
waiting=অপেক্ষাত
yourTurn=আপোনাৰ পাল
white=বগা
black=ক’লা
randomColor=যাদৃচ্ছিক দল
createAGame=নতুন খেল আৰমভ কৰক
whiteIsVictorious=বগা দল বিজয়ী
blackIsVictorious=ক’লা দল বিজয়ী
kingInTheCenter=ৰজা আহিল মাজ'লৈ
whitePlays=বগা দলৰ পাল
blackPlays=ক’লা দলৰ পাল
|
fix as translation unit
|
fix as translation unit
|
ActionScript
|
mit
|
abougouffa/lila,Unihedro/lila,arex1337/lila,abougouffa/lila,terokinnunen/lila,bjhaid/lila,samuel-soubeyran/lila,r0k3/lila,TangentialAlan/lila,systemovich/lila,Enigmahack/lila,arex1337/lila,ccampo133/lila,samuel-soubeyran/lila,bjhaid/lila,luanlv/lila,terokinnunen/lila,r0k3/lila,luanlv/lila,elioair/lila,JimmyMow/lila,samuel-soubeyran/lila,clarkerubber/lila,pawank/lila,samuel-soubeyran/lila,Happy0/lila,pawank/lila,pawank/lila,Enigmahack/lila,pavelo65/lila,ccampo133/lila,pawank/lila,pavelo65/lila,elioair/lila,TangentialAlan/lila,abougouffa/lila,systemovich/lila,elioair/lila,ccampo133/lila,Unihedro/lila,terokinnunen/lila,systemovich/lila,Enigmahack/lila,Enigmahack/lila,pavelo65/lila,JimmyMow/lila,Happy0/lila,terokinnunen/lila,ccampo133/lila,luanlv/lila,pawank/lila,samuel-soubeyran/lila,terokinnunen/lila,TangentialAlan/lila,arex1337/lila,JimmyMow/lila,luanlv/lila,Enigmahack/lila,r0k3/lila,Unihedro/lila,bjhaid/lila,arex1337/lila,systemovich/lila,JimmyMow/lila,pavelo65/lila,Enigmahack/lila,arex1337/lila,elioair/lila,bjhaid/lila,bjhaid/lila,systemovich/lila,systemovich/lila,pavelo65/lila,Happy0/lila,ccampo133/lila,bjhaid/lila,ccampo133/lila,Unihedro/lila,clarkerubber/lila,JimmyMow/lila,pawank/lila,ccampo133/lila,r0k3/lila,Enigmahack/lila,Happy0/lila,luanlv/lila,Unihedro/lila,abougouffa/lila,clarkerubber/lila,abougouffa/lila,elioair/lila,samuel-soubeyran/lila,clarkerubber/lila,arex1337/lila,TangentialAlan/lila,bjhaid/lila,TangentialAlan/lila,pavelo65/lila,Unihedro/lila,Unihedro/lila,abougouffa/lila,abougouffa/lila,r0k3/lila,r0k3/lila,elioair/lila,clarkerubber/lila,terokinnunen/lila,arex1337/lila,Happy0/lila,luanlv/lila,pawank/lila,samuel-soubeyran/lila,r0k3/lila,Happy0/lila,clarkerubber/lila,systemovich/lila,luanlv/lila,elioair/lila,Happy0/lila,TangentialAlan/lila,JimmyMow/lila,pavelo65/lila,JimmyMow/lila,clarkerubber/lila,TangentialAlan/lila,terokinnunen/lila
|
19d20c8ead59f276bd655a9e8ab9ea6481240cf2
|
Makefile.as
|
Makefile.as
|
# Makefile to rebuild SM64 split image
################ Target Executable and Sources ###############
# TARGET is used to specify prefix in all build artifacts including
# output ROM is $(TARGET).z64
TARGET = sm64
# BUILD_DIR is location where all build artifacts are placed
BUILD_DIR = build
##################### Compiler Options #######################
CROSS = mips64-elf-
AS = $(CROSS)as
LD = $(CROSS)ld
OBJDUMP = $(CROSS)objdump
OBJCOPY = $(CROSS)objcopy
ASFLAGS = -mtune=vr4300 -march=vr4300
LDFLAGS = -T $(LD_SCRIPT) -Map $(BUILD_DIR)/sm64.map
####################### Other Tools #########################
# N64 tools
TOOLS_DIR = .
MIO0TOOL = $(TOOLS_DIR)/mio0
N64CKSUM = $(TOOLS_DIR)/n64cksum
N64GRAPHICS = $(TOOLS_DIR)/n64graphics
EMULATOR = mupen64plus
EMU_FLAGS = --noosd --verbose
######################## Targets #############################
default: all
# file dependencies generated by splitter
MAKEFILE_GEN = gen/Makefile.gen
include $(MAKEFILE_GEN)
all: $(TARGET).gen.z64
clean:
rm -f $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).o $(BUILD_DIR)/$(TARGET).bin $(TARGET).v64
$(MIO0_DIR)/%.mio0: $(MIO0_DIR)/%.bin
$(MIO0TOOL) $< $@
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
$(BUILD_DIR)/$(TARGET).o: gen/$(TARGET).s Makefile.as $(MAKEFILE_GEN) $(MIO0_FILES) $(LEVEL_FILES) | $(BUILD_DIR)
$(AS) $(ASFLAGS) -o $@ $<
$(BUILD_DIR)/$(TARGET).elf: $(BUILD_DIR)/$(TARGET).o $(LD_SCRIPT)
$(LD) $(LDFLAGS) -o $@ $< $(LIBS)
$(BUILD_DIR)/$(TARGET).bin: $(BUILD_DIR)/$(TARGET).elf
$(OBJCOPY) $< $@ -O binary
# final z64 updates checksum
$(TARGET).gen.z64: $(BUILD_DIR)/$(TARGET).bin
$(N64CKSUM) $< $@
$(BUILD_DIR)/$(TARGET).gen.hex: $(TARGET).gen.z64
xxd $< > $@
$(BUILD_DIR)/$(TARGET).objdump: $(BUILD_DIR)/$(TARGET).elf
$(OBJDUMP) -D $< > $@
diff: $(BUILD_DIR)/$(TARGET).gen.hex
diff sm64.hex $< | wc -l
test: $(TARGET).gen.z64
$(EMULATOR) $(EMU_FLAGS) $<
.PHONY: all clean default diff test
|
# Makefile to rebuild SM64 split image
################ Target Executable and Sources ###############
# TARGET is used to specify prefix in all build artifacts including
# output ROM is $(TARGET).z64
TARGET = sm64
# BUILD_DIR is location where all build artifacts are placed
BUILD_DIR = build
##################### Compiler Options #######################
CROSS = mips64-elf-
AS = $(CROSS)as
LD = $(CROSS)ld
OBJDUMP = $(CROSS)objdump
OBJCOPY = $(CROSS)objcopy
ASFLAGS = -mtune=vr4300 -march=vr4300
LDFLAGS = -T $(LD_SCRIPT) -Map $(BUILD_DIR)/sm64.map
####################### Other Tools #########################
# N64 tools
TOOLS_DIR = .
MIO0TOOL = $(TOOLS_DIR)/mio0
N64CKSUM = $(TOOLS_DIR)/n64cksum
N64GRAPHICS = $(TOOLS_DIR)/n64graphics
EMULATOR = mupen64plus
EMU_FLAGS = --noosd
######################## Targets #############################
default: all
# file dependencies generated by splitter
MAKEFILE_GEN = gen/Makefile.gen
include $(MAKEFILE_GEN)
all: $(TARGET).gen.z64
clean:
rm -f $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).o $(BUILD_DIR)/$(TARGET).bin $(TARGET).v64
$(MIO0_DIR)/%.mio0: $(MIO0_DIR)/%.bin
$(MIO0TOOL) $< $@
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
$(BUILD_DIR)/$(TARGET).o: gen/$(TARGET).s Makefile.as $(MAKEFILE_GEN) $(MIO0_FILES) $(LEVEL_FILES) | $(BUILD_DIR)
$(AS) $(ASFLAGS) -o $@ $<
$(BUILD_DIR)/$(TARGET).elf: $(BUILD_DIR)/$(TARGET).o $(LD_SCRIPT)
$(LD) $(LDFLAGS) -o $@ $< $(LIBS)
$(BUILD_DIR)/$(TARGET).bin: $(BUILD_DIR)/$(TARGET).elf
$(OBJCOPY) $< $@ -O binary
# final z64 updates checksum
$(TARGET).gen.z64: $(BUILD_DIR)/$(TARGET).bin
$(N64CKSUM) $< $@
$(BUILD_DIR)/$(TARGET).gen.hex: $(TARGET).gen.z64
xxd $< > $@
$(BUILD_DIR)/$(TARGET).objdump: $(BUILD_DIR)/$(TARGET).elf
$(OBJDUMP) -D $< > $@
diff: $(BUILD_DIR)/$(TARGET).gen.hex
diff sm64.hex $< | wc -l
test: $(TARGET).gen.z64
$(EMULATOR) $(EMU_FLAGS) $<
.PHONY: all clean default diff test
|
Remove verbose emulator flag
|
Remove verbose emulator flag
|
ActionScript
|
mit
|
queueRAM/sm64tools,queueRAM/sm64tools
|
435f8cdbd8b27bddeb5994d1b8c4590e4e909a2b
|
exporter/src/main/as/flump/xfl/XflLibrary.as
|
exporter/src/main/as/flump/xfl/XflLibrary.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flash.utils.Dictionary;
import flump.executor.load.LoadedSwf;
import flump.export.Atlas;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
import flump.mold.LibraryMold;
import flump.mold.MovieMold;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.Set;
import com.threerings.util.Sets;
public class XflLibrary
{
/**
* When an exported movie contains an unexported movie, it gets assigned a generated symbol
* name with this prefix.
*/
public static const IMPLICIT_PREFIX :String = "~";
public var swf :LoadedSwf;
public var frameRate :Number;
// The MD5 of the published library SWF
public var md5 :String;
public var location :String;
public const movies :Vector.<MovieMold> = new Vector.<MovieMold>();
public const textures :Vector.<XflTexture> = new Vector.<XflTexture>();
public function XflLibrary(location :String) {
this.location = location;
}
public function get (id :String, requiredType :Class=null) :* {
const result :* = _ids[id];
if (result === undefined) throw new Error("Unknown library item '" + id + "'");
else if (requiredType != null) return requiredType(result);
else return result;
}
public function isExported (movie :MovieMold) :Boolean {
return _moldToSymbol.containsKey(movie);
}
public function get publishedMovies () :Vector.<MovieMold> {
const result :Vector.<MovieMold> = new Vector.<MovieMold>();
for each (var movie :MovieMold in _toPublish.toArray) result.push(movie);
return result;
}
public function finishLoading () :void {
for each (var movie :MovieMold in movies) if (isExported(movie)) addToPublished(movie);
}
protected function addToPublished (movie :MovieMold) :void {
if (!_toPublish.add(movie) || movie.flipbook) return;
for each (var layer :LayerMold in movie.layers) {
for each (var kf :KeyframeMold in layer.keyframes) {
if (kf.ref == null) continue;
kf.ref = _libraryNameToId.get(kf.ref);
var item :Object = _ids[kf.ref];
if (item == null) {
addTopLevelError(ParseError.CRIT,
"unrecognized library item '" + kf.ref + "'");
} else if (item is MovieMold) addToPublished(MovieMold(item));
}
}
}
public function createId (mold :Object, libraryName :String, symbol :String) :String {
if (symbol != null) _moldToSymbol.put(mold, symbol);
const id :String = symbol == null ? IMPLICIT_PREFIX + libraryName : symbol;
_libraryNameToId.put(libraryName, id);
_ids[id] = mold;
return id;
}
public function getErrors (sev :String=null) :Vector.<ParseError> {
if (sev == null) return _errors;
const sevOrdinal :int = ParseError.severityToOrdinal(sev);
return _errors.filter(function (err :ParseError, ..._) :Boolean {
return err.sevOrdinal >= sevOrdinal;
});
}
public function get valid () :Boolean { return getErrors(ParseError.CRIT).length == 0; }
public function addTopLevelError(severity :String, message :String, e :Object=null) :void {
addError(location, severity, message, e);
}
public function addError(location :String, severity :String, message :String, e :Object=null) :void {
_errors.push(new ParseError(location, severity, message, e));
}
public function toJSONString (atlases :Vector.<Atlas>, pretty :Boolean=false) :String {
return JSON.stringify(toMold(atlases), null, pretty ? " " : null);
}
public function toMold (atlases :Vector.<Atlas>) :LibraryMold {
const mold :LibraryMold = new LibraryMold();
mold.frameRate = frameRate;
mold.md5 = md5;
mold.movies = movies;
for each (var atlas :Atlas in atlases) mold.atlases.push(atlas.toMold());
return mold;
}
/** Object to symbol name for all exported textures and movies in the library */
protected const _moldToSymbol :Map = Maps.newMapOf(Object);
/** Library name to symbol or generated symbol for all textures and movies in the library */
protected const _libraryNameToId :Map = Maps.newMapOf(String);
/** Exported movies or movies used in exported movies. */
protected const _toPublish :Set = Sets.newSetOf(MovieMold);
/** Symbol or generated symbol to texture or movie. */
protected const _ids :Dictionary = new Dictionary();
protected const _errors :Vector.<ParseError> = new Vector.<ParseError>;
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flash.utils.Dictionary;
import flump.executor.load.LoadedSwf;
import flump.export.Atlas;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
import flump.mold.LibraryMold;
import flump.mold.MovieMold;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.Set;
import com.threerings.util.Sets;
public class XflLibrary
{
/**
* When an exported movie contains an unexported movie, it gets assigned a generated symbol
* name with this prefix.
*/
public static const IMPLICIT_PREFIX :String = "~";
public var swf :LoadedSwf;
public var frameRate :Number;
// The MD5 of the published library SWF
public var md5 :String;
public var location :String;
public const movies :Vector.<MovieMold> = new Vector.<MovieMold>();
public const textures :Vector.<XflTexture> = new Vector.<XflTexture>();
public function XflLibrary(location :String) {
this.location = location;
}
public function get (id :String, requiredType :Class=null) :* {
const result :* = _ids[id];
if (result === undefined) throw new Error("Unknown library item '" + id + "'");
else if (requiredType != null) return requiredType(result);
else return result;
}
public function isExported (movie :MovieMold) :Boolean {
return _moldToSymbol.containsKey(movie);
}
public function get publishedMovies () :Vector.<MovieMold> {
const result :Vector.<MovieMold> = new Vector.<MovieMold>();
for each (var movie :MovieMold in _toPublish.toArray()) result.push(movie);
return result;
}
public function finishLoading () :void {
for each (var movie :MovieMold in movies) if (isExported(movie)) addToPublished(movie);
}
protected function addToPublished (movie :MovieMold) :void {
if (!_toPublish.add(movie) || movie.flipbook) return;
for each (var layer :LayerMold in movie.layers) {
for each (var kf :KeyframeMold in layer.keyframes) {
if (kf.ref == null) continue;
kf.ref = _libraryNameToId.get(kf.ref);
var item :Object = _ids[kf.ref];
if (item == null) {
addTopLevelError(ParseError.CRIT,
"unrecognized library item '" + kf.ref + "'");
} else if (item is MovieMold) addToPublished(MovieMold(item));
}
}
}
public function createId (mold :Object, libraryName :String, symbol :String) :String {
if (symbol != null) _moldToSymbol.put(mold, symbol);
const id :String = symbol == null ? IMPLICIT_PREFIX + libraryName : symbol;
_libraryNameToId.put(libraryName, id);
_ids[id] = mold;
return id;
}
public function getErrors (sev :String=null) :Vector.<ParseError> {
if (sev == null) return _errors;
const sevOrdinal :int = ParseError.severityToOrdinal(sev);
return _errors.filter(function (err :ParseError, ..._) :Boolean {
return err.sevOrdinal >= sevOrdinal;
});
}
public function get valid () :Boolean { return getErrors(ParseError.CRIT).length == 0; }
public function addTopLevelError(severity :String, message :String, e :Object=null) :void {
addError(location, severity, message, e);
}
public function addError(location :String, severity :String, message :String, e :Object=null) :void {
_errors.push(new ParseError(location, severity, message, e));
}
public function toJSONString (atlases :Vector.<Atlas>, pretty :Boolean=false) :String {
return JSON.stringify(toMold(atlases), null, pretty ? " " : null);
}
public function toMold (atlases :Vector.<Atlas>) :LibraryMold {
const mold :LibraryMold = new LibraryMold();
mold.frameRate = frameRate;
mold.md5 = md5;
mold.movies = movies;
for each (var atlas :Atlas in atlases) mold.atlases.push(atlas.toMold());
return mold;
}
/** Object to symbol name for all exported textures and movies in the library */
protected const _moldToSymbol :Map = Maps.newMapOf(Object);
/** Library name to symbol or generated symbol for all textures and movies in the library */
protected const _libraryNameToId :Map = Maps.newMapOf(String);
/** Exported movies or movies used in exported movies. */
protected const _toPublish :Set = Sets.newSetOf(MovieMold);
/** Symbol or generated symbol to texture or movie. */
protected const _ids :Dictionary = new Dictionary();
protected const _errors :Vector.<ParseError> = new Vector.<ParseError>;
}
}
|
fix movie publishing
|
fix movie publishing
|
ActionScript
|
mit
|
mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,tconkling/flump
|
4805bcd369f55dd54f0941fbaebeffdc66e5d62a
|
exporter/src/main/as/flump/xfl/XflLibrary.as
|
exporter/src/main/as/flump/xfl/XflLibrary.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.xfl {
import com.adobe.crypto.MD5;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.Set;
import com.threerings.util.Sets;
import com.threerings.util.XmlUtil;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flump.SwfTexture;
import flump.Util;
import flump.executor.Executor;
import flump.executor.Future;
import flump.executor.FutureTask;
import flump.executor.load.LoadedSwf;
import flump.executor.load.SwfLoader;
import flump.export.Atlas;
import flump.export.ExportConf;
import flump.export.Files;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
import flump.mold.LibraryMold;
import flump.mold.MovieMold;
import flump.mold.TextureGroupMold;
public class XflLibrary
{
use namespace xflns;
/**
* When an exported movie contains an unexported movie, it gets assigned a generated symbol
* name with this prefix.
*/
public static const IMPLICIT_PREFIX :String = "~";
public var swf :LoadedSwf;
public var frameRate :Number;
public var backgroundColor :int;
// The MD5 of the published library SWF
public var md5 :String;
public var location :String;
public const movies :Vector.<MovieMold> = new <MovieMold>[];
public const textures :Vector.<XflTexture> = new <XflTexture>[];
public function XflLibrary (location :String) {
this.location = location;
}
public function getItem (id :String, requiredType :Class=null) :* {
const result :* = _idToItem[id];
if (result === undefined) throw new Error("Unknown library item '" + id + "'");
else if (requiredType != null) return requiredType(result);
else return result;
}
public function isExported (movie :MovieMold) :Boolean {
return _moldToSymbol.containsKey(movie);
}
public function get publishedMovies () :Vector.<MovieMold> {
const result :Vector.<MovieMold> = new <MovieMold>[];
for each (var movie :MovieMold in _toPublish.toArray().sortOn("id")) result.push(movie);
return result;
}
public function finishLoading () :void {
var movie :MovieMold = null;
// Parse all un-exported movies that are referenced by the exported movies.
for (var ii :int = 0; ii < movies.length; ++ii) {
movie = movies[ii];
for each (var symbolName :String in XflMovie.getSymbolNames(movie).toArray()) {
var xml :XML = _unexportedMovies.remove(symbolName);
if (xml != null) parseMovie(xml);
}
}
for each (movie in movies) if (isExported(movie)) prepareForPublishing(movie);
}
protected function prepareForPublishing (movie :MovieMold) :void {
if (!_toPublish.add(movie)) return;
const numMovieFrames :int = movie.frames;
for each (var layer :LayerMold in movie.layers) {
// If the layer's timeline is shorter than its movie's timeline, and it doesn't end in
// an empty keyframe, we add an empty keyframe at the end so that the layer will be
// "invisible" for the remainder of the movie's timeline. This matches Flash's behavior.
if (layer.frames < numMovieFrames) {
var lastKeyframe :KeyframeMold = (layer.keyframes.length > 0 ?
layer.keyframes[layer.keyframes.length - 1] : null);
if (lastKeyframe == null || !lastKeyframe.isEmpty) {
var emptyKeyframe :KeyframeMold = new KeyframeMold();
emptyKeyframe.index = layer.frames + 1;
emptyKeyframe.duration = 1;
layer.keyframes.push(emptyKeyframe);
}
}
for each (var kf :KeyframeMold in layer.keyframes) {
var swfTexture :SwfTexture = null;
if (movie.flipbook) {
try {
swfTexture = SwfTexture.fromFlipbook(this, movie, kf.index)
} catch (e :Error) {
addTopLevelError(ParseError.CRIT, "Error creating flipbook texture from '" + movie.id + "'");
swfTexture = null;
}
} else {
if (kf.ref == null) continue;
kf.ref = _libraryNameToId.get(kf.ref);
var item :Object = _idToItem[kf.ref];
if (item == null) {
addTopLevelError(ParseError.CRIT,
"unrecognized library item '" + kf.ref + "'");
} else if (item is MovieMold) {
prepareForPublishing(MovieMold(item));
} else if (item is XflTexture) {
const tex :XflTexture = XflTexture(item);
try {
swfTexture = SwfTexture.fromTexture(this.swf, tex);
} catch (e :Error) {
addTopLevelError(ParseError.CRIT, "Error creating texture '" + tex.symbol + "'");
swfTexture = null;
}
}
}
if (swfTexture != null) {
// Texture symbols have origins. For texture layer keyframes,
// we combine the texture's origin with the keyframe's pivot point.
kf.pivotX += swfTexture.origin.x;
kf.pivotY += swfTexture.origin.y;
}
}
}
}
public function createId (item :Object, libraryName :String, symbol :String) :String {
if (symbol != null) _moldToSymbol.put(item, symbol);
const id :String = symbol == null ? IMPLICIT_PREFIX + libraryName : symbol;
_libraryNameToId.put(libraryName, id);
_idToItem[id] = item;
return id;
}
public function getErrors (sev :String=null) :Vector.<ParseError> {
if (sev == null) return _errors;
const sevOrdinal :int = ParseError.severityToOrdinal(sev);
return _errors.filter(function (err :ParseError, ..._) :Boolean {
return err.sevOrdinal >= sevOrdinal;
});
}
public function get valid () :Boolean { return getErrors(ParseError.CRIT).length == 0; }
public function addTopLevelError (severity :String, message :String, e :Object=null) :void {
addError(location, severity, message, e);
}
public function addError (location :String, severity :String, message :String, e :Object=null) :void {
_errors.push(new ParseError(location, severity, message, e));
}
public function toJSONString (atlases :Vector.<Atlas>, conf :ExportConf, pretty :Boolean=false) :String {
return JSON.stringify(toMold(atlases, conf), null, pretty ? " " : null);
}
public function toMold (atlases :Vector.<Atlas>, conf :ExportConf) :LibraryMold {
const mold :LibraryMold = new LibraryMold();
mold.frameRate = frameRate;
mold.md5 = md5;
mold.movies = publishedMovies.map(function (movie :MovieMold, ..._) :MovieMold {
return movie.scale(conf.scale);
});
mold.textureGroups = createTextureGroupMolds(atlases);
return mold;
}
public function loadSWF (path :String, loader :Executor=null) :Future {
const onComplete :FutureTask = new FutureTask();
const swfFile :File = new File(path);
const loadSwfFile :Future = Files.load(swfFile, loader);
loadSwfFile.succeeded.connect(function (data :ByteArray) :void {
md5 = MD5.hashBytes(data);
const loadSwf :Future = new SwfLoader().loadFromBytes(data);
loadSwf.succeeded.connect(function (loadedSwf :LoadedSwf) :void {
swf = loadedSwf;
});
loadSwf.failed.connect(function (error :Error) :void {
addTopLevelError(ParseError.CRIT, error.message, error);
});
loadSwf.completed.connect(onComplete.succeed);
});
loadSwfFile.failed.connect(function (error :Error) :void {
addTopLevelError(ParseError.CRIT, error.message, error);
onComplete.fail(error);
});
return onComplete;
}
/**
* @returns A list of paths to symbols in this library.
*/
public function parseDocumentFile (fileData :ByteArray, path :String) :Vector.<String> {
const xml :XML = Util.bytesToXML(fileData);
frameRate = XmlUtil.getNumberAttr(xml, "frameRate", 24);
const hex :String = XmlUtil.getStringAttr(xml, "backgroundColor", "#ffffff");
backgroundColor = parseInt(hex.substr(1), 16);
if (xml.media != null) {
for each (var bitmap :XML in xml.media.DOMBitmapItem) {
if (XmlUtil.getBooleanAttr(bitmap, "linkageExportForAS", false)) {
textures.push(new XflTexture(this, location, bitmap));
}
}
}
const paths :Vector.<String> = new <String>[];
if (xml.symbols != null) {
for each (var symbolXmlPath :XML in xml.symbols.Include) {
paths.push("LIBRARY/" + XmlUtil.getStringAttr(symbolXmlPath, "href"));
}
}
return paths;
}
public function parseLibraryFile (fileData :ByteArray, path :String) :void {
const xml :XML = Util.bytesToXML(fileData);
if (xml.name().localName != "DOMSymbolItem") {
addTopLevelError(ParseError.DEBUG,
"Skipping file since its root element isn't DOMSymbolItem");
return;
} else if (XmlUtil.getStringAttr(xml, "symbolType", "") == "graphic") {
addTopLevelError(ParseError.DEBUG, "Skipping file because symbolType=graphic");
return;
}
const isSprite :Boolean = XmlUtil.getBooleanAttr(xml, "isSpriteSubclass", false);
log.debug("Parsing for library", "file", path, "isSprite", isSprite);
try {
if (isSprite) {
// if "export in first frame" is not set, we won't be able to load the texture
// from the swf.
// TODO: remove this restriction by loading the entire swf before reading textures?
if (!XmlUtil.getBooleanAttr(xml, "linkageExportInFirstFrame", true)) {
addError(location + ":" + XmlUtil.getStringAttr(xml, "linkageClassName"),
ParseError.CRIT, "\"Export in frame 1\" must be set");
return;
}
var texture :XflTexture = new XflTexture(this, location, xml);
if (texture.isValid(swf)) textures.push(texture);
else addError(location + ":" + texture.symbol, ParseError.CRIT, "Sprite is empty");
} else {
// It's a movie. If it's exported, we parse it now.
// Else, we save it for possible parsing later.
// (Un-exported movies that are not referenced will not be published.)
if (XflMovie.isExported(xml)) parseMovie(xml);
else _unexportedMovies.put(XflMovie.getName(xml), xml);
}
} catch (e :Error) {
var type :String = isSprite ? "sprite" : "movie";
addTopLevelError(ParseError.CRIT, "Unable to parse " + type + " in " + path, e);
log.error("Unable to parse " + path, e);
}
}
protected function parseMovie (xml :XML) :void {
movies.push(XflMovie.parse(this, xml));
}
/** Creates TextureGroupMolds from a list of Atlases */
protected static function createTextureGroupMolds (atlases :Vector.<Atlas>) :Vector.<TextureGroupMold> {
const groups :Vector.<TextureGroupMold> = new <TextureGroupMold>[];
function getGroup (scaleFactor :int) :TextureGroupMold {
for each (var group :TextureGroupMold in groups) {
if (group.scaleFactor == scaleFactor) {
return group;
}
}
group = new TextureGroupMold();
group.scaleFactor = scaleFactor;
groups.push(group);
return group;
}
for each (var atlas :Atlas in atlases) {
var group :TextureGroupMold = getGroup(atlas.scaleFactor);
group.atlases.push(atlas.toMold());
}
return groups;
}
/** Library name to XML for movies in the XFL that are not marked for export */
protected const _unexportedMovies :Map = Maps.newMapOf(String);
/** Object to symbol name for all exported textures and movies in the library */
protected const _moldToSymbol :Map = Maps.newMapOf(Object);
/** Library name to symbol or generated symbol for all textures and movies in the library */
protected const _libraryNameToId :Map = Maps.newMapOf(String);
/** Exported movies or movies used in exported movies. */
protected const _toPublish :Set = Sets.newSetOf(MovieMold);
/** Symbol or generated symbol to texture or movie. */
protected const _idToItem :Dictionary = new Dictionary();
protected const _errors :Vector.<ParseError> = new <ParseError>[];
private static const log :Log = Log.getLog(XflLibrary);
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.xfl {
import com.adobe.crypto.MD5;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import com.threerings.util.Set;
import com.threerings.util.Sets;
import com.threerings.util.XmlUtil;
import flash.filesystem.File;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flump.SwfTexture;
import flump.Util;
import flump.executor.Executor;
import flump.executor.Future;
import flump.executor.FutureTask;
import flump.executor.load.LoadedSwf;
import flump.executor.load.SwfLoader;
import flump.export.Atlas;
import flump.export.ExportConf;
import flump.export.Files;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
import flump.mold.LibraryMold;
import flump.mold.MovieMold;
import flump.mold.TextureGroupMold;
public class XflLibrary
{
use namespace xflns;
/**
* When an exported movie contains an unexported movie, it gets assigned a generated symbol
* name with this prefix.
*/
public static const IMPLICIT_PREFIX :String = "~";
public var swf :LoadedSwf;
public var frameRate :Number;
public var backgroundColor :int;
// The MD5 of the published library SWF
public var md5 :String;
public var location :String;
public const movies :Vector.<MovieMold> = new <MovieMold>[];
public const textures :Vector.<XflTexture> = new <XflTexture>[];
public function XflLibrary (location :String) {
this.location = location;
}
public function getItem (id :String, requiredType :Class=null) :* {
const result :* = _idToItem[id];
if (result === undefined) throw new Error("Unknown library item '" + id + "'");
else if (requiredType != null) return requiredType(result);
else return result;
}
public function isExported (movie :MovieMold) :Boolean {
return _moldToSymbol.containsKey(movie);
}
public function get publishedMovies () :Vector.<MovieMold> {
const result :Vector.<MovieMold> = new <MovieMold>[];
for each (var movie :MovieMold in _toPublish.toArray().sortOn("id")) result.push(movie);
return result;
}
public function finishLoading () :void {
var movie :MovieMold = null;
// Parse all un-exported movies that are referenced by the exported movies.
for (var ii :int = 0; ii < movies.length; ++ii) {
movie = movies[ii];
for each (var symbolName :String in XflMovie.getSymbolNames(movie).toArray()) {
var xml :XML = _unexportedMovies.remove(symbolName);
if (xml != null) parseMovie(xml);
}
}
for each (movie in movies) if (isExported(movie)) prepareForPublishing(movie);
}
protected function prepareForPublishing (movie :MovieMold) :void {
if (!_toPublish.add(movie)) return;
const numMovieFrames :int = movie.frames;
for each (var layer :LayerMold in movie.layers) {
// If the layer's timeline is shorter than its movie's timeline, and it doesn't end in
// an empty keyframe, we add an empty keyframe at the end so that the layer will be
// "invisible" for the remainder of the movie's timeline. This matches Flash's behavior.
if (layer.frames < numMovieFrames) {
var lastKeyframe :KeyframeMold = (layer.keyframes.length > 0 ?
layer.keyframes[layer.keyframes.length - 1] : null);
if (lastKeyframe == null || !lastKeyframe.isEmpty) {
var emptyKeyframe :KeyframeMold = new KeyframeMold();
emptyKeyframe.index = layer.frames;
emptyKeyframe.duration = 1;
layer.keyframes.push(emptyKeyframe);
}
}
for each (var kf :KeyframeMold in layer.keyframes) {
var swfTexture :SwfTexture = null;
if (movie.flipbook) {
try {
swfTexture = SwfTexture.fromFlipbook(this, movie, kf.index)
} catch (e :Error) {
addTopLevelError(ParseError.CRIT, "Error creating flipbook texture from '" + movie.id + "'");
swfTexture = null;
}
} else {
if (kf.ref == null) continue;
kf.ref = _libraryNameToId.get(kf.ref);
var item :Object = _idToItem[kf.ref];
if (item == null) {
addTopLevelError(ParseError.CRIT,
"unrecognized library item '" + kf.ref + "'");
} else if (item is MovieMold) {
prepareForPublishing(MovieMold(item));
} else if (item is XflTexture) {
const tex :XflTexture = XflTexture(item);
try {
swfTexture = SwfTexture.fromTexture(this.swf, tex);
} catch (e :Error) {
addTopLevelError(ParseError.CRIT, "Error creating texture '" + tex.symbol + "'");
swfTexture = null;
}
}
}
if (swfTexture != null) {
// Texture symbols have origins. For texture layer keyframes,
// we combine the texture's origin with the keyframe's pivot point.
kf.pivotX += swfTexture.origin.x;
kf.pivotY += swfTexture.origin.y;
}
}
}
}
public function createId (item :Object, libraryName :String, symbol :String) :String {
if (symbol != null) _moldToSymbol.put(item, symbol);
const id :String = symbol == null ? IMPLICIT_PREFIX + libraryName : symbol;
_libraryNameToId.put(libraryName, id);
_idToItem[id] = item;
return id;
}
public function getErrors (sev :String=null) :Vector.<ParseError> {
if (sev == null) return _errors;
const sevOrdinal :int = ParseError.severityToOrdinal(sev);
return _errors.filter(function (err :ParseError, ..._) :Boolean {
return err.sevOrdinal >= sevOrdinal;
});
}
public function get valid () :Boolean { return getErrors(ParseError.CRIT).length == 0; }
public function addTopLevelError (severity :String, message :String, e :Object=null) :void {
addError(location, severity, message, e);
}
public function addError (location :String, severity :String, message :String, e :Object=null) :void {
_errors.push(new ParseError(location, severity, message, e));
}
public function toJSONString (atlases :Vector.<Atlas>, conf :ExportConf, pretty :Boolean=false) :String {
return JSON.stringify(toMold(atlases, conf), null, pretty ? " " : null);
}
public function toMold (atlases :Vector.<Atlas>, conf :ExportConf) :LibraryMold {
const mold :LibraryMold = new LibraryMold();
mold.frameRate = frameRate;
mold.md5 = md5;
mold.movies = publishedMovies.map(function (movie :MovieMold, ..._) :MovieMold {
return movie.scale(conf.scale);
});
mold.textureGroups = createTextureGroupMolds(atlases);
return mold;
}
public function loadSWF (path :String, loader :Executor=null) :Future {
const onComplete :FutureTask = new FutureTask();
const swfFile :File = new File(path);
const loadSwfFile :Future = Files.load(swfFile, loader);
loadSwfFile.succeeded.connect(function (data :ByteArray) :void {
md5 = MD5.hashBytes(data);
const loadSwf :Future = new SwfLoader().loadFromBytes(data);
loadSwf.succeeded.connect(function (loadedSwf :LoadedSwf) :void {
swf = loadedSwf;
});
loadSwf.failed.connect(function (error :Error) :void {
addTopLevelError(ParseError.CRIT, error.message, error);
});
loadSwf.completed.connect(onComplete.succeed);
});
loadSwfFile.failed.connect(function (error :Error) :void {
addTopLevelError(ParseError.CRIT, error.message, error);
onComplete.fail(error);
});
return onComplete;
}
/**
* @returns A list of paths to symbols in this library.
*/
public function parseDocumentFile (fileData :ByteArray, path :String) :Vector.<String> {
const xml :XML = Util.bytesToXML(fileData);
frameRate = XmlUtil.getNumberAttr(xml, "frameRate", 24);
const hex :String = XmlUtil.getStringAttr(xml, "backgroundColor", "#ffffff");
backgroundColor = parseInt(hex.substr(1), 16);
if (xml.media != null) {
for each (var bitmap :XML in xml.media.DOMBitmapItem) {
if (XmlUtil.getBooleanAttr(bitmap, "linkageExportForAS", false)) {
textures.push(new XflTexture(this, location, bitmap));
}
}
}
const paths :Vector.<String> = new <String>[];
if (xml.symbols != null) {
for each (var symbolXmlPath :XML in xml.symbols.Include) {
paths.push("LIBRARY/" + XmlUtil.getStringAttr(symbolXmlPath, "href"));
}
}
return paths;
}
public function parseLibraryFile (fileData :ByteArray, path :String) :void {
const xml :XML = Util.bytesToXML(fileData);
if (xml.name().localName != "DOMSymbolItem") {
addTopLevelError(ParseError.DEBUG,
"Skipping file since its root element isn't DOMSymbolItem");
return;
} else if (XmlUtil.getStringAttr(xml, "symbolType", "") == "graphic") {
addTopLevelError(ParseError.DEBUG, "Skipping file because symbolType=graphic");
return;
}
const isSprite :Boolean = XmlUtil.getBooleanAttr(xml, "isSpriteSubclass", false);
log.debug("Parsing for library", "file", path, "isSprite", isSprite);
try {
if (isSprite) {
// if "export in first frame" is not set, we won't be able to load the texture
// from the swf.
// TODO: remove this restriction by loading the entire swf before reading textures?
if (!XmlUtil.getBooleanAttr(xml, "linkageExportInFirstFrame", true)) {
addError(location + ":" + XmlUtil.getStringAttr(xml, "linkageClassName"),
ParseError.CRIT, "\"Export in frame 1\" must be set");
return;
}
var texture :XflTexture = new XflTexture(this, location, xml);
if (texture.isValid(swf)) textures.push(texture);
else addError(location + ":" + texture.symbol, ParseError.CRIT, "Sprite is empty");
} else {
// It's a movie. If it's exported, we parse it now.
// Else, we save it for possible parsing later.
// (Un-exported movies that are not referenced will not be published.)
if (XflMovie.isExported(xml)) parseMovie(xml);
else _unexportedMovies.put(XflMovie.getName(xml), xml);
}
} catch (e :Error) {
var type :String = isSprite ? "sprite" : "movie";
addTopLevelError(ParseError.CRIT, "Unable to parse " + type + " in " + path, e);
log.error("Unable to parse " + path, e);
}
}
protected function parseMovie (xml :XML) :void {
movies.push(XflMovie.parse(this, xml));
}
/** Creates TextureGroupMolds from a list of Atlases */
protected static function createTextureGroupMolds (atlases :Vector.<Atlas>) :Vector.<TextureGroupMold> {
const groups :Vector.<TextureGroupMold> = new <TextureGroupMold>[];
function getGroup (scaleFactor :int) :TextureGroupMold {
for each (var group :TextureGroupMold in groups) {
if (group.scaleFactor == scaleFactor) {
return group;
}
}
group = new TextureGroupMold();
group.scaleFactor = scaleFactor;
groups.push(group);
return group;
}
for each (var atlas :Atlas in atlases) {
var group :TextureGroupMold = getGroup(atlas.scaleFactor);
group.atlases.push(atlas.toMold());
}
return groups;
}
/** Library name to XML for movies in the XFL that are not marked for export */
protected const _unexportedMovies :Map = Maps.newMapOf(String);
/** Object to symbol name for all exported textures and movies in the library */
protected const _moldToSymbol :Map = Maps.newMapOf(Object);
/** Library name to symbol or generated symbol for all textures and movies in the library */
protected const _libraryNameToId :Map = Maps.newMapOf(String);
/** Exported movies or movies used in exported movies. */
protected const _toPublish :Set = Sets.newSetOf(MovieMold);
/** Symbol or generated symbol to texture or movie. */
protected const _idToItem :Dictionary = new Dictionary();
protected const _errors :Vector.<ParseError> = new <ParseError>[];
private static const log :Log = Log.getLog(XflLibrary);
}
}
|
Fix off-by-1 in empty keyframe creation
|
Fix off-by-1 in empty keyframe creation
|
ActionScript
|
mit
|
mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump,mathieuanthoine/flump
|
3c7b0426a2c1d5b210cbbe9350ff821ac71788c7
|
runtime/src/main/as/flump/xfl/XflMovie.as
|
runtime/src/main/as/flump/xfl/XflMovie.as
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flash.utils.Dictionary;
public class XflMovie extends XflTopLevelComponent
{
use namespace xflns;
public var md5 :String;
public var libraryItem :String;
public var symbol :String;
public var layers :Array;
public function XflMovie (baseLocation :String, xml :XML, md5 :String) {
const converter :XmlConverter = new XmlConverter(xml);
libraryItem = converter.getStringAttr("name");
super(baseLocation + ":" + libraryItem);
this.md5 = md5;
symbol = converter.getStringAttr("linkageClassName", null);
const layerEls :XMLList = xml.timeline.DOMTimeline[0].layers.DOMLayer;
if (new XmlConverter(layerEls[0]).getStringAttr("name") == "flipbook") {
layers = [new XflLayer(location, layerEls[0], _errors, true)];
if (symbol == null) {
addError(ParseError.CRIT, "Flipbook movie '" + libraryItem + "' not exported");
}
} else {
layers = new Array();
for each (var layerEl :XML in layerEls) {
layers.push(new XflLayer(location, layerEl, _errors, false));
}
}
}
public function checkSymbols (lookup :Dictionary) :void {
if (flipbook && !lookup.hasOwnProperty(symbol)) {
addError(ParseError.CRIT, "Flipbook movie '" + symbol + "' not exported");
} else for each (var layer :XflLayer in layers) layer.checkSymbols(lookup);
}
public function get flipbook () :Boolean { return layers[0].flipbook; }
}
}
|
//
// Flump - Copyright 2012 Three Rings Design
package flump.xfl {
import flash.utils.Dictionary;
public class XflMovie extends XflTopLevelComponent
{
use namespace xflns;
public var md5 :String;
public var libraryItem :String;
public var symbol :String;
public var layers :Array;
public function XflMovie (baseLocation :String, xml :XML, md5 :String) {
const converter :XmlConverter = new XmlConverter(xml);
libraryItem = converter.getStringAttr("name");
super(baseLocation + ":" + libraryItem);
this.md5 = md5;
symbol = converter.getStringAttr("linkageClassName", null);
const layerEls :XMLList = xml.timeline.DOMTimeline[0].layers.DOMLayer;
if (new XmlConverter(layerEls[0]).getStringAttr("name") == "flipbook") {
layers = [new XflLayer(location, layerEls[0], _errors, true)];
if (symbol == null) {
addError(ParseError.CRIT, "Flipbook movie '" + libraryItem + "' not exported");
}
} else {
layers = new Array();
for each (var layerEl :XML in layerEls) {
layers.unshift(new XflLayer(location, layerEl, _errors, false));
}
}
}
public function checkSymbols (lookup :Dictionary) :void {
if (flipbook && !lookup.hasOwnProperty(symbol)) {
addError(ParseError.CRIT, "Flipbook movie '" + symbol + "' not exported");
} else for each (var layer :XflLayer in layers) layer.checkSymbols(lookup);
}
public function get flipbook () :Boolean { return layers[0].flipbook; }
}
}
|
Order layers for correct display.
|
Order layers for correct display.
|
ActionScript
|
mit
|
mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump,tconkling/flump,tconkling/flump,mathieuanthoine/flump,funkypandagame/flump
|
f6e7d0c955d5621ee9f188b91ae229f372e35263
|
src/org/mangui/hls/HLSJS.as
|
src/org/mangui/hls/HLSJS.as
|
package org.mangui.hls
{
import flash.external.ExternalInterface;
import org.hola.ZExternalInterface;
import org.hola.JSAPI;
import org.hola.HSettings;
import org.mangui.hls.event.HLSEvent;
public class HLSJS
{
private static var _inited:Boolean = false;
private static var _duration:Number;
private static var _bandwidth:Number = -1;
private static var _url:String;
private static var _hls:HLS;
public static function init():void{
if (_inited || !ZExternalInterface.avail())
return;
_inited = true;
JSAPI.init();
ExternalInterface.addCallback("hola_version", hola_version);
ExternalInterface.addCallback("hola_hls_get_video_url",
hola_hls_get_video_url);
ExternalInterface.addCallback("hola_hls_get_position",
hola_hls_get_position);
ExternalInterface.addCallback("hola_hls_get_duration",
hola_hls_get_duration);
ExternalInterface.addCallback("hola_hls_get_buffer_sec",
hola_hls_get_buffer_sec);
ExternalInterface.addCallback("hola_hls_get_state",
hola_hls_get_state);
ExternalInterface.addCallback("hola_hls_get_levels",
hola_hls_get_levels);
ExternalInterface.addCallback("hola_hls_get_level",
hola_hls_get_level);
ExternalInterface.addCallback("hola_setBandwidth",
hola_setBandwidth);
}
public static function HLSnew(hls:HLS):void{
_hls = hls;
// notify js events
hls.addEventListener(HLSEvent.MANIFEST_LOADING, on_event);
hls.addEventListener(HLSEvent.MANIFEST_PARSED, on_event);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING_ABORTED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADED, on_event);
hls.addEventListener(HLSEvent.LEVEL_SWITCH, on_event);
hls.addEventListener(HLSEvent.LEVEL_ENDLIST, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOAD_EMERGENCY_ABORTED,
on_event);
hls.addEventListener(HLSEvent.FRAGMENT_PLAYING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_SKIPPED, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACK_SWITCH, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADED, on_event);
hls.addEventListener(HLSEvent.TAGS_LOADED, on_event);
hls.addEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.WARNING, on_event);
hls.addEventListener(HLSEvent.ERROR, on_event);
hls.addEventListener(HLSEvent.MEDIA_TIME, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_STATE, on_event);
hls.addEventListener(HLSEvent.SEEK_STATE, on_event);
hls.addEventListener(HLSEvent.STREAM_TYPE_DID_CHANGE, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, on_event);
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_event);
hls.addEventListener(HLSEvent.ID3_UPDATED, on_event);
hls.addEventListener(HLSEvent.FPS_DROP, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_LEVEL_CAPPING, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_SMOOTH_LEVEL_SWITCH,
on_event);
hls.addEventListener(HLSEvent.LIVE_LOADING_STALLED, on_event);
// track duration events
hls.addEventListener(HLSEvent.MANIFEST_LOADED, on_manifest_loaded);
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_playlist_duration_updated);
// track playlist url
hls.addEventListener(HLSEvent.MANIFEST_LOADING, on_manifest_loading);
JSAPI.postMessage2({id: 'flashls.hlsNew', hls_id: hls.id});
}
public static function HLSdispose(hls:HLS):void{
JSAPI.postMessage2({id: 'flashls.hlsDispose', hls_id: hls.id});
_hls = null;
}
public static function get bandwidth():Number{
return HSettings.hls_mode ? _bandwidth : -1;
}
private static function on_manifest_loaded(e:HLSEvent):void{
_duration = e.levels[_hls.startLevel].duration;
}
private static function on_playlist_duration_updated(e:HLSEvent):void{
_duration = e.duration;
}
private static function on_manifest_loading(e:HLSEvent):void{
_url = e.url;
}
private static function on_event(e:HLSEvent):void{
JSAPI.postMessage2({id: 'flashls.'+e.type, hls_id: _hls.id,
url: e.url, level: e.level, duration: e.duration, levels: e.levels,
error: e.error, loadMetrics: e.loadMetrics,
playMetrics: e.playMetrics, mediatime: e.mediatime, state: e.state,
audioTrack: e.audioTrack, streamType: e.streamType});
}
private static function hola_version():Object{
return {
flashls_version: '0.4.2.1',
patch_version: '2.0.1'
};
}
private static function hola_hls_get_video_url():String{
return _url;
}
private static function hola_hls_get_position():Number{
return _hls.position;
}
private static function hola_hls_get_duration():Number{
return _duration;
}
private static function hola_hls_get_buffer_sec():Number{
return _hls.stream.bufferLength;
}
private static function hola_hls_get_state():String{
return _hls.playbackState;
}
private static function hola_hls_get_levels():Object{
return _hls.levels;
}
private static function hola_hls_get_level():Number{
return _hls.loadLevel;
}
private static function hola_setBandwidth(bandwidth:Number):void{
_bandwidth = bandwidth;
}
}
}
|
package org.mangui.hls
{
import flash.external.ExternalInterface;
import org.hola.ZExternalInterface;
import org.hola.JSAPI;
import org.hola.HSettings;
import org.mangui.hls.event.HLSEvent;
public class HLSJS
{
private static var _inited:Boolean = false;
private static var _duration:Number;
private static var _bandwidth:Number = -1;
private static var _url:String;
private static var _hls:HLS;
public static function init():void{
if (_inited || !ZExternalInterface.avail())
return;
_inited = true;
JSAPI.init();
ExternalInterface.addCallback("hola_version", hola_version);
ExternalInterface.addCallback("hola_hls_get_video_url",
hola_hls_get_video_url);
ExternalInterface.addCallback("hola_hls_get_position",
hola_hls_get_position);
ExternalInterface.addCallback("hola_hls_get_duration",
hola_hls_get_duration);
ExternalInterface.addCallback("hola_hls_get_buffer_sec",
hola_hls_get_buffer_sec);
ExternalInterface.addCallback("hola_hls_get_state",
hola_hls_get_state);
ExternalInterface.addCallback("hola_hls_get_levels",
hola_hls_get_levels);
ExternalInterface.addCallback("hola_hls_get_level",
hola_hls_get_level);
ExternalInterface.addCallback("hola_setBandwidth",
hola_setBandwidth);
}
public static function HLSnew(hls:HLS):void{
_hls = hls;
// notify js events
hls.addEventListener(HLSEvent.MANIFEST_LOADING, on_event);
hls.addEventListener(HLSEvent.MANIFEST_PARSED, on_event);
hls.addEventListener(HLSEvent.MANIFEST_LOADED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADING_ABORTED, on_event);
hls.addEventListener(HLSEvent.LEVEL_LOADED, on_event);
hls.addEventListener(HLSEvent.LEVEL_SWITCH, on_event);
hls.addEventListener(HLSEvent.LEVEL_ENDLIST, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_LOAD_EMERGENCY_ABORTED,
on_event);
hls.addEventListener(HLSEvent.FRAGMENT_PLAYING, on_event);
hls.addEventListener(HLSEvent.FRAGMENT_SKIPPED, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACKS_LIST_CHANGE, on_event);
hls.addEventListener(HLSEvent.AUDIO_TRACK_SWITCH, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADING, on_event);
hls.addEventListener(HLSEvent.AUDIO_LEVEL_LOADED, on_event);
hls.addEventListener(HLSEvent.TAGS_LOADED, on_event);
hls.addEventListener(HLSEvent.LAST_VOD_FRAGMENT_LOADED, on_event);
hls.addEventListener(HLSEvent.WARNING, on_event);
hls.addEventListener(HLSEvent.ERROR, on_event);
hls.addEventListener(HLSEvent.MEDIA_TIME, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_STATE, on_event);
hls.addEventListener(HLSEvent.SEEK_STATE, on_event);
hls.addEventListener(HLSEvent.STREAM_TYPE_DID_CHANGE, on_event);
hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, on_event);
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_event);
hls.addEventListener(HLSEvent.ID3_UPDATED, on_event);
hls.addEventListener(HLSEvent.FPS_DROP, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_LEVEL_CAPPING, on_event);
hls.addEventListener(HLSEvent.FPS_DROP_SMOOTH_LEVEL_SWITCH,
on_event);
hls.addEventListener(HLSEvent.LIVE_LOADING_STALLED, on_event);
// track duration events
hls.addEventListener(HLSEvent.MANIFEST_LOADED, on_manifest_loaded);
hls.addEventListener(HLSEvent.PLAYLIST_DURATION_UPDATED,
on_playlist_duration_updated);
// track playlist url
hls.addEventListener(HLSEvent.MANIFEST_LOADING, on_manifest_loading);
JSAPI.postMessage2({id: 'flashls.hlsNew', hls_id: hls.id});
}
public static function HLSdispose(hls:HLS):void{
JSAPI.postMessage2({id: 'flashls.hlsDispose', hls_id: hls.id});
_duration = 0;
_bandwidth = -1;
_url = null;
_hls = null;
}
public static function get bandwidth():Number{
return HSettings.hls_mode ? _bandwidth : -1;
}
private static function on_manifest_loaded(e:HLSEvent):void{
_duration = e.levels[_hls.startLevel].duration;
}
private static function on_playlist_duration_updated(e:HLSEvent):void{
_duration = e.duration;
}
private static function on_manifest_loading(e:HLSEvent):void{
_url = e.url;
}
private static function on_event(e:HLSEvent):void{
JSAPI.postMessage2({id: 'flashls.'+e.type, hls_id: _hls.id,
url: e.url, level: e.level, duration: e.duration, levels: e.levels,
error: e.error, loadMetrics: e.loadMetrics,
playMetrics: e.playMetrics, mediatime: e.mediatime, state: e.state,
audioTrack: e.audioTrack, streamType: e.streamType});
}
private static function hola_version():Object{
return {
flashls_version: '0.4.2.1',
patch_version: '2.0.1'
};
}
private static function hola_hls_get_video_url():String{
return _url;
}
private static function hola_hls_get_position():Number{
return _hls.position;
}
private static function hola_hls_get_duration():Number{
return _duration;
}
private static function hola_hls_get_buffer_sec():Number{
return _hls.stream.bufferLength;
}
private static function hola_hls_get_state():String{
return _hls.playbackState;
}
private static function hola_hls_get_levels():Object{
return _hls.levels;
}
private static function hola_hls_get_level():Number{
return _hls.loadLevel;
}
private static function hola_setBandwidth(bandwidth:Number):void{
_bandwidth = bandwidth;
}
}
}
|
reset state on dispose
|
reset state on dispose
|
ActionScript
|
mpl-2.0
|
hola/flashls,hola/flashls
|
9e93db601c4e2c97037394bfc3755a6e86719ed4
|
src/aerys/minko/scene/visitor/data/ViewportData.as
|
src/aerys/minko/scene/visitor/data/ViewportData.as
|
package aerys.minko.scene.visitor.data
{
import aerys.minko.render.RenderTarget;
import aerys.minko.render.Viewport;
import aerys.minko.render.effect.IEffect;
import flash.utils.Dictionary;
public class ViewportData implements IWorldData
{
public static const RATIO : String = 'ratio';
public static const WIDTH : String = 'width';
public static const HEIGHT : String = 'height';
public static const ANTIALIASING : String = 'antialiasing';
public static const BACKGROUND_COLOR : String = 'backgroundColor';
protected var _viewport : Viewport;
protected var _renderTarget : RenderTarget;
public function get ratio() : Number
{
return _viewport.width / _viewport.height;
}
public function get width() : int
{
return _viewport.width;
}
public function get height() : int
{
return _viewport.height;
}
public function get antiAliasing() : int
{
return _viewport.antiAliasing;
}
public function get backgroundColor() : uint
{
return _viewport.backgroundColor;
}
public function get defaultEffect() : IEffect
{
return _viewport.defaultEffect;
}
public function get renderTarget() : RenderTarget
{
var viewportWidth : int = _viewport.width;
var viewportHeight : int = _viewport.height;
var viewportAntialias : int = _viewport.antiAliasing;
var viewportBgColor : int = _viewport.backgroundColor;
if (_renderTarget == null
|| viewportWidth != _renderTarget.width
|| viewportHeight != _renderTarget.height
|| viewportAntialias != _renderTarget.antiAliasing
|| viewportBgColor != _renderTarget.backgroundColor)
{
_renderTarget = new RenderTarget(
RenderTarget.BACKBUFFER, viewportWidth, viewportHeight,
viewportBgColor, true, viewportAntialias);
}
return _renderTarget;
}
public function ViewportData(viewport : Viewport)
{
_viewport = viewport;
}
public function setDataProvider(styleStack : StyleStack,
localData : LocalData,
worldData : Dictionary) : void
{
}
public function invalidate() : void
{
}
public function reset() : void
{
}
}
}
|
package aerys.minko.scene.visitor.data
{
import aerys.minko.render.RenderTarget;
import aerys.minko.render.Viewport;
import aerys.minko.render.effect.IEffect;
import flash.display.Stage;
import flash.utils.Dictionary;
public class ViewportData implements IWorldData
{
public static const RATIO : String = 'ratio';
public static const WIDTH : String = 'width';
public static const HEIGHT : String = 'height';
public static const ANTIALIASING : String = 'antialiasing';
public static const BACKGROUND_COLOR : String = 'backgroundColor';
protected var _viewport : Viewport;
protected var _renderTarget : RenderTarget;
public function get ratio() : Number
{
return _viewport.width / _viewport.height;
}
public function get width() : int
{
return _viewport.width;
}
public function get height() : int
{
return _viewport.height;
}
public function get antiAliasing() : int
{
return _viewport.antiAliasing;
}
public function get backgroundColor() : uint
{
return _viewport.backgroundColor;
}
public function get defaultEffect() : IEffect
{
return _viewport.defaultEffect;
}
public function get renderTarget() : RenderTarget
{
var viewportWidth : int = _viewport.width;
var viewportHeight : int = _viewport.height;
var viewportAntialias : int = _viewport.antiAliasing;
var viewportBgColor : int = _viewport.backgroundColor;
if (_renderTarget == null
|| viewportWidth != _renderTarget.width
|| viewportHeight != _renderTarget.height
|| viewportAntialias != _renderTarget.antiAliasing
|| viewportBgColor != _renderTarget.backgroundColor)
{
_renderTarget = new RenderTarget(
RenderTarget.BACKBUFFER, viewportWidth, viewportHeight,
viewportBgColor, true, viewportAntialias);
}
return _renderTarget;
}
public function get stage() : Stage
{
return _viewport.stage;
}
public function ViewportData(viewport : Viewport)
{
_viewport = viewport;
}
public function setDataProvider(styleStack : StyleStack,
localData : LocalData,
worldData : Dictionary) : void
{
}
public function invalidate() : void
{
}
public function reset() : void
{
}
}
}
|
Add a new getter into ViewportData, to be able to access the stage.
|
Add a new getter into ViewportData, to be able to access the stage.
|
ActionScript
|
mit
|
aerys/minko-as3
|
281016ce6f94b34cfa61dfcbe3c4a935d2cbaa92
|
axscript/mscom.as
|
axscript/mscom.as
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [ActiveScripting implemented with Tamarin].
*
* The Initial Developer of the Original Code is Mozilla Corp.
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Mark Hammond
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// hackery - for now, this file is "built" via:
// % java -ea -DAS3 -Xmx200m -DAVMPLUS -classpath ../utils/asc.jar macromedia.asc.embedding.ScriptCompiler -abcfuture -builtin -import ../core/builtin.abc -import ../esc/bin/parse.es.abc -import ../esc/bin/cogen.es.abc -out axtoplevel mscom.as Domain.as ../shell/ByteArray.as && move /y ..\shell\axtoplevel.* .
package axtam
{
// should possibly be private...
public class System
{
public native static function getAvmplusVersion():String
public native static function write(s:String):void
public native static function trace(a:Array):void
public native static function debugger():void
public native static function isDebugger():Boolean
public native static function nativeDebugBreak():void
}
}
package
{
// a global 'print' statement...
public function print(...s)
{
axtam.System.trace(s)
}
}
package axtam.com {
// Its not clear if we should subclass the standard 'Error', but given
// it has its own concept of 'Message' and 'ID', it doesn't seem a good fit.
// Maybe a new base-class should be introduced.
public dynamic class Error
{
public static const E_NOTIMPL = 0x80004001
public static const E_INVALIDARG = 0x80070057
public static const E_UNEXPECTED = 0x8000ffff
public static const E_FAIL = 0x80004005
public static const E_NOINTERFACE = 0x80000004
public var hresult: int
function Error(hresult) {
this.hresult = hresult;
print('Error constructed')
}
prototype.toString = function():String
{
var e:axtam.com.Error = this
return e.message !== "" ? e.name + ": " + e.message : e.name;
}
_setPropertyIsEnumerable(prototype, "toString", false);
public native static function getErrorMessage(index:int):String;
public static function throwError(hresult:int, ... rest)
{
// todo: rich error support?
//throw new axtam.com.Error(hresult);
}
}
// constants go directly in the axtam.com package.
public const SCRIPTINFO_IUNKNOWN = 0x00000001
public const SCRIPTINFO_ITYPEINFO = 0x00000002
public const SCRIPTITEM_ISVISIBLE = 0x00000002
public const SCRIPTITEM_ISSOURCE = 0x00000004
public const SCRIPTITEM_GLOBALMEMBERS = 0x00000008
public const SCRIPTITEM_ISPERSISTENT = 0x00000040
public const SCRIPTITEM_CODEONLY = 0x00000200
public const SCRIPTITEM_NOCODE = 0x00000400
}
package axtam.com.adaptors.consumer {
// scripting interfaces we consume in AS (ie, implemented externally)
// Each method listed here corresponds to a native method in the engine,
// which inturn delegates to the real COM object.
// Note that some of these classes have no scriptable methods, but they
// are used internally
public class IUnknown
{
}
// XXX - technically the rest of these 'derive' from IUnknown...
public class IDispatch
{
}
public class ITypeInfo
{
}
public class IActiveScriptSite
{
// somewhat like GetItemInfo() - but gets both IDispatch and ITypelib,
// and wraps them in a ScriptObject which can be used from script.
public native function GetItemInfo(name:String, flags:uint):Array
public native function GetDocVersionString(): String
}
}
package {
import flash.utils.*; // for our ByteArray clone - either it should die, or we rename the package in our clone!
public function execString(str, domain)
{
import Parse.*;
var top = []
var parser = new Parse.Parser(str,top);
var prog = parser.program();
var ts = prog[0]
var nd = prog[1]
var bytes = Gen::cg(nd).getBytes();
var b = new ByteArray();
b.endian = "littleEndian";
for (var i = 0, len = bytes.length; i<len; ++i) {
b.writeByte(uint(bytes[i]));
}
domain.loadBytes(b);
}
}
package {
class ScriptEngine {
public var globalDomain:axtam.Domain;
public var objectDomains; // A hashtable of named objects to their domains.
public var state:int;
public function ScriptEngine() {
}
public function InitNew() {
//domain = Domain.currentDomain
globalDomain = new axtam.Domain(null, null)
objectDomains = {}
}
public function ParseScriptText(code:String, itemName:String, context:Object, delim:String, sourceCookie:int, lineNumber:int, flags:int) {
print('ParseScriptText')
print(code)
// XXX - this is wrong - we should only do the parse and generation
// of bytecode here. We should execute all such blocks at
// SetScriptState(SCRIPTSTATE_RUNNING) time.
var domain = objectDomains[itemName]
if (!domain)
domain = globalDomain
execString(code, domain)
}
// This function is called as a 'named item' is added to the environment.
// Examples include IE's 'window' object.
public function AddNamedItem(name:String, flags:uint):void
{
print('AddNamedItem(', name, flags)
var site = new axtam.com.adaptors.consumer.IActiveScriptSite()
// MS docs say we should avoid grabbing typeinfo unless we
// really need it. At this stage, we need it if the item is
// "global", and later will need it if it sources events
var gii_flags:uint = axtam.com.SCRIPTINFO_IUNKNOWN
if (flags & axtam.com.SCRIPTITEM_GLOBALMEMBERS)
gii_flags |= axtam.com.SCRIPTINFO_ITYPEINFO
var items = site.GetItemInfo(name, gii_flags)
var dispatch = items[0]
var typeinfo = items[1]
globalDomain.global[name] = dispatch
// but we also need to tell the VM exactly what 'scope'
// provides this object.
globalDomain.addNamedScriptObject(name)
// if its global, we enumerate items and make them public - all
// this is done inside exposeGlobalMembers
//if (flags & axtam.com.SCRIPTITEM_GLOBALMEMBERS && typeinfo != null) {
// domain.exposeGlobalMembers(dispatch, typeinfo)
//}
// create a new domain for the object with the IDispatch as its global.
var obDomain = new axtam.Domain(globalDomain, dispatch)
objectDomains[name] = obDomain
}
public function GetScriptState(): uint
{
return state;
}
public function SetScriptState(new_state:uint): void
{
// don't allow new state transitions once we are closed.
axtam.com.Error.throwError(axtam.com.Error.E_INVALIDARG)
}
}
public var engine = new ScriptEngine()
// and magically methods will be called on 'engine'
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [ActiveScripting implemented with Tamarin].
*
* The Initial Developer of the Original Code is Mozilla Corp.
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Mark Hammond
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// hackery - for now, this file is "built" via:
// % java -ea -DAS3 -Xmx200m -DAVMPLUS -classpath ../utils/asc.jar macromedia.asc.embedding.ScriptCompiler -abcfuture -builtin -import ../core/builtin.abc -import ../esc/bin/parse.es.abc -import ../esc/bin/cogen.es.abc -out axtoplevel mscom.as Domain.as ../shell/ByteArray.as && move /y ..\shell\axtoplevel.* .
package axtam
{
// should possibly be private...
public class System
{
public native static function getAvmplusVersion():String
public native static function write(s:String):void
public native static function trace(a:Array):void
public native static function debugger():void
public native static function isDebugger():Boolean
public native static function nativeDebugBreak():void
}
}
package
{
// a global 'print' statement...
public function print(...s)
{
axtam.System.trace(s)
}
}
package axtam.com {
// Its not clear if we should subclass the standard 'Error', but given
// it has its own concept of 'Message' and 'ID', it doesn't seem a good fit.
// Maybe a new base-class should be introduced.
public dynamic class Error
{
public static const E_NOTIMPL = 0x80004001
public static const E_INVALIDARG = 0x80070057
public static const E_UNEXPECTED = 0x8000ffff
public static const E_FAIL = 0x80004005
public static const E_NOINTERFACE = 0x80000004
public var hresult: int
function Error(hresult) {
this.hresult = hresult;
print('Error constructed')
}
prototype.toString = function():String
{
var e:axtam.com.Error = this
return e.message !== "" ? e.name + ": " + e.message : e.name;
}
_setPropertyIsEnumerable(prototype, "toString", false);
public native static function getErrorMessage(index:int):String;
public static function throwError(hresult:int, ... rest)
{
// todo: rich error support?
//throw new axtam.com.Error(hresult);
}
}
// constants go directly in the axtam.com package.
public const SCRIPTINFO_IUNKNOWN = 0x00000001
public const SCRIPTINFO_ITYPEINFO = 0x00000002
public const SCRIPTITEM_ISVISIBLE = 0x00000002
public const SCRIPTITEM_ISSOURCE = 0x00000004
public const SCRIPTITEM_GLOBALMEMBERS = 0x00000008
public const SCRIPTITEM_ISPERSISTENT = 0x00000040
public const SCRIPTITEM_CODEONLY = 0x00000200
public const SCRIPTITEM_NOCODE = 0x00000400
}
package axtam.com.adaptors.consumer {
// scripting interfaces we consume in AS (ie, implemented externally)
// Each method listed here corresponds to a native method in the engine,
// which inturn delegates to the real COM object.
// Note that some of these classes have no scriptable methods, but they
// are used internally
public class IUnknown
{
}
// XXX - technically the rest of these 'derive' from IUnknown...
public class IDispatch
{
}
public class ITypeInfo
{
}
public class IActiveScriptSite
{
// somewhat like GetItemInfo() - but gets both IDispatch and ITypelib,
// and wraps them in a ScriptObject which can be used from script.
public native function GetItemInfo(name:String, flags:uint):Array
public native function GetDocVersionString(): String
}
}
package {
import flash.utils.*; // for our ByteArray clone - either it should die, or we rename the package in our clone!
public function execString(str, domain)
{
import Parse.*;
var top = []
var parser = new Parse.Parser(str,top);
var prog = parser.program();
var ts = prog[0]
var nd = prog[1]
var bytes = Gen::cg(nd).getBytes();
var b = new ByteArray();
b.endian = "littleEndian";
for (var i = 0, len = bytes.length; i<len; ++i) {
b.writeByte(uint(bytes[i]));
}
domain.loadBytes(b);
}
}
package {
class ScriptEngine {
public var globalDomain:axtam.Domain;
public var objectDomains; // A hashtable of named objects to their domains.
public var state:int;
public function ScriptEngine() {
}
public function InitNew() {
//domain = Domain.currentDomain
globalDomain = new axtam.Domain(null, null)
objectDomains = {}
}
public function ParseScriptText(code:String, itemName:String, context:Object, delim:String, sourceCookie:int, lineNumber:int, flags:int) {
// XXX - this is wrong - we should only do the parse and generation
// of bytecode here. We should execute all such blocks at
// SetScriptState(SCRIPTSTATE_RUNNING) time.
var domain = objectDomains[itemName]
if (!domain)
domain = globalDomain
execString(code, domain)
}
// This function is called as a 'named item' is added to the environment.
// Examples include IE's 'window' object.
public function AddNamedItem(name:String, flags:uint):void
{
print('AddNamedItem(', name, flags)
var site = new axtam.com.adaptors.consumer.IActiveScriptSite()
// MS docs say we should avoid grabbing typeinfo unless we
// really need it. At this stage, we need it if the item is
// "global", and later will need it if it sources events
var gii_flags:uint = axtam.com.SCRIPTINFO_IUNKNOWN
if (flags & axtam.com.SCRIPTITEM_GLOBALMEMBERS)
gii_flags |= axtam.com.SCRIPTINFO_ITYPEINFO
var items = site.GetItemInfo(name, gii_flags)
var dispatch = items[0]
var typeinfo = items[1]
globalDomain.global[name] = dispatch
// but we also need to tell the VM exactly what 'scope'
// provides this object.
globalDomain.addNamedScriptObject(name)
// if its global, we enumerate items and make them public - all
// this is done inside exposeGlobalMembers
//if (flags & axtam.com.SCRIPTITEM_GLOBALMEMBERS && typeinfo != null) {
// domain.exposeGlobalMembers(dispatch, typeinfo)
//}
// create a new domain for the object with the IDispatch as its global.
var obDomain = new axtam.Domain(globalDomain, dispatch)
objectDomains[name] = obDomain
}
public function GetScriptState(): uint
{
return state;
}
public function SetScriptState(new_state:uint): void
{
// don't allow new state transitions once we are closed.
axtam.com.Error.throwError(axtam.com.Error.E_INVALIDARG)
}
}
public var engine = new ScriptEngine()
// and magically methods will be called on 'engine'
}
|
Remove debug prints
|
Remove debug prints
|
ActionScript
|
mpl-2.0
|
pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux
|
6bf7a9bf4a365f686ffe06f6d71ae41dd9a960ce
|
src/aerys/minko/scene/node/Group.as
|
src/aerys/minko/scene/node/Group.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.scene.SceneIterator;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.type.Signal;
import aerys.minko.type.Sort;
import aerys.minko.type.loader.ILoader;
import aerys.minko.type.loader.SceneLoader;
import aerys.minko.type.loader.parser.ParserOptions;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Ray;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
/**
* Group objects can contain other scene nodes and applies a 3D
* transformation to its descendants.
*
* @author Jean-Marc Le Roux
*/
public class Group extends AbstractSceneNode
{
use namespace minko_scene;
minko_scene var _children : Vector.<ISceneNode> = null;
minko_scene var _numChildren : uint = 0;
private var _numDescendants : uint = 0;
private var _descendantAdded : Signal = new Signal('Group.descendantAdded');
private var _descendantRemoved : Signal = new Signal('Group.descendantRemoved');
/**
* The number of children of the Group.
*/
public function get numChildren() : uint
{
return _numChildren;
}
/**
* The number of descendants of the Group.
*
* @return
*
*/
public function get numDescendants() : uint
{
return _numDescendants;
}
/**
* The signal executed when a descendant is added to the Group.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>newParent : Group, the Group the descendant was actually added to</li>
* <li>descendant : ISceneNode, the descendant that was just added</li>
* </ul>
*
* @return
*
*/
public function get descendantAdded() : Signal
{
return _descendantAdded
}
/**
* The signal executed when a descendant is removed from the Group.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>oldParent : Group, the Group the descendant was actually removed from</li>
* <li>descendant : ISceneNode, the descendant that was just removed</li>
* </ul>
*
* @return
*
*/
public function get descendantRemoved() : Signal
{
return _descendantRemoved;
}
public function Group(...children)
{
super();
initialize();
initializeChildren(children);
}
private function initialize() : void
{
_children = new <ISceneNode>[];
descendantAdded.add(descendantAddedHandler);
descendantRemoved.add(descendantRemovedHandler);
}
protected function initializeChildren(children : Array) : void
{
while (children.length == 1 && children[0] is Array)
children = children[0];
var childrenNum : uint = children.length;
for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex)
addChild(ISceneNode(children[childrenIndex]));
}
override protected function addedHandler(child : ISceneNode, parent : Group) : void
{
super.addedHandler(child, parent);
for (var childIndex : int = 0; childIndex < _numChildren; ++childIndex)
_children[childIndex].added.execute(child, parent);
}
override protected function removedHandler(child : ISceneNode, parent : Group) : void
{
super.removedHandler(child, parent);
for (var childIndex : int = 0; childIndex < _numChildren; ++childIndex)
_children[childIndex].removed.execute(child, parent);
}
private function descendantAddedHandler(group : Group, child : ISceneNode) : void
{
if (group == this)
{
var childGroup : Group = child as Group;
if (childGroup)
{
childGroup.descendantAdded.add(_descendantAdded.execute);
childGroup.descendantRemoved.add(_descendantRemoved.execute);
}
}
_numDescendants += (child is Group) ? (child as Group)._numDescendants + 1 : 1;
}
private function descendantRemovedHandler(group : Group, child : ISceneNode) : void
{
if (group == this)
{
var childGroup : Group = child as Group;
if (childGroup)
{
childGroup.descendantAdded.remove(_descendantAdded.execute);
childGroup.descendantRemoved.remove(_descendantRemoved.execute);
}
}
_numDescendants -= (child is Group) ? (child as Group)._numDescendants + 1 : 1;
}
/**
* Return true if the specified scene node is a child of the Group, false otherwise.
*
* @param scene
* @return
*
*/
public function contains(scene : ISceneNode) : Boolean
{
return getChildIndex(scene) >= 0;
}
/**
* Return the index of the speficied scene node or -1 if it is not in the Group.
*
* @param child
* @return
*
*/
public function getChildIndex(child : ISceneNode) : int
{
if (child == null)
throw new Error('The \'child\' parameter cannot be null.');
for (var i : int = 0; i < _numChildren; i++)
if (_children[i] === child)
return i;
return -1;
}
public function getChildByName(name : String) : ISceneNode
{
for (var i : int = 0; i < _numChildren; i++)
if (_children[i].name === name)
return _children[i];
return null;
}
/**
* Add a child to the group.
*
* @param scene The child to add.
*/
public function addChild(node : ISceneNode) : Group
{
return addChildAt(node, _numChildren);
}
/**
* Add a child to the group at the specified position.
*
* @param node
* @param position
* @return
*
*/
public function addChildAt(node : ISceneNode, position : uint) : Group
{
if (!node)
throw new Error('Parameter \'scene\' must not be null.');
node.parent = this;
for (var i : int = _numChildren - 1; i > position; --i)
_children[i] = _children[int(i - 1)];
_children[position] = node;
return this;
}
/**
* Remove a child from the container.
*
* @param myChild The child to remove.
* @return Whether the child was actually removed or not.
*/
public function removeChild(child : ISceneNode) : Group
{
return removeChildAt(getChildIndex(child));
}
public function removeChildAt(position : uint) : Group
{
if (position >= _numChildren || position < 0)
throw new Error('The scene node is not a child of the caller.');
(_children[position] as ISceneNode).parent = null;
return this;
}
/**
* Remove all the children.
*
* @return
*
*/
public function removeAllChildren() : Group
{
while (_numChildren)
removeChildAt(0);
return this;
}
/**
* Return the child at the specified position.
*
* @param position
* @return
*
*/
public function getChildAt(position : uint) : ISceneNode
{
return position < _numChildren ? _children[position] : null;
}
/**
* Returns the list of descendant scene nodes that have the specified type.
*
* @param type
* @param descendants
* @return
*
*/
public function getDescendantsByType(type : Class,
descendants : Vector.<ISceneNode> = null) : Vector.<ISceneNode>
{
descendants ||= new Vector.<ISceneNode>();
for (var i : int = 0; i < _numChildren; ++i)
{
var child : ISceneNode = _children[i];
var group : Group = child as Group;
if (child is type)
descendants.push(child);
if (group)
group.getDescendantsByType(type, descendants);
}
return descendants;
}
public function toString() : String
{
return '[' + getQualifiedClassName(this) + ' ' + name + ']';
}
/**
* Load the 3D scene corresponding to the specified URLRequest object
* and add it directly to the group.
*
* @param request
* @param options
* @return
*
*/
public function load(request : URLRequest,
options : ParserOptions = null) : ILoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.load(request);
return loader;
}
/**
* Load the 3D scene corresponding to the specified Class object
* and add it directly to the group.
*
* @param classObject
* @param options
* @return
*
*/
public function loadClass(classObject : Class,
options : ParserOptions = null) : ILoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.loadClass(classObject);
return loader;
}
/**
* Load the 3D scene corresponding to the specified ByteArray object
* and add it directly to the group.
*
* @param bytes
* @param options
* @return
*
*/
public function loadBytes(bytes : ByteArray,
options : ParserOptions = null) : ILoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.loadBytes(bytes);
return loader;
}
/**
* Return the set of nodes matching the specified XPath query.
*
* @param xpath
* @return
*
*/
public function get(xpath : String) : SceneIterator
{
return new SceneIterator(xpath, new <ISceneNode>[this]);
}
private function loaderCompleteHandler(loader : ILoader,
scene : ISceneNode) : void
{
addChild(scene);
}
/**
* Return all the Mesh objects hit by the specified ray.
*
* @param ray
* @param maxDistance
* @return
*
*/
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : SceneIterator
{
var meshes : Vector.<ISceneNode> = getDescendantsByType(Mesh);
var numMeshes : uint = meshes.length;
var hit : Array = [];
var depth : Vector.<Number> = new <Number>[];
var numItems : uint = 0;
for (var i : uint = 0; i < numMeshes; ++i)
{
var mesh : Mesh = meshes[i] as Mesh;
var hitDepth : Number = mesh.geometry.boundingBox.testRay(
ray,
mesh.worldToLocal,
maxDistance
);
if (hitDepth >= 0.0)
{
hit[numItems] = mesh;
depth[numItems] = hitDepth;
++numItems;
}
}
if (numItems > 1)
Sort.flashSort(depth, hit, numItems);
return new SceneIterator(null, Vector.<ISceneNode>(hit));
}
override public function clone(cloneControllers : Boolean = false) : ISceneNode
{
var cloned : Group = new Group();
cloned.name = name;
cloned.transform.copyFrom(transform);
for (var childId : uint = 0; childId < _numChildren; ++childId)
cloned.addChildAt(getChildAt(childId).clone(), childId);
copyControllersFrom(this, cloned, cloneControllers);
return cloned;
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.scene.SceneIterator;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.type.Signal;
import aerys.minko.type.Sort;
import aerys.minko.type.loader.ILoader;
import aerys.minko.type.loader.SceneLoader;
import aerys.minko.type.loader.parser.ParserOptions;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Ray;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
/**
* Group objects can contain other scene nodes and applies a 3D
* transformation to its descendants.
*
* @author Jean-Marc Le Roux
*/
public class Group extends AbstractSceneNode
{
use namespace minko_scene;
minko_scene var _children : Vector.<ISceneNode> = null;
minko_scene var _numChildren : uint = 0;
private var _numDescendants : uint = 0;
private var _descendantAdded : Signal = new Signal('Group.descendantAdded');
private var _descendantRemoved : Signal = new Signal('Group.descendantRemoved');
/**
* The number of children of the Group.
*/
public function get numChildren() : uint
{
return _numChildren;
}
/**
* The number of descendants of the Group.
*
* @return
*
*/
public function get numDescendants() : uint
{
return _numDescendants;
}
/**
* The signal executed when a descendant is added to the Group.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>newParent : Group, the Group the descendant was actually added to</li>
* <li>descendant : ISceneNode, the descendant that was just added</li>
* </ul>
*
* @return
*
*/
public function get descendantAdded() : Signal
{
return _descendantAdded
}
/**
* The signal executed when a descendant is removed from the Group.
* Callbacks for this signal must accept the following arguments:
* <ul>
* <li>oldParent : Group, the Group the descendant was actually removed from</li>
* <li>descendant : ISceneNode, the descendant that was just removed</li>
* </ul>
*
* @return
*
*/
public function get descendantRemoved() : Signal
{
return _descendantRemoved;
}
public function Group(...children)
{
super();
initialize();
initializeChildren(children);
}
private function initialize() : void
{
_children = new <ISceneNode>[];
descendantAdded.add(descendantAddedHandler);
descendantRemoved.add(descendantRemovedHandler);
}
protected function initializeChildren(children : Array) : void
{
while (children.length == 1 && children[0] is Array)
children = children[0];
var childrenNum : uint = children.length;
for (var childrenIndex : uint = 0; childrenIndex < childrenNum; ++childrenIndex)
addChild(ISceneNode(children[childrenIndex]));
}
override protected function addedHandler(child : ISceneNode, parent : Group) : void
{
super.addedHandler(child, parent);
for (var childIndex : int = 0; childIndex < _numChildren; ++childIndex)
_children[childIndex].added.execute(child, parent);
}
override protected function removedHandler(child : ISceneNode, parent : Group) : void
{
super.removedHandler(child, parent);
for (var childIndex : int = 0; childIndex < _numChildren; ++childIndex)
_children[childIndex].removed.execute(child, parent);
}
private function descendantAddedHandler(group : Group, child : ISceneNode) : void
{
if (group == this)
{
var childGroup : Group = child as Group;
if (childGroup)
{
childGroup.descendantAdded.add(_descendantAdded.execute);
childGroup.descendantRemoved.add(_descendantRemoved.execute);
}
}
_numDescendants += (child is Group) ? (child as Group)._numDescendants + 1 : 1;
}
private function descendantRemovedHandler(group : Group, child : ISceneNode) : void
{
if (group == this)
{
var childGroup : Group = child as Group;
if (childGroup)
{
childGroup.descendantAdded.remove(_descendantAdded.execute);
childGroup.descendantRemoved.remove(_descendantRemoved.execute);
}
}
_numDescendants -= (child is Group) ? (child as Group)._numDescendants + 1 : 1;
}
/**
* Return true if the specified scene node is a child of the Group, false otherwise.
*
* @param scene
* @return
*
*/
public function contains(scene : ISceneNode) : Boolean
{
return getChildIndex(scene) >= 0;
}
/**
* Return the index of the speficied scene node or -1 if it is not in the Group.
*
* @param child
* @return
*
*/
public function getChildIndex(child : ISceneNode) : int
{
if (child == null)
throw new Error('The \'child\' parameter cannot be null.');
for (var i : int = 0; i < _numChildren; i++)
if (_children[i] === child)
return i;
return -1;
}
public function getChildByName(name : String) : ISceneNode
{
for (var i : int = 0; i < _numChildren; i++)
if (_children[i].name === name)
return _children[i];
return null;
}
/**
* Add a child to the group.
*
* @param scene The child to add.
*/
public function addChild(node : ISceneNode) : Group
{
return addChildAt(node, _numChildren);
}
/**
* Add a child to the group at the specified position.
*
* @param node
* @param position
* @return
*
*/
public function addChildAt(node : ISceneNode, position : uint) : Group
{
if (!node)
throw new Error('Parameter \'scene\' must not be null.');
node.parent = this;
for (var i : int = _numChildren - 1; i > position; --i)
_children[i] = _children[int(i - 1)];
_children[position] = node;
return this;
}
/**
* Remove a child from the container.
*
* @param myChild The child to remove.
* @return Whether the child was actually removed or not.
*/
public function removeChild(child : ISceneNode) : Group
{
return removeChildAt(getChildIndex(child));
}
public function removeChildAt(position : uint) : Group
{
if (position >= _numChildren || position < 0)
throw new Error('The scene node is not a child of the caller.');
(_children[position] as ISceneNode).parent = null;
return this;
}
/**
* Remove all the children.
*
* @return
*
*/
public function removeAllChildren() : Group
{
while (_numChildren)
removeChildAt(0);
return this;
}
/**
* Return the child at the specified position.
*
* @param position
* @return
*
*/
public function getChildAt(position : uint) : ISceneNode
{
return position < _numChildren ? _children[position] : null;
}
/**
* Returns the list of descendant scene nodes that have the specified type.
*
* @param type
* @param descendants
* @return
*
*/
public function getDescendantsByType(type : Class,
descendants : Vector.<ISceneNode> = null) : Vector.<ISceneNode>
{
descendants ||= new Vector.<ISceneNode>();
for (var i : int = 0; i < _numChildren; ++i)
{
var child : ISceneNode = _children[i];
var group : Group = child as Group;
if (child is type)
descendants.push(child);
if (group)
group.getDescendantsByType(type, descendants);
}
return descendants;
}
public function toString() : String
{
return '[' + getQualifiedClassName(this) + ' ' + name + ']';
}
/**
* Load the 3D scene corresponding to the specified URLRequest object
* and add it directly to the group.
*
* @param request
* @param options
* @return
*
*/
public function load(request : URLRequest,
options : ParserOptions = null) : ILoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.load(request);
return loader;
}
/**
* Load the 3D scene corresponding to the specified Class object
* and add it directly to the group.
*
* @param classObject
* @param options
* @return
*
*/
public function loadClass(classObject : Class,
options : ParserOptions = null) : ILoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.loadClass(classObject);
return loader;
}
/**
* Load the 3D scene corresponding to the specified ByteArray object
* and add it directly to the group.
*
* @param bytes
* @param options
* @return
*
*/
public function loadBytes(bytes : ByteArray,
options : ParserOptions = null) : ILoader
{
var loader : SceneLoader = new SceneLoader(options);
loader.complete.add(loaderCompleteHandler);
loader.loadBytes(bytes);
return loader;
}
/**
* Return the set of nodes matching the specified XPath query.
*
* @param xpath
* @return
*
*/
public function get(xpath : String) : SceneIterator
{
return new SceneIterator(xpath, new <ISceneNode>[this]);
}
private function loaderCompleteHandler(loader : ILoader,
scene : ISceneNode) : void
{
addChild(scene);
}
/**
* Return all the Mesh objects hit by the specified ray.
*
* @param ray
* @param maxDistance
* @return
*
*/
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : SceneIterator
{
var meshes : Vector.<ISceneNode> = getDescendantsByType(Mesh);
var numMeshes : uint = meshes.length;
var hit : Array = [];
var depth : Vector.<Number> = new <Number>[];
var numItems : uint = 0;
for (var i : uint = 0; i < numMeshes; ++i)
{
var mesh : Mesh = meshes[i] as Mesh;
var hitDepth : Number = mesh.cast(ray, maxDistance);
if (hitDepth >= 0.0)
{
hit[numItems] = mesh;
depth[numItems] = hitDepth;
++numItems;
}
}
if (numItems > 1)
Sort.flashSort(depth, hit, numItems);
return new SceneIterator(null, Vector.<ISceneNode>(hit));
}
override public function clone(cloneControllers : Boolean = false) : ISceneNode
{
var cloned : Group = new Group();
cloned.name = name;
cloned.transform.copyFrom(transform);
for (var childId : uint = 0; childId < _numChildren; ++childId)
cloned.addChildAt(getChildAt(childId).clone(), childId);
copyControllersFrom(this, cloned, cloneControllers);
return cloned;
}
}
}
|
use Mesh.cast() in Group.cast()
|
use Mesh.cast() in Group.cast()
|
ActionScript
|
mit
|
aerys/minko-as3
|
8342b47b183ed60d1e8321fd2ebe5f8a465d09c1
|
src/aerys/minko/render/geometry/stream/iterator/TriangleIterator.as
|
src/aerys/minko/render/geometry/stream/iterator/TriangleIterator.as
|
package aerys.minko.render.geometry.stream.iterator
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.IndexStream;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* TriangleIterator allow per-triangle access on VertexStream objects.
*
* @author Jean-Marc Le Roux
*
*/
public final class TriangleIterator extends Proxy
{
use namespace minko_stream;
private var _singleReference : Boolean = true;
private var _offset : int = 0;
private var _index : int = 0;
private var _vb : IVertexStream = null;
private var _ib : IndexStream = null;
private var _triangle : TriangleReference = null;
public function get length() : int
{
return _ib ? _ib.length / 3 : _vb.numVertices / 3;
}
public function TriangleIterator(vertexStream : IVertexStream,
indexStream : IndexStream,
singleReference : Boolean = true)
{
super();
_vb = vertexStream;
_ib = indexStream;
_singleReference = singleReference;
}
override flash_proxy function hasProperty(name : *) : Boolean
{
return int(name) < _ib.length / 3;
}
override flash_proxy function nextNameIndex(index : int) : int
{
index -= _offset;
_offset = 0;
return index < _ib.length / 3 ? index + 1 : 0;
}
override flash_proxy function nextName(index : int) : String
{
return String(index - 1);
}
override flash_proxy function nextValue(index : int) : *
{
_index = index - 1;
if (!_singleReference || !_triangle)
_triangle = new TriangleReference(_vb, _ib, _index);
if (_singleReference)
{
_triangle._index = _index;
_triangle.v0._index = _ib._data[int(_index * 3)];
_triangle.v1._index = _ib._data[int(_index * 3 + 1)];
_triangle.v2._index = _ib._data[int(_index * 3 + 2)];
_triangle._update = TriangleReference.UPDATE_ALL;
}
return _triangle;
}
override flash_proxy function getProperty(name : *) : *
{
return new TriangleReference(_vb, _ib, int(name));
}
override flash_proxy function deleteProperty(name : *) : Boolean
{
var index : uint = uint(name);
_ib.deleteTriangle(index);
return true;
}
}
}
|
package aerys.minko.render.geometry.stream.iterator
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.IndexStream;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
/**
* TriangleIterator allow per-triangle access on VertexStream objects.
*
* @author Jean-Marc Le Roux
*
*/
public final class TriangleIterator extends Proxy
{
use namespace minko_stream;
private var _singleReference : Boolean = true;
private var _offset : int = 0;
private var _index : int = 0;
private var _vb : IVertexStream = null;
private var _ib : IndexStream = null;
private var _triangle : TriangleReference = null;
public function get length() : int
{
return _ib ? _ib.length / 3 : _vb.numVertices / 3;
}
public function TriangleIterator(vertexStream : IVertexStream,
indexStream : IndexStream,
singleReference : Boolean = true)
{
super();
_vb = vertexStream;
_ib = indexStream;
_singleReference = singleReference;
}
override flash_proxy function hasProperty(name : *) : Boolean
{
return int(name) < _ib.length / 3;
}
override flash_proxy function nextNameIndex(index : int) : int
{
index -= _offset;
_offset = 0;
return index < _ib.length / 3 ? index + 1 : 0;
}
override flash_proxy function nextName(index : int) : String
{
return String(index - 1);
}
override flash_proxy function nextValue(index : int) : *
{
_index = index - 1;
if (!_singleReference || !_triangle)
_triangle = new TriangleReference(_vb, _ib, _index);
if (_singleReference)
{
_triangle._index = _index;
_triangle.v0.index = _ib.get(_index * 3);
_triangle.v1.index = _ib.get(_index * 3 + 1);
_triangle.v2.index = _ib.get(_index * 3 + 2);
_triangle._update = TriangleReference.UPDATE_ALL;
}
return _triangle;
}
override flash_proxy function getProperty(name : *) : *
{
return new TriangleReference(_vb, _ib, int(name));
}
override flash_proxy function deleteProperty(name : *) : Boolean
{
var index : uint = uint(name);
_ib.deleteTriangle(index);
return true;
}
}
}
|
fix triangle iterator
|
fix triangle iterator
|
ActionScript
|
mit
|
aerys/minko-as3
|
030ea965568fe3469824a2143c017194835209c1
|
src/org/mangui/hls/HLSSettings.as
|
src/org/mangui/hls/HLSSettings.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // // /////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // // /////////////////////////////////
/**
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 120.
*/
public static var maxBufferLength : Number = 120;
/**
* Defines maximum back buffer length in seconds.
* (0 means infinite back buffering)
*
* Default is 30.
*/
public static var maxBackBufferLength : Number = 30;
/**
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3.
*/
public static var lowBufferLength : Number = 3;
/**
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
*
* Default is HLSSeekMode.KEYFRAME_SEEK.
*/
public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK;
/** max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var keyLoadMaxRetry : int = 3;
/** keyLoadMaxRetryTimeout
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/** max nb of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var fragmentLoadMaxRetry : int = 3;
/** fragmentLoadMaxRetryTimeout
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 4000.
*/
public static var fragmentLoadMaxRetryTimeout : Number = 64000;
/** fragmentLoadSkipAfterMaxRetry
* control behaviour in case fragment load still fails after max retry timeout
* if set to true, fragment will be skipped and next one will be loaded.
* If set to false, an I/O Error will be raised.
*
* Default is true.
*/
public static var fragmentLoadSkipAfterMaxRetry : Boolean = true;
/**
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/** max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = -1;
/** manifestLoadMaxRetryTimeout
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*/
public static var startFromBitrate : Number = -1;
/** start level :
* from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
* -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate)
*/
public static var startFromLevel : Number = -1;
/** seek level :
* from 0 to 1 : indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*/
public static var seekFromLevel : Number = -1;
/** use hardware video decoder :
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*/
public static var useHardwareVideoDecoder : Boolean = false;
/**
* Defines whether INFO level log messages will will appear in the console
* Default is true.
*/
public static var logInfo : Boolean = true;
/**
* Defines whether DEBUG level log messages will will appear in the console
* Default is false.
*/
public static var logDebug : Boolean = false;
/**
* Defines whether DEBUG2 level log messages will will appear in the console
* Default is false.
*/
public static var logDebug2 : Boolean = false;
/**
* Defines whether WARN level log messages will will appear in the console
* Default is true.
*/
public static var logWarn : Boolean = true;
/**
* Defines whether ERROR level log messages will will appear in the console
* Default is true.
*/
public static var logError : Boolean = true;
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.constant.HLSSeekMode;
import org.mangui.hls.constant.HLSMaxLevelCappingMode;
public final class HLSSettings extends Object {
/**
* capLevelToStage
*
* Limit levels usable in auto-quality by the stage dimensions (width and height).
* true - level width and height (defined in m3u8 playlist) will be compared with the player width and height (stage.stageWidth and stage.stageHeight).
* Max level will be set depending on the maxLevelCappingMode option.
* false - levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration.
*
* Note: this setting is ignored in manual mode so all the levels could be selected manually.
*
* Default is false
*/
public static var capLevelToStage : Boolean = false;
/**
* maxLevelCappingMode
*
* Defines the max level capping mode to the one available in HLSMaxLevelCappingMode
* HLSMaxLevelCappingMode.DOWNSCALE - max capped level should be the one with the dimensions equal or greater than the stage dimensions (so the video will be downscaled)
* HLSMaxLevelCappingMode.UPSCALE - max capped level should be the one with the dimensions equal or lower than the stage dimensions (so the video will be upscaled)
*
* Default is HLSMaxLevelCappingMode.DOWNSCALE
*/
public static var maxLevelCappingMode : String = HLSMaxLevelCappingMode.DOWNSCALE;
// // // // // // /////////////////////////////////
//
// org.mangui.hls.stream.HLSNetStream
//
// // // // // // /////////////////////////////////
/**
* minBufferLength
*
* Defines minimum buffer length in seconds before playback can start, after seeking or buffer stalling.
*
* Default is -1 = auto
*/
public static var minBufferLength : Number = -1;
/**
* maxBufferLength
*
* Defines maximum buffer length in seconds.
* (0 means infinite buffering)
*
* Default is 120
*/
public static var maxBufferLength : Number = 120;
/**
* maxBackBufferLength
*
* Defines maximum back buffer length in seconds.
* (0 means infinite back buffering)
*
* Default is 30
*/
public static var maxBackBufferLength : Number = 30;
/**
* lowBufferLength
*
* Defines low buffer length in seconds.
* When crossing down this threshold, HLS will switch to buffering state.
*
* Default is 3
*/
public static var lowBufferLength : Number = 3;
/**
* seekMode
*
* Defines seek mode to one form available in HLSSeekMode class:
* HLSSeekMode.ACCURATE_SEEK - accurate seeking to exact requested position
* HLSSeekMode.KEYFRAME_SEEK - key-frame based seeking (seek to nearest key frame before requested seek position)
*
* Default is HLSSeekMode.KEYFRAME_SEEK
*/
public static var seekMode : String = HLSSeekMode.KEYFRAME_SEEK;
/**
* keyLoadMaxRetry
*
* Max nb of retries for Key Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*
* Default is 3
*/
public static var keyLoadMaxRetry : int = 3;
/**
* keyLoadMaxRetryTimeout
*
* Maximum key retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on key request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until keyLoadMaxRetryTimeout is reached.
*
* Default is 64000.
*/
public static var keyLoadMaxRetryTimeout : Number = 64000;
/**
* fragmentLoadMaxRetry
*
* Max number of retries for Fragment Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*
* Default is 3
*/
public static var fragmentLoadMaxRetry : int = 3;
/**
* fragmentLoadMaxRetryTimeout
*
* Maximum Fragment retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until fragmentLoadMaxRetryTimeout is reached.
*
* Default is 4000
*/
public static var fragmentLoadMaxRetryTimeout : Number = 4000
/**
* fragmentLoadSkipAfterMaxRetry
*
* control behaviour in case fragment load still fails after max retry timeout
* if set to true, fragment will be skipped and next one will be loaded.
* If set to false, an I/O Error will be raised.
*
* Default is true.
*/
public static var fragmentLoadSkipAfterMaxRetry : Boolean = true;
/**
* flushLiveURLCache
*
* If set to true, live playlist will be flushed from URL cache before reloading
* (this is to workaround some cache issues with some combination of Flash Player / IE version)
*
* Default is false
*/
public static var flushLiveURLCache : Boolean = false;
/**
* manifestLoadMaxRetry
*
* max nb of retries for Manifest Loading in case I/O errors are met,
* 0, means no retry, error will be triggered automatically
* -1 means infinite retry
*/
public static var manifestLoadMaxRetry : int = -1;
/**
* manifestLoadMaxRetryTimeout
*
* Maximum Manifest retry timeout (in milliseconds) in case I/O errors are met.
* Every fail on fragment request, player will exponentially increase the timeout to try again.
* It starts waiting 1 second (1000ms), than 2, 4, 8, 16, until manifestLoadMaxRetryTimeout is reached.
*
* Default is 64000
*/
public static var manifestLoadMaxRetryTimeout : Number = 64000;
/**
* startFromBitrate
*
* If greater than 0, specifies the preferred bitrate.
* If -1, and startFromLevel is not specified, automatic start level selection will be used.
* This parameter, if set, will take priority over startFromLevel.
*
* Default is -1
*/
public static var startFromBitrate : Number = -1;
/**
* startFromLevel
*
* start level :
* from 0 to 1 : indicates the "normalized" preferred level. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, playback will start from level matching download bandwidth (determined from download of first segment)
* -2 : playback will start from the first level appearing in Manifest (not sorted by bitrate)
*
* Default is -1
*/
public static var startFromLevel : Number = -1;
/**
* seekFromLevel
*
* Seek level:
* from 0 to 1: indicates the "normalized" preferred bitrate. As such, if it is 0.5, the closest to the middle bitrate will be selected and used first.
* -1 : automatic start level selection, keep previous level matching previous download bandwidth
*
* Default is -1
*/
public static var seekFromLevel : Number = -1;
/**
* useHardwareVideoDecoder
*
* Use hardware video decoder:
* it will set NetStream.useHardwareDecoder
* refer to http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#useHardwareDecoder
*
* Default is false
*/
public static var useHardwareVideoDecoder : Boolean = false;
/**
* logInfo
*
* Defines whether INFO level log messages will will appear in the console
*
* Default is true
*/
public static var logInfo : Boolean = true;
/**
* logDebug
*
* Defines whether DEBUG level log messages will will appear in the console
*
* Default is false
*/
public static var logDebug : Boolean = false;
/**
* logDebug2
*
* Defines whether DEBUG2 level log messages will will appear in the console
*
* Default is false
*/
public static var logDebug2 : Boolean = false;
/**
* logWarn
*
* Defines whether WARN level log messages will will appear in the console
*
* Default is true
*/
public static var logWarn : Boolean = true;
/**
* logError
*
* Defines whether ERROR level log messages will will appear in the console
*
* Default is true
*/
public static var logError : Boolean = true;
}
}
|
Format settings in consistent and readable manner
|
Format settings in consistent and readable manner
Remove inconsistencies in formatting. Fix differences between defaults in descriptions and setting values.
|
ActionScript
|
mpl-2.0
|
jlacivita/flashls,tedconf/flashls,JulianPena/flashls,mangui/flashls,Boxie5/flashls,clappr/flashls,fixedmachine/flashls,Peer5/flashls,loungelogic/flashls,aevange/flashls,aevange/flashls,NicolasSiver/flashls,tedconf/flashls,mangui/flashls,jlacivita/flashls,NicolasSiver/flashls,hola/flashls,aevange/flashls,codex-corp/flashls,Peer5/flashls,neilrackett/flashls,Corey600/flashls,Boxie5/flashls,dighan/flashls,Corey600/flashls,neilrackett/flashls,thdtjsdn/flashls,clappr/flashls,hola/flashls,dighan/flashls,loungelogic/flashls,vidible/vdb-flashls,vidible/vdb-flashls,fixedmachine/flashls,Peer5/flashls,Peer5/flashls,aevange/flashls,codex-corp/flashls,JulianPena/flashls,thdtjsdn/flashls
|
ef967cc8cda2e9c3eb3be8cb7fad91df30a492eb
|
WeaveCore/src/weave/utils/MethodChainProxy.as
|
WeaveCore/src/weave/utils/MethodChainProxy.as
|
/*
Weave (Web-based Analysis and Visualization Environment)
Copyright (C) 2008-2011 University of Massachusetts Lowell
This file is a part of Weave.
Weave is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, Version 3,
as published by the Free Software Foundation.
Weave is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Weave. If not, see <http://www.gnu.org/licenses/>.
*/
package weave.utils
{
import flash.utils.Proxy;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
/**
* This is a Proxy object that wraps function calls in a way that allows method chaining (<code>obj.f(1).g(2).h(3)</code>).
* Multiple objects can be wrapped in a single MethodChainProxy object.
* In that case, method calls will use the first object with a matching property name.
* If a wrapped function returns a value, it can be accessed using valueOf(): <code>obj.f(1).g(2).valueOf()</code>
* Non-function properties are automatically wrapped in setter/getter functions that will set the value if given one parameter
* and get the value if given zero parameters.
*
* @example
* <listing version="3.0">
* var shape:Shape = new Shape();
* var graphicsChain:MethodChainProxy = new MethodChainProxy(shape, shape.graphics);
*
* this.rawChildren.addChild(shape);
*
* graphicsChain.lineStyle(1,1,1)
* .moveTo(0,0)
* .lineTo(10,10)
* .lineTo(10,0)
* .lineTo(0,0)
* .x(20)
* .y(40)
* .scaleX(3)
* .scaleY(4);
*
* trace( 'Width of shape is:', graphicsChain.width() );
* trace( 'getRect() returns:', graphicsChain.getRect(this).valueOf() );
* </listing>
*
* @author adufilie
*/
public dynamic class MethodChainProxy extends Proxy
{
/**
* Constructor.
* @param object The primary object to be proxied by chainable method wrappers, or null if you wish to specify objects in an Array in the moreObjects parameter.
* @param moreObjects Additional objects to be checked in order in case properties/methods do not exist on the primary object.
* You may specify a single Array as the moreObjects parameter if the primary object parameter is set to null.
*/
public function MethodChainProxy(primaryObject:Object, ...moreObjects):void
{
if (primaryObject == null && moreObjects.length == 1 && moreObjects[0] is Array)
moreObjects = (moreObjects[0] as Array).concat();
else
moreObjects.unshift(primaryObject);
_objectsToCheck = moreObjects;
_classNames = _objectsToCheck.map(function(o:*):* { return getQualifiedClassName(o); });
_thisQName = getQualifiedClassName(this);
var i:int = _classNames.indexOf('Object');
if (i >= 0)
_classNames[i] = _thisQName;
else
_classNames.push(_thisQName);
}
private var _thisQName:String;
private var _objectsToCheck:Array;
private var _classNames:Array;
private var _wrappers:Object = {};
private var _hosts:Object = {};
private var _result:*;
/**
* Gets the value returned from the last function call.
*/
public function valueOf():*
{
return _result;
}
private function _getWrapper(host:Object, property:String):*
{
// used cached wrapper function if it exists
if (_wrappers.hasOwnProperty(property))
return _wrappers[property] as Function;
// cache a new wrapper function
var wrapper:*;
if (host[property] is Function)
wrapper = _newFunctionWrapper(host, property);
else
wrapper = _newSetterGetter(host, property);
return _wrappers[property] = wrapper;
}
private function _newFunctionWrapper(host:Object, property:String):Function
{
// create a wrapper function that supports method chaining
var isProxy:Boolean = host is Proxy;
var _this:* = this;
return function(...args):* {
_this._result = undefined; // in case error is thrown
if (isProxy)
_this._result = (host as Proxy).flash_proxy::callProperty(property, args);
else
_this._result = host[property].apply(host, args);
return _this; // return MethodChainProxy to allow method chaining
};
}
private function _newSetterGetter(host:Object, property:String):Function
{
// create a property setter/getter
var _this:* = this;
return function(...args):* {
_this._result = undefined; // in case error is thrown
if (args.length == 0)
{
// 'getter' mode - return the value
return _this._result = host[property];
}
if (args.length == 1)
{
// 'setter' mode - allows method chaining
_this._result = host[property] = args[0];
return _this;
}
throw new Error(_thisQName + '.' + property + '(): Invalid number of arguments. Expecting 0 or 1.');
};
}
private function _throwError(propertyName:String):void
{
throw new Error('There is no property named "' + propertyName + '" on ' + _classNames.join(' or '));
}
private function _findHost(name:*, checkBuiltIns:Boolean):Object
{
var host:Object;
for each (host in _objectsToCheck)
if (host.hasOwnProperty(name))
return _hosts[name] = host;
if (checkBuiltIns)
for each (host in _objectsToCheck)
if (name in host)
return _hosts[name] = host;
return null;
}
override flash_proxy function hasProperty(name:*):Boolean
{
if (_hosts.hasOwnProperty(name) || _findHost(name, false))
return true;
return false;
}
override flash_proxy function getProperty(name:*):*
{
if (name == 'valueOf')
return valueOf as Function;
if (_wrappers.hasOwnProperty(name))
return _wrappers[name];
if (_hosts.hasOwnProperty(name) || _findHost(name, true))
return _getWrapper(_hosts[name], name);
_throwError(name);
}
override flash_proxy function setProperty(name:*, value:*):void
{
if (_hosts.hasOwnProperty(name) || _findHost(name, true))
{
_hosts[name][name] = value;
return;
}
_throwError(name);
}
override flash_proxy function callProperty(name:*, ...parameters):*
{
var method:*;
if (_wrappers.hasOwnProperty(name))
method = _wrappers[name];
else
method = flash_proxy::getProperty(name);
try
{
return method.apply(_hosts[name], parameters);
}
catch (e:Error)
{
e.message = _thisQName + '.' + name + '(): ' + e.message;
throw e;
}
}
}
}
|
/*
Weave (Web-based Analysis and Visualization Environment)
Copyright (C) 2008-2011 University of Massachusetts Lowell
This file is a part of Weave.
Weave is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License, Version 3,
as published by the Free Software Foundation.
Weave is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Weave. If not, see <http://www.gnu.org/licenses/>.
*/
package weave.utils
{
import flash.utils.Proxy;
import flash.utils.flash_proxy;
import flash.utils.getQualifiedClassName;
/**
* This is a Proxy object that wraps function calls in a way that allows method chaining (<code>obj.f(1).g(2).h(3)</code>).
* Multiple objects can be wrapped in a single MethodChainProxy object.
* In that case, method calls will use the first object with a matching property name.
* If a wrapped function returns a value, it can be accessed using valueOf(): <code>obj.f(1).g(2).valueOf()</code>
* Non-function properties are automatically wrapped in setter/getter functions that will set the value if given one parameter
* and get the value if given zero parameters.
*
* @example
* <listing version="3.0">
* var shape:Shape = new Shape();
* var graphicsChain:MethodChainProxy = new MethodChainProxy(shape, shape.graphics);
*
* this.rawChildren.addChild(shape);
*
* graphicsChain.lineStyle(1,1,1)
* .moveTo(0,0)
* .lineTo(10,10)
* .lineTo(10,0)
* .lineTo(0,0)
* .x(20)
* .y(40)
* .scaleX(3)
* .scaleY(4);
*
* trace( 'Width of shape is:', graphicsChain.width() );
* trace( 'getRect() returns:', graphicsChain.getRect(this).valueOf() );
* </listing>
*
* @author adufilie
*/
public dynamic class MethodChainProxy extends Proxy
{
/**
* Constructor.
* @param object The primary object to be proxied by chainable method wrappers, or null if you wish to specify objects in an Array in the moreObjects parameter.
* @param moreObjects Additional objects to be checked in order in case properties/methods do not exist on the primary object.
* You may specify a single Array as the moreObjects parameter if the primary object parameter is set to null.
*/
public function MethodChainProxy(primaryObject:Object, ...moreObjects):void
{
if (primaryObject == null && moreObjects.length == 1 && moreObjects[0] is Array)
moreObjects = (moreObjects[0] as Array).concat();
else
moreObjects.unshift(primaryObject);
_objectsToCheck = moreObjects;
_classNames = _objectsToCheck.map(function(o:*, ..._):* { return getQualifiedClassName(o); });
_thisQName = getQualifiedClassName(this);
var i:int = _classNames.indexOf('Object');
if (i >= 0)
_classNames[i] = _thisQName;
else
_classNames.push(_thisQName);
}
private var _thisQName:String;
private var _objectsToCheck:Array;
private var _classNames:Array;
private var _wrappers:Object = {};
private var _hosts:Object = {};
private var _result:*;
/**
* Gets the value returned from the last function call.
*/
public function valueOf():*
{
return _result;
}
private function _getWrapper(host:Object, property:String):*
{
// used cached wrapper function if it exists
if (_wrappers.hasOwnProperty(property))
return _wrappers[property] as Function;
// cache a new wrapper function
var wrapper:*;
if (host[property] is Function)
wrapper = _newFunctionWrapper(host, property);
else
wrapper = _newSetterGetter(host, property);
return _wrappers[property] = wrapper;
}
private function _newFunctionWrapper(host:Object, property:String):Function
{
// create a wrapper function that supports method chaining
var isProxy:Boolean = host is Proxy;
var _this:* = this;
return function(...args):* {
_this._result = undefined; // in case error is thrown
if (isProxy)
_this._result = (host as Proxy).flash_proxy::callProperty(property, args);
else
_this._result = host[property].apply(host, args);
return _this; // return MethodChainProxy to allow method chaining
};
}
private function _newSetterGetter(host:Object, property:String):Function
{
// create a property setter/getter
var _this:* = this;
return function(...args):* {
_this._result = undefined; // in case error is thrown
if (args.length == 0)
{
// 'getter' mode - return the value
return _this._result = host[property];
}
if (args.length == 1)
{
// 'setter' mode - allows method chaining
_this._result = host[property] = args[0];
return _this;
}
throw new Error(_thisQName + '.' + property + '(): Invalid number of arguments. Expecting 0 or 1.');
};
}
private function _throwError(propertyName:String):void
{
throw new Error('There is no property named "' + propertyName + '" on ' + _classNames.join(' or '));
}
private function _findHost(name:*, checkBuiltIns:Boolean):Object
{
var host:Object;
for each (host in _objectsToCheck)
if (host.hasOwnProperty(name))
return _hosts[name] = host;
if (checkBuiltIns)
for each (host in _objectsToCheck)
if (name in host)
return _hosts[name] = host;
return null;
}
override flash_proxy function hasProperty(name:*):Boolean
{
if (_hosts.hasOwnProperty(name) || _findHost(name, false))
return true;
return false;
}
override flash_proxy function getProperty(name:*):*
{
if (name == 'valueOf')
return valueOf as Function;
if (_wrappers.hasOwnProperty(name))
return _wrappers[name];
if (_hosts.hasOwnProperty(name) || _findHost(name, true))
return _getWrapper(_hosts[name], name);
_throwError(name);
}
override flash_proxy function setProperty(name:*, value:*):void
{
if (_hosts.hasOwnProperty(name) || _findHost(name, true))
{
_hosts[name][name] = value;
return;
}
_throwError(name);
}
override flash_proxy function callProperty(name:*, ...parameters):*
{
var method:*;
if (_wrappers.hasOwnProperty(name))
method = _wrappers[name];
else
method = flash_proxy::getProperty(name);
try
{
return method.apply(_hosts[name], parameters);
}
catch (e:Error)
{
e.message = _thisQName + '.' + name + '(): ' + e.message;
throw e;
}
}
}
}
|
add ..._
|
add ..._
|
ActionScript
|
mpl-2.0
|
WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS,WeaveTeam/WeaveJS
|
7ca0d2473073f9d201d8beda9ab89b9442bea813
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/emitter/Emitter.as
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/emitter/Emitter.as
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker.emitter
{
import com.adobe.net.URI;
import com.snowplowanalytics.snowplow.tracker.Constants;
import com.snowplowanalytics.snowplow.tracker.Util;
import com.snowplowanalytics.snowplow.tracker.event.EmitterEvent;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
public class Emitter extends EventDispatcher
{
private var _uri:URI;
private var _buffer:Array = [];
protected var bufferSize:int = BufferOption.DEFAULT;
protected var httpMethod:String = URLRequestMethod.GET;
/**
* Create an Emitter instance with a collector URL and HttpMethod to send requests.
* @param URI The collector URL. Don't include "http://" - this is done automatically.
* @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>.
* @param successCallback The callback function to handle success cases when sending events.
* @param errorCallback The callback function to handle error cases when sending events.
*/
public function Emitter(uri:String, httpMethod:String = "get") {
if (httpMethod == URLRequestMethod.GET) {
_uri = new URI("http://" + uri + "/i");
} else { // POST
_uri = new URI("http://" + uri + "/" + Constants.PROTOCOL_VENDOR + "/" + Constants.PROTOCOL_VERSION);
}
this.httpMethod = httpMethod;
}
/**
* Sets whether the buffer should send events instantly or after the buffer has reached
* it's limit. By default, this is set to BufferOption Default.
* @param option Set the BufferOption enum to Instant send events upon creation.
*/
public function setBufferSize(option:int):void {
this.bufferSize = option;
}
/**
* Add event payloads to the emitter's buffer
* @param payload Payload to be added
*/
public function addToBuffer(payload:IPayload):void {
_buffer.push(payload);
if (_buffer.length == bufferSize)
flushBuffer();
}
/**
* Sends all events in the buffer to the collector.
*/
public function checkBufferComplete(successCount:int, totalCount:int, totalPayloads:int, unsentPayloads:Array):void {
if (totalCount == totalPayloads)
{
if (unsentPayloads.length == 0)
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, successCount));
}
else
{
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, successCount, unsentPayloads, "Not all items in buffer were sent"));
}
}
}
/**
* Sends all events in the buffer to the collector.
*/
public function flushBuffer():void {
if (_buffer.length == 0) {
trace("Buffer is empty, exiting flush operation.");
return;
}
if (httpMethod == URLRequestMethod.GET) {
var successCount:int = 0;
var totalCount:int = 0;
var totalPayloads:int = _buffer.length;
var unsentPayloads:Array = [];
for each (var getPayload:IPayload in _buffer) {
sendGetData(getPayload,
function onGetSuccess (data:*):void {
successCount++;
totalCount++;
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
},
function onGetError ():void {
totalCount++;
unsentPayloads.push(payload);
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
}
);
}
} else if (httpMethod == URLRequestMethod.POST) {
var unsentPayload:Array = [];
var postPayload:SchemaPayload = new SchemaPayload();
postPayload.setSchema(Constants.SCHEMA_PAYLOAD_DATA);
var eventMaps:Array = [];
for each (var payload:IPayload in _buffer) {
eventMaps.push(payload.getMap());
}
postPayload.setData(eventMaps);
sendPostData(postPayload,
function onPostSuccess (data:*):void
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, _buffer.length));
},
function onPostError (event:Event):void
{
unsentPayload.push(postPayload);
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, 0, unsentPayloads, event.toString()));
}
);
}
// Empties current buffer
Util.clearArray(_buffer);
}
protected function sendPostData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
Util.getResponse(_uri.toString(),
successCallback,
errorCallback,
URLRequestMethod.POST,
payload.toString());
}
protected function sendGetData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
var hashMap:Object = payload.getMap();
_uri.setQueryByMap(hashMap);
Util.getResponse(_uri.toString(),
successCallback,
errorCallback);
}
}
}
|
/*
* Copyright (c) 2015 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.tracker.emitter
{
import com.adobe.net.URI;
import com.snowplowanalytics.snowplow.tracker.Constants;
import com.snowplowanalytics.snowplow.tracker.Util;
import com.snowplowanalytics.snowplow.tracker.event.EmitterEvent;
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
public class Emitter extends EventDispatcher
{
private var _uri:URI;
private var _buffer:Array = [];
protected var bufferSize:int = BufferOption.DEFAULT;
protected var httpMethod:String = URLRequestMethod.GET;
/**
* Create an Emitter instance with a collector URL and HttpMethod to send requests.
* @param URI The collector URL. Don't include "http://" - this is done automatically.
* @param httpMethod The HTTP request method. If GET, <code>BufferOption</code> is set to <code>Instant</code>.
* @param successCallback The callback function to handle success cases when sending events.
* @param errorCallback The callback function to handle error cases when sending events.
*/
public function Emitter(uri:String, httpMethod:String = URLRequestMethod.GET) {
if (httpMethod == URLRequestMethod.GET) {
_uri = new URI("http://" + uri + "/i");
} else { // POST
_uri = new URI("http://" + uri + "/" + Constants.PROTOCOL_VENDOR + "/" + Constants.PROTOCOL_VERSION);
}
this.httpMethod = httpMethod;
}
/**
* Sets whether the buffer should send events instantly or after the buffer has reached
* it's limit. By default, this is set to BufferOption Default.
* @param option Set the BufferOption enum to Instant send events upon creation.
*/
public function setBufferSize(option:int):void {
this.bufferSize = option;
}
/**
* Add event payloads to the emitter's buffer
* @param payload Payload to be added
*/
public function addToBuffer(payload:IPayload):void {
_buffer.push(payload);
if (_buffer.length == bufferSize)
flushBuffer();
}
/**
* Sends all events in the buffer to the collector.
*/
public function checkBufferComplete(successCount:int, totalCount:int, totalPayloads:int, unsentPayloads:Array):void {
if (totalCount == totalPayloads)
{
if (unsentPayloads.length == 0)
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, successCount));
}
else
{
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, successCount, unsentPayloads, "Not all items in buffer were sent"));
}
}
}
/**
* Sends all events in the buffer to the collector.
*/
public function flushBuffer():void {
if (_buffer.length == 0) {
trace("Buffer is empty, exiting flush operation.");
return;
}
if (httpMethod == URLRequestMethod.GET) {
var successCount:int = 0;
var totalCount:int = 0;
var totalPayloads:int = _buffer.length;
var unsentPayloads:Array = [];
for each (var getPayload:IPayload in _buffer) {
sendGetData(getPayload,
function onGetSuccess (data:*):void {
successCount++;
totalCount++;
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
},
function onGetError ():void {
totalCount++;
unsentPayloads.push(payload);
checkBufferComplete(successCount, totalCount, totalPayloads, unsentPayloads);
}
);
}
} else if (httpMethod == URLRequestMethod.POST) {
var unsentPayload:Array = [];
var postPayload:SchemaPayload = new SchemaPayload();
postPayload.setSchema(Constants.SCHEMA_PAYLOAD_DATA);
var eventMaps:Array = [];
for each (var payload:IPayload in _buffer) {
eventMaps.push(payload.getMap());
}
postPayload.setData(eventMaps);
sendPostData(postPayload,
function onPostSuccess (data:*):void
{
dispatchEvent(new EmitterEvent(EmitterEvent.SUCCESS, _buffer.length));
},
function onPostError (event:Event):void
{
unsentPayload.push(postPayload);
dispatchEvent(new EmitterEvent(EmitterEvent.FAILURE, 0, unsentPayloads, event.toString()));
}
);
}
// Empties current buffer
Util.clearArray(_buffer);
}
protected function sendPostData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
Util.getResponse(_uri.toString(),
successCallback,
errorCallback,
URLRequestMethod.POST,
payload.toString());
}
protected function sendGetData(payload:IPayload, successCallback:Function, errorCallback:Function):void
{
var hashMap:Object = payload.getMap();
_uri.setQueryByMap(hashMap);
Util.getResponse(_uri.toString(),
successCallback,
errorCallback);
}
}
}
|
Use constant in constructor params
|
Use constant in constructor params
|
ActionScript
|
apache-2.0
|
snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker
|
8640073418e7ce4e7adb4e08d483a55cc6a60a29
|
generator/sources/as3/com/kaltura/delegates/WebDelegateBase.as
|
generator/sources/as3/com/kaltura/delegates/WebDelegateBase.as
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {
import com.kaltura.KalturaClient;
import com.kaltura.config.IKalturaConfig;
import com.kaltura.config.KalturaConfig;
import com.kaltura.core.KClassFactory;
import com.kaltura.encryption.MD5;
import com.kaltura.errors.KalturaError;
import com.kaltura.events.KalturaEvent;
import com.kaltura.net.KalturaCall;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {
public static var CONNECT_TIME:int = 120000; //120 secs
public static var LOAD_TIME:int = 120000; //120 secs
protected var connectTimer:Timer;
protected var loadTimer:Timer;
protected var _call:KalturaCall;
protected var _config:KalturaConfig;
protected var loader:URLLoader;
protected var fileRef:FileReference;
//Setters & getters
public function get call():KalturaCall {
return _call;
}
public function set call(newVal:KalturaCall):void {
_call = newVal;
}
public function get config():IKalturaConfig {
return _config;
}
public function set config(newVal:IKalturaConfig):void {
_config = newVal as KalturaConfig;
}
public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
this.call = call;
this.config = config;
if (!call)
return; //maybe a multi request
if (call.useTimeout) {
connectTimer = new Timer(CONNECT_TIME, 1);
connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);
loadTimer = new Timer(LOAD_TIME, 1);
loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
}
execute();
}
public function close():void {
try {
loader.close();
}
catch (e:*) {
}
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
}
protected function onConnectTimeout(event:TimerEvent):void {
var kError:KalturaError = new KalturaError();
kError.errorCode = "CONNECTION_TIMEOUT";
kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
loadTimer.stop();
close();
}
protected function onLoadTimeOut(event:TimerEvent):void {
connectTimer.stop();
close();
var kError:KalturaError = new KalturaError();
kError.errorCode = "POST_TIMEOUT";
kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
protected function execute():void {
if (call == null) {
throw new Error('No call defined.');
}
post(); //post the call
}
/**
* Helper function for sending the call straight to the server
*/
protected function post():void {
addOptionalArguments();
formatRequest();
sendRequest();
if (call.useTimeout) {
connectTimer.start();
}
}
protected function formatRequest():void {
//The configuration is stronger then the args
if (_config.partnerId != null && _call.args["partnerId"] == -1)
_call.setRequestArgument("partnerId", _config.partnerId);
if (_config.ks != null)
_call.setRequestArgument("ks", _config.ks);
if (_config.clientTag != null)
_call.setRequestArgument("clientTag", _config.clientTag);
_call.setRequestArgument("ignoreNull", _config.ignoreNull);
_call.setRequestArgument("apiVersion", KalturaClient.API_VERSION);
//Create signature hash.
//call.setRequestArgument("kalsig", getMD5Checksum(call));
}
protected function getMD5Checksum(call:KalturaCall):String {
var props:Array = new Array();
for (var arg:String in call.args)
props.push(arg);
props.sort();
var s:String = "";
for each (var prop:String in props) {
if ( call.args[prop] )
s += prop + call.args[prop];
}
return MD5.encrypt(s);
}
protected function sendRequest():void {
//construct the loader
createURLLoader();
//Create signature hash.
var kalsig:String = getMD5Checksum(call);
//create the service request for normal calls
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;
if (_call.method == URLRequestMethod.GET)
url += "&";
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
req.data = call.args;
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(req);
}
protected function createURLLoader():void {
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onDataComplete);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.addEventListener(Event.OPEN, onOpen);
}
protected function onHTTPStatus(event:HTTPStatusEvent):void {
}
protected function onOpen(event:Event):void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.start();
}
}
protected function addOptionalArguments():void {
//add optional args here
}
// Event Handlers
/**
* try to process received data.
* if procesing failed, let call handle the processing error
* @param event load complete event
*/
protected function onDataComplete(event:Event):void {
try {
handleResult(XML(event.target.data));
}
catch (e:Error) {
var kErr:KalturaError = new KalturaError();
kErr.errorCode = String(e.errorID);
kErr.errorMsg = e.message;
_call.handleError(kErr);
}
}
/**
* handle io or security error events from the loader.
* create relevant KalturaError, let the call process it.
* @param event
*/
protected function onError(event:ErrorEvent):void {
clean();
var kError:KalturaError = createKalturaError(event, loader.data);
if (!kError) {
kError = new KalturaError();
kError.errorMsg = event.text;
kError.errorCode = event.type; // either IOErrorEvent.IO_ERROR or SecurityErrorEvent.SECURITY_ERROR
}
call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
/**
* parse the server's response and let the call process it.
* @param result server's response
*/
protected function handleResult(result:XML):void {
clean();
var error:KalturaError = validateKalturaResponse(result);
if (error == null) {
var digestedResult:Object = parse(result);
call.handleResult(digestedResult);
}
else {
call.handleError(error);
}
}
/**
* stop timers and clean event listeners
*/
protected function clean():void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
if (loader == null) {
return;
}
loader.removeEventListener(Event.COMPLETE, onDataComplete);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.removeEventListener(Event.OPEN, onOpen);
}
/**
* create the correct object and populate it with the given values. if the needed class is not found
* in the file, a generic object is created with attributes matching the XML attributes.
* Override this parssing function in the specific delegate to create the correct object.
* @param result instance attributes
* @return an instance of the class declared by the given XML.
* */
public function parse(result:XML):* {
//by defualt create the response object
var cls:Class;
try {
cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
}
catch (e:Error) {
cls = Object;
}
var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
return obj;
}
/**
* If the result string holds an error, return a KalturaError object with
* relevant values. <br/>
* Overide this to create validation object and fill it.
* @param result the string returned from the server.
* @return matching error object
*/
protected function validateKalturaResponse(result:String):KalturaError {
var kError:KalturaError = null;
var xml:XML = XML(result);
if (xml.result.hasOwnProperty('error')
&& xml.result.error.hasOwnProperty('code')
&& xml.result.error.hasOwnProperty('message')) {
kError = new KalturaError();
kError.errorCode = String(xml.result.error.code);
kError.errorMsg = xml.result.error.message;
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
return kError;
}
/**
* create error object and fill it with relevant details
* @param event
* @param loaderData
* @return detailed KalturaError to be processed
*/
protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
var ke:KalturaError = new KalturaError();
ke.errorMsg = event.text;
ke.errorCode = event.type;
return ke;
}
/**
* create the url that is used for serve actions
* @param call the KalturaCall that defines the required parameters
* @return URLRequest with relevant parameters
* */
public function getServeUrl(call:KalturaCall):URLRequest {
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
for (var key:String in call.args) {
url += "&" + key + "=" + call.args[key];
}
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
// req.data = call.args;
return req;
}
}
}
|
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {
import com.kaltura.KalturaClient;
import com.kaltura.config.IKalturaConfig;
import com.kaltura.config.KalturaConfig;
import com.kaltura.core.KClassFactory;
import com.kaltura.encryption.MD5;
import com.kaltura.errors.KalturaError;
import com.kaltura.events.KalturaEvent;
import com.kaltura.net.KalturaCall;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.HTTPStatusEvent;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TimerEvent;
import flash.net.FileReference;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.Timer;
import flash.utils.getDefinitionByName;
public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {
public static var CONNECT_TIME:int = 120000; //120 secs
public static var LOAD_TIME:int = 120000; //120 secs
protected var connectTimer:Timer;
protected var loadTimer:Timer;
protected var _call:KalturaCall;
protected var _config:KalturaConfig;
protected var loader:URLLoader;
protected var fileRef:FileReference;
//Setters & getters
public function get call():KalturaCall {
return _call;
}
public function set call(newVal:KalturaCall):void {
_call = newVal;
}
public function get config():IKalturaConfig {
return _config;
}
public function set config(newVal:IKalturaConfig):void {
_config = newVal as KalturaConfig;
}
public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
this.call = call;
this.config = config;
if (!call)
return; //maybe a multi request
if (call.useTimeout) {
connectTimer = new Timer(CONNECT_TIME, 1);
connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);
loadTimer = new Timer(LOAD_TIME, 1);
loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
}
execute();
}
public function close():void {
try {
loader.close();
}
catch (e:*) {
}
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
}
protected function onConnectTimeout(event:TimerEvent):void {
var kError:KalturaError = new KalturaError();
kError.errorCode = "CONNECTION_TIMEOUT";
kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
loadTimer.stop();
close();
}
protected function onLoadTimeOut(event:TimerEvent):void {
connectTimer.stop();
close();
var kError:KalturaError = new KalturaError();
kError.errorCode = "POST_TIMEOUT";
kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
_call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
protected function execute():void {
if (call == null) {
throw new Error('No call defined.');
}
post(); //post the call
}
/**
* Helper function for sending the call straight to the server
*/
protected function post():void {
addOptionalArguments();
formatRequest();
sendRequest();
if (call.useTimeout) {
connectTimer.start();
}
}
protected function formatRequest():void {
//The configuration is stronger then the args
if (_config.partnerId != null && (!_call.args["partnerId"] || _call.args["partnerId"]==-1))
_call.setRequestArgument("partnerId", _config.partnerId);
if (_config.ks != null)
_call.setRequestArgument("ks", _config.ks);
if (_config.clientTag != null)
_call.setRequestArgument("clientTag", _config.clientTag);
_call.setRequestArgument("ignoreNull", _config.ignoreNull);
_call.setRequestArgument("apiVersion", KalturaClient.API_VERSION);
//Create signature hash.
//call.setRequestArgument("kalsig", getMD5Checksum(call));
}
protected function getMD5Checksum(call:KalturaCall):String {
var props:Array = new Array();
for (var arg:String in call.args)
props.push(arg);
props.sort();
var s:String = "";
for each (var prop:String in props) {
if ( call.args[prop] )
s += prop + call.args[prop];
}
return MD5.encrypt(s);
}
protected function sendRequest():void {
//construct the loader
createURLLoader();
//Create signature hash.
var kalsig:String = getMD5Checksum(call);
//create the service request for normal calls
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;
if (_call.method == URLRequestMethod.GET)
url += "&";
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
req.data = call.args;
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.load(req);
}
protected function createURLLoader():void {
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onDataComplete);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.addEventListener(Event.OPEN, onOpen);
}
protected function onHTTPStatus(event:HTTPStatusEvent):void {
}
protected function onOpen(event:Event):void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.start();
}
}
protected function addOptionalArguments():void {
//add optional args here
}
// Event Handlers
/**
* try to process received data.
* if procesing failed, let call handle the processing error
* @param event load complete event
*/
protected function onDataComplete(event:Event):void {
try {
handleResult(XML(event.target.data));
}
catch (e:Error) {
var kErr:KalturaError = new KalturaError();
kErr.errorCode = String(e.errorID);
kErr.errorMsg = e.message;
_call.handleError(kErr);
}
}
/**
* handle io or security error events from the loader.
* create relevant KalturaError, let the call process it.
* @param event
*/
protected function onError(event:ErrorEvent):void {
clean();
var kError:KalturaError = createKalturaError(event, loader.data);
if (!kError) {
kError = new KalturaError();
kError.errorMsg = event.text;
kError.errorCode = event.type; // either IOErrorEvent.IO_ERROR or SecurityErrorEvent.SECURITY_ERROR
}
call.handleError(kError);
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
/**
* parse the server's response and let the call process it.
* @param result server's response
*/
protected function handleResult(result:XML):void {
clean();
var error:KalturaError = validateKalturaResponse(result);
if (error == null) {
var digestedResult:Object = parse(result);
call.handleResult(digestedResult);
}
else {
call.handleError(error);
}
}
/**
* stop timers and clean event listeners
*/
protected function clean():void {
if (call.useTimeout) {
connectTimer.stop();
loadTimer.stop();
}
if (loader == null) {
return;
}
loader.removeEventListener(Event.COMPLETE, onDataComplete);
loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
loader.removeEventListener(Event.OPEN, onOpen);
}
/**
* create the correct object and populate it with the given values. if the needed class is not found
* in the file, a generic object is created with attributes matching the XML attributes.
* Override this parssing function in the specific delegate to create the correct object.
* @param result instance attributes
* @return an instance of the class declared by the given XML.
* */
public function parse(result:XML):* {
//by defualt create the response object
var cls:Class;
try {
cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
}
catch (e:Error) {
cls = Object;
}
var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
return obj;
}
/**
* If the result string holds an error, return a KalturaError object with
* relevant values. <br/>
* Overide this to create validation object and fill it.
* @param result the string returned from the server.
* @return matching error object
*/
protected function validateKalturaResponse(result:String):KalturaError {
var kError:KalturaError = null;
var xml:XML = XML(result);
if (xml.result.hasOwnProperty('error')
&& xml.result.error.hasOwnProperty('code')
&& xml.result.error.hasOwnProperty('message')) {
kError = new KalturaError();
kError.errorCode = String(xml.result.error.code);
kError.errorMsg = xml.result.error.message;
dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
}
return kError;
}
/**
* create error object and fill it with relevant details
* @param event
* @param loaderData
* @return detailed KalturaError to be processed
*/
protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
var ke:KalturaError = new KalturaError();
ke.errorMsg = event.text;
ke.errorCode = event.type;
return ke;
}
/**
* create the url that is used for serve actions
* @param call the KalturaCall that defines the required parameters
* @return URLRequest with relevant parameters
* */
public function getServeUrl(call:KalturaCall):URLRequest {
var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
for (var key:String in call.args) {
url += "&" + key + "=" + call.args[key];
}
var req:URLRequest = new URLRequest(url);
req.contentType = "application/x-www-form-urlencoded";
req.method = call.method;
// req.data = call.args;
return req;
}
}
}
|
Fix client code to send partnerId from client config by default. Fix By Michal.
|
Fix client code to send partnerId from client config by default.
Fix By Michal.
|
ActionScript
|
agpl-3.0
|
matsuu/server,gale320/server,DBezemer/server,gale320/server,ratliff/server,kaltura/server,jorgevbo/server,doubleshot/server,matsuu/server,jorgevbo/server,ivesbai/server,ratliff/server,gale320/server,jorgevbo/server,DBezemer/server,ratliff/server,DBezemer/server,jorgevbo/server,ivesbai/server,gale320/server,ratliff/server,kaltura/server,matsuu/server,ivesbai/server,gale320/server,jorgevbo/server,matsuu/server,doubleshot/server,DBezemer/server,ratliff/server,ivesbai/server,ratliff/server,doubleshot/server,jorgevbo/server,ivesbai/server,doubleshot/server,doubleshot/server,DBezemer/server,matsuu/server,jorgevbo/server,ivesbai/server,gale320/server,ivesbai/server,DBezemer/server,kaltura/server,ratliff/server,doubleshot/server,doubleshot/server,matsuu/server,kaltura/server,ratliff/server,gale320/server,ivesbai/server,matsuu/server,matsuu/server,jorgevbo/server,gale320/server,DBezemer/server,kaltura/server,kaltura/server,DBezemer/server,doubleshot/server
|
eaaa1bf8ab6ece8c9f4c29e6cbb6fd28f9f0d4de
|
src/com/esri/builder/controllers/supportClasses/LocalConnectionDelegate.as
|
src/com/esri/builder/controllers/supportClasses/LocalConnectionDelegate.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers.supportClasses
{
import com.esri.builder.supportClasses.LogUtil;
import flash.events.StatusEvent;
import flash.net.LocalConnection;
import mx.logging.ILogger;
import mx.logging.Log;
public final class LocalConnectionDelegate
{
private static const LOG:ILogger = LogUtil.createLogger(LocalConnectionDelegate);
private static const CONNECTION_NAME:String = '_flexViewer';
private var _localConnection:LocalConnection;
private function get localConnection():LocalConnection
{
if (_localConnection === null)
{
if (Log.isDebug())
{
LOG.debug("Acquiring local connection");
}
_localConnection = new LocalConnection();
_localConnection.addEventListener(StatusEvent.STATUS, localConnection_statusHandler);
}
return _localConnection;
}
private function localConnection_statusHandler(event:StatusEvent):void
{
if (event.level == "error")
{
if (Log.isDebug())
{
LOG.debug("Call failed: {0}", event.toString());
}
}
}
public function setTitles(title:String, subtitle:String):void
{
if (Log.isDebug())
{
LOG.debug("Sending titles changes: title {0} - subtitle {1}", title, subtitle);
}
callViewerMethod('setTitles', title, subtitle);
}
private function callViewerMethod(methodName:String, ... values):void
{
try
{
//use Function#apply to avoid passing rest argument as Array
localConnection.send.apply(null, [ CONNECTION_NAME, methodName ].concat(values));
}
catch (error:Error)
{
if (Log.isDebug())
{
LOG.debug("Call to Viewer method {0} failed: {1}", methodName, error);
}
}
}
public function setLogo(value:String):void
{
if (Log.isDebug())
{
LOG.debug("Sending logo changes {0}", value);
}
callViewerMethod('setLogo', value);
}
public function setTextColor(value:uint):void
{
if (Log.isDebug())
{
LOG.debug("Sending text color changes {0}", value);
}
callViewerMethod('setTextColor', value);
}
public function setBackgroundColor(value:uint):void
{
if (Log.isDebug())
{
LOG.debug("Sending background color changes {0}", value);
}
callViewerMethod('setBackgroundColor', value);
}
public function setRolloverColor(value:uint):void
{
if (Log.isDebug())
{
LOG.debug("Sending rollover color changes {0}", value);
}
callViewerMethod('setRolloverColor', value);
}
public function setSelectionColor(value:uint):void
{
if (Log.isDebug())
{
LOG.debug("Sending selection color changes {0}", value);
}
callViewerMethod('setSelectionColor', value);
}
public function setTitleColor(value:uint):void
{
if (Log.isDebug())
{
LOG.debug("Sending title color changes {0}", value);
}
callViewerMethod('setTitleColor', value);
}
public function setLocale(localeChain:String):void
{
if (Log.isDebug())
{
LOG.debug("Sending locale changes {0}", localeChain);
}
callViewerMethod('setLocale', localeChain);
}
public function setFontName(value:String):void
{
if (Log.isDebug())
{
LOG.debug("Sending font name changes {0}", value);
}
callViewerMethod('setFontName', value);
}
public function setAppTitleFontName(value:String):void
{
if (Log.isDebug())
{
LOG.debug("Sending app title font name changes {0}", value);
}
callViewerMethod('setAppTitleFontName', value);
}
public function setSubTitleFontName(value:String):void
{
if (Log.isDebug())
{
LOG.debug("Sending subtitle font name changes {0}", value);
}
callViewerMethod('setSubTitleFontName', value);
}
public function setAlpha(value:Number):void
{
if (Log.isDebug())
{
LOG.debug("Sending alpha changes {0}", value);
}
callViewerMethod('setAlpha', value);
}
public function setPredefinedStyles(value:Object):void
{
if (Log.isDebug())
{
LOG.debug("Sending predefined changes {0}", value);
}
callViewerMethod('setPredefinedStyles', value);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers.supportClasses
{
import com.esri.builder.supportClasses.LogUtil;
import flash.events.StatusEvent;
import flash.net.LocalConnection;
import mx.logging.ILogger;
import mx.logging.Log;
public final class LocalConnectionDelegate
{
private static const LOG:ILogger = LogUtil.createLogger(LocalConnectionDelegate);
private static const CONNECTION_NAME:String = '_flexViewer';
private var _localConnection:LocalConnection;
private function get localConnection():LocalConnection
{
if (_localConnection === null)
{
if (Log.isDebug())
{
LOG.debug("Acquiring local connection");
}
_localConnection = new LocalConnection();
_localConnection.addEventListener(StatusEvent.STATUS, localConnection_statusHandler);
}
return _localConnection;
}
private function localConnection_statusHandler(event:StatusEvent):void
{
if (event.level == "error")
{
if (Log.isDebug())
{
LOG.debug("Call failed: {0}", event.toString());
}
}
}
public function setTitles(title:String, subtitle:String):void
{
callViewerMethod('setTitles', title, subtitle);
}
private function callViewerMethod(methodName:String, ... values):void
{
if (Log.isDebug())
{
LOG.debug("Calling Viewer method: {0} with the following arguments: {1}", methodName, values);
}
try
{
//use Function#apply to avoid passing rest argument as Array
localConnection.send.apply(null, [ CONNECTION_NAME, methodName ].concat(values));
}
catch (error:Error)
{
if (Log.isDebug())
{
LOG.debug("Call to method {0} failed: {1}", methodName, error);
}
}
}
public function setLogo(value:String):void
{
callViewerMethod('setLogo', value);
}
public function setTextColor(value:uint):void
{
callViewerMethod('setTextColor', value);
}
public function setBackgroundColor(value:uint):void
{
callViewerMethod('setBackgroundColor', value);
}
public function setRolloverColor(value:uint):void
{
callViewerMethod('setRolloverColor', value);
}
public function setSelectionColor(value:uint):void
{
callViewerMethod('setSelectionColor', value);
}
public function setTitleColor(value:uint):void
{
callViewerMethod('setTitleColor', value);
}
public function setLocale(localeChain:String):void
{
callViewerMethod('setLocale', localeChain);
}
public function setFontName(value:String):void
{
callViewerMethod('setFontName', value);
}
public function setAppTitleFontName(value:String):void
{
callViewerMethod('setAppTitleFontName', value);
}
public function setSubTitleFontName(value:String):void
{
callViewerMethod('setSubTitleFontName', value);
}
public function setAlpha(value:Number):void
{
callViewerMethod('setAlpha', value);
}
public function setPredefinedStyles(value:Object):void
{
callViewerMethod('setPredefinedStyles', value);
}
}
}
|
Generalize method call log messages.
|
Generalize method call log messages.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
c2eebc8b19c392a234e9c61284ca272bf8be645e
|
frameworks/projects/Graphics/src/main/flex/GraphicsClasses.as
|
frameworks/projects/Graphics/src/main/flex/GraphicsClasses.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
{
/**
* @private
* This class is used to link additional classes into rpc.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
*/
internal class GraphicsClasses
{
import org.apache.flex.svg.GraphicContainer; GraphicContainer;
import org.apache.flex.svg.GraphicShape; GraphicShape;
import org.apache.flex.svg.Rect; Rect;
import org.apache.flex.svg.Ellipse; Ellipse;
import org.apache.flex.svg.Circle; Circle;
import org.apache.flex.svg.Path; Path;
import org.apache.flex.graphics.SolidColor; SolidColor;
import org.apache.flex.graphics.SolidColorStroke; SolidColorStroke;
import org.apache.flex.svg.Text; Text;
import org.apache.flex.svg.CompoundGraphic; CompoundGraphic;
import org.apache.flex.svg.LinearGradient; LinearGradient;
import org.apache.flex.graphics.CubicCurve; CubicCurve;
import org.apache.flex.graphics.LineStyle; LineStyle;
import org.apache.flex.graphics.LineTo; LineTo;
import org.apache.flex.graphics.MoveTo; MoveTo;
import org.apache.flex.graphics.PathBuilder; PathBuilder;
import org.apache.flex.graphics.QuadraticCurve; QuadraticCurve;
import org.apache.flex.svg.DOMWrapper; DOMWrapper;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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
{
/**
* @private
* This class is used to link additional classes into rpc.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
*/
internal class GraphicsClasses
{
import org.apache.flex.svg.GraphicContainer; GraphicContainer;
import org.apache.flex.svg.GraphicShape; GraphicShape;
import org.apache.flex.svg.Rect; Rect;
import org.apache.flex.svg.Ellipse; Ellipse;
import org.apache.flex.svg.Circle; Circle;
import org.apache.flex.svg.Path; Path;
import org.apache.flex.graphics.SolidColor; SolidColor;
import org.apache.flex.graphics.SolidColorStroke; SolidColorStroke;
import org.apache.flex.svg.Text; Text;
import org.apache.flex.svg.CompoundGraphic; CompoundGraphic;
import org.apache.flex.svg.TransformBead; TransformBead;
import org.apache.flex.svg.LinearGradient; LinearGradient;
import org.apache.flex.graphics.CubicCurve; CubicCurve;
import org.apache.flex.graphics.LineStyle; LineStyle;
import org.apache.flex.graphics.LineTo; LineTo;
import org.apache.flex.graphics.MoveTo; MoveTo;
import org.apache.flex.graphics.PathBuilder; PathBuilder;
import org.apache.flex.graphics.QuadraticCurve; QuadraticCurve;
import org.apache.flex.svg.DOMWrapper; DOMWrapper;
}
}
|
Add transform bead to GraphicClasses
|
Add transform bead to GraphicClasses
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
a9d538c92f9378a280d1c962874b5f6f686b76c1
|
frameworks/as/src/FlexJSUIClasses.as
|
frameworks/as/src/FlexJSUIClasses.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
{
/**
* @private
* This class is used to link additional classes into rpc.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
*/
internal class FlexJSUIClasses
{
import org.apache.flex.html.staticControls.beads.IButtonBead; IButtonBead;
import org.apache.flex.html.staticControls.beads.CSSTextButtonBead; CSSTextButtonBead;
import org.apache.flex.html.staticControls.beads.TextButtonBead; TextButtonBead;
import org.apache.flex.html.staticControls.beads.TextFieldBead; TextFieldBead;
import org.apache.flex.html.staticControls.beads.TextInputBead; TextInputBead;
import org.apache.flex.html.staticControls.beads.TextInputWithBorderBead; TextInputWithBorderBead;
import org.apache.flex.html.staticControls.beads.TextAreaBead; TextAreaBead;
import org.apache.flex.html.staticControls.beads.CheckBoxBead; CheckBoxBead;
import org.apache.flex.html.staticControls.beads.RadioButtonBead; RadioButtonBead;
import org.apache.flex.html.staticControls.beads.ComboBoxBead; ComboBoxBead;
import org.apache.flex.html.staticControls.beads.models.TextModel; TextModel;
import org.apache.flex.html.staticControls.beads.models.ComboBoxModel; ComboBoxModel;
import org.apache.flex.html.staticControls.beads.models.ToggleButtonModel; ToggleButtonModel;
import org.apache.flex.html.staticControls.beads.models.ValueToggleButtonModel; ValueToggleButtonModel;
import org.apache.flex.html.staticControls.beads.models.ArraySelectionModel; ArraySelectionModel;
import org.apache.flex.events.CustomEvent; CustomEvent;
import org.apache.flex.events.Event; Event;
import org.apache.flex.utils.Timer; Timer;
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// 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
{
/**
* @private
* This class is used to link additional classes into rpc.swc
* beyond those that are found by dependecy analysis starting
* from the classes specified in manifest.xml.
*/
internal class FlexJSUIClasses
{
import org.apache.flex.html.staticControls.beads.IButtonBead; IButtonBead;
import org.apache.flex.html.staticControls.beads.CSSTextButtonBead; CSSTextButtonBead;
import org.apache.flex.html.staticControls.beads.TextButtonBead; TextButtonBead;
import org.apache.flex.html.staticControls.beads.TextFieldBead; TextFieldBead;
import org.apache.flex.html.staticControls.beads.TextInputBead; TextInputBead;
import org.apache.flex.html.staticControls.beads.TextInputWithBorderBead; TextInputWithBorderBead;
import org.apache.flex.html.staticControls.beads.TextAreaBead; TextAreaBead;
import org.apache.flex.html.staticControls.beads.CheckBoxBead; CheckBoxBead;
import org.apache.flex.html.staticControls.beads.RadioButtonBead; RadioButtonBead;
import org.apache.flex.html.staticControls.beads.ComboBoxBead; ComboBoxBead;
import org.apache.flex.html.staticControls.beads.ContainerBead; ContainerBead;
import org.apache.flex.html.staticControls.beads.models.TextModel; TextModel;
import org.apache.flex.html.staticControls.beads.models.ComboBoxModel; ComboBoxModel;
import org.apache.flex.html.staticControls.beads.models.ToggleButtonModel; ToggleButtonModel;
import org.apache.flex.html.staticControls.beads.models.ValueToggleButtonModel; ValueToggleButtonModel;
import org.apache.flex.html.staticControls.beads.models.ArraySelectionModel; ArraySelectionModel;
import org.apache.flex.events.CustomEvent; CustomEvent;
import org.apache.flex.events.Event; Event;
import org.apache.flex.utils.Timer; Timer;
}
}
|
Add bead to SWC
|
Add bead to SWC
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
2d7df8fee61797db91e9c114a4adebd6580bd2aa
|
src/main/flex/org/servebox/cafe/core/observer/AbstractObserver.as
|
src/main/flex/org/servebox/cafe/core/observer/AbstractObserver.as
|
/*
* actionscript-cafe AbstractObserver 18 avr. 2011 adesmarais
*
* Created by Servebox
* Copyright 2010 Servebox (c) All rights reserved. You may not use, distribute
* or modify this code under its source or binary form
* without the express authorization of ServeBox. Contact : [email protected]
*/
package org.servebox.cafe.core.observer
{
import flash.events.EventDispatcher;
import flash.utils.Dictionary;
import flash.utils.describeType;
import org.servebox.cafe.core.observer.IObservable;
import org.servebox.cafe.core.observer.IObserver;
import org.servebox.cafe.core.observer.Notification;
import org.servebox.cafe.core.signal.Signal;
public class AbstractObserver extends EventDispatcher implements IObserver
{
public function AbstractObserver()
{
}
private var notificationHandlers : Dictionary = null;
private var signalHandlers : Dictionary = null;
private function loadMetadata() : void
{
if( notificationHandlers != null )
{
return;
}
notificationHandlers = new Dictionary();
signalHandlers = new Dictionary();
var typeDesc : XML = describeType( this );
for each( var method : XML in typeDesc.method )
{
try
{
for each ( var metadata : XML in method.metadata.(@name="NotificationHandler") )
{
var notification : String = metadata.arg.(@key=="triggerFor").@value;
if( notification.length < 1 )
{
continue;
}
if( notificationHandlers[ notification ] == null )
{
notificationHandlers[ notification ] = [];
}
notificationHandlers[ notification ].push( this[ method.@name ] );
}
for each ( var metadataSignal : XML in method.metadata.(@name="SignalHandler") )
{
var signal : String = metadataSignal.arg.(@key=="triggerFor").@value;
if( signal.length < 1 )
{
continue;
}
if( signalHandlers[ signal ] == null )
{
signalHandlers[ signal ] = [];
}
signalHandlers[ signal ].push( this[ method.@name ] );
}
}catch( e : Error ){}
}
}
public function update( source : IObservable, notification : Notification ) : void
{
loadMetadata();
if ( !(notification is Signal) )
{
var notificationHandlers : Array = notificationHandlers[ notification.getType() ];
if( notificationHandlers != null )
{
for each( var notificationHandler : Function in notificationHandlers )
{
notificationHandler.apply( this, [ source, notification ] );
}
}
}
else
{
var signalHandlers : Array = signalHandlers[ notification.getType() ];
if ( signalHandlers != null )
{
for each ( var signalHandler : Function in signalHandlers )
{
signalHandler.apply( this, [notification.getCargo()] );
}
}
}
}
}
}
|
/*
* actionscript-cafe AbstractObserver 18 avr. 2011 adesmarais
*
* Created by Servebox
* Copyright 2010 Servebox (c) All rights reserved. You may not use, distribute
* or modify this code under its source or binary form
* without the express authorization of ServeBox. Contact : [email protected]
*/
package org.servebox.cafe.core.observer
{
import flash.events.EventDispatcher;
import flash.utils.Dictionary;
import flash.utils.describeType;
import org.servebox.cafe.core.observer.IObservable;
import org.servebox.cafe.core.observer.IObserver;
import org.servebox.cafe.core.observer.Notification;
import org.servebox.cafe.core.signal.Signal;
public class AbstractObserver extends EventDispatcher implements IObserver
{
public function AbstractObserver()
{
}
private var notificationHandlers : Dictionary = null;
private var signalHandlers : Dictionary = null;
private function loadMetadata() : void
{
if( notificationHandlers != null )
{
return;
}
notificationHandlers = new Dictionary();
signalHandlers = new Dictionary();
var typeDesc : XML = describeType( this );
for each( var method : XML in typeDesc.method )
{
try
{
for each ( var metadata : XML in method.metadata.(@name="NotificationHandler") )
{
var notification : String = metadata.arg.(@key=="triggerFor").@value;
if( notification.length < 1 )
{
continue;
}
if( notificationHandlers[ notification ] == null )
{
notificationHandlers[ notification ] = [];
}
notificationHandlers[ notification ].push( this[ method.@name ] );
}
for each ( var metadataSignal : XML in method.metadata.(@name="SignalHandler") )
{
var signal : String = metadataSignal.arg.(@key=="triggerFor").@value;
if( signal.length < 1 )
{
continue;
}
if( signalHandlers[ signal ] == null )
{
signalHandlers[ signal ] = [];
}
signalHandlers[ signal ].push( this[ method.@name ] );
}
}catch( e : Error ){}
}
}
public function update( source : IObservable, notification : Notification ) : void
{
loadMetadata();
if ( !(notification is Signal) )
{
var notificationHandlers : Array = notificationHandlers[ notification.getType() ];
if( notificationHandlers != null )
{
for each( var notificationHandler : Function in notificationHandlers )
{
notificationHandler.apply( this, [ source, notification ] );
}
}
}
else
{
var signalHandlers : Array = signalHandlers[ notification.getType() ];
if ( signalHandlers != null )
{
for each ( var signalHandler : Function in signalHandlers )
{
if ( notification.getCargo() != null )
{
signalHandler.apply( this, [notification.getCargo()] );
}
else
{
signalHandler.apply( this );
}
}
}
}
}
}
}
|
Change apply method if signal has no cargo.
|
Change apply method if signal has no cargo.
|
ActionScript
|
mit
|
servebox/as-cafe
|
1b051701aa7dd481935b3757d88fe8de82736b04
|
plugins/akamaiHDPlugin/src/com/kaltura/kdpfl/plugin/akamaiHDMediator.as
|
plugins/akamaiHDPlugin/src/com/kaltura/kdpfl/plugin/akamaiHDMediator.as
|
package com.kaltura.kdpfl.plugin
{
import com.akamai.osmf.utils.AkamaiStrings;
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class akamaiHDMediator extends Mediator
{
public static const NAME:String = "akamaiHDMediator";
/**
* default buffer length to be used when playing with HD Akamai plugin
*/
public static const DEFAULT_HD_BUFFER_LENGTH:int = 20;
/**
* default bandwith check time in seconds
*/
public static const DEFAULT_HD_BANDWIDTH_CHECK_TIME:int = 2;
private var _mediaProxy:MediaProxy;
private var _flashvars:Object;
public function akamaiHDMediator(viewComponent:Object=null)
{
super(NAME, viewComponent);
}
override public function onRegister():void
{
_mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
_flashvars = (facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars;
super.onRegister();
}
override public function listNotificationInterests():Array
{
return [
NotificationType.MEDIA_READY,
NotificationType.PLAYER_PLAYED
];
}
override public function handleNotification(notification:INotification):void
{
switch (notification.getName())
{
case NotificationType.PLAYER_PLAYED:
//workaround to display the bitrate that was automatically detected by akamai
if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true")
{
_mediaProxy.notifyStartingIndexChanged((facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentDynamicStreamIndex);
}
break;
case NotificationType.MEDIA_READY:
//add akamai metadata on the stream resource
//find last index of resource metadata flashvars.
var i:int = 0;
while (_flashvars.hasOwnProperty("objMetadataNamespace" + i) && _flashvars.hasOwnProperty("objMetadataValues" + i))
{
i++;
}
var bufferLength:int = DEFAULT_HD_BUFFER_LENGTH;
if (_flashvars.hdnetworkBufferLength && _flashvars.hdnetworkBufferLength!="")
{
bufferLength = _flashvars.hdnetworkBufferLength;
}
//Then add akamai resource metadata on the next index
_flashvars["objMetadataNamespace"+i] = AkamaiStrings.AKAMAI_ADVANCED_STREAMING_PLUGIN_METADATA_NAMESPACE;
//set buffer length
var akamaiMetadataValues:String = AkamaiStrings.AKAMAI_METADATA_KEY_MAX_BUFFER_LENGTH + "=" + bufferLength;
if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true")
{
//var bwEstimationObject:Object = new Object();
//bwEstimationObject.enabled = true;
var bandwidthEstimationPeriodInSeconds:int;
if (_flashvars.hdnetworkBRDetectionTime && _flashvars.hdnetworkBRDetectionTime!="")
{
bandwidthEstimationPeriodInSeconds = _flashvars.hdnetworkBRDetectionTime;
}
else
{
bandwidthEstimationPeriodInSeconds = DEFAULT_HD_BANDWIDTH_CHECK_TIME;
}
//enable akamai BW detection
akamaiMetadataValues += "&"+ AkamaiStrings.AKAMAI_METADATA_KEY_SET_BANDWIDTH_ESTIMATION_ENABLED + "={enabled:true,bandwidthEstimationPeriodInSeconds:"+bandwidthEstimationPeriodInSeconds+"}";
}
else
{
var preferedIndex:int = _mediaProxy.getFlavorByBitrate(_mediaProxy.vo.preferedFlavorBR);
if (preferedIndex!=-1)
{
akamaiMetadataValues += "&" + AkamaiStrings.AKAMAI_METDATA_KEY_MBR_STARTING_INDEX + "=" + preferedIndex;
_mediaProxy.notifyStartingIndexChanged(preferedIndex);
}
}
_flashvars["objMetadataValues"+i] = akamaiMetadataValues;
break;
}
}
}
}
|
package com.kaltura.kdpfl.plugin
{
import com.akamai.osmf.utils.AkamaiStrings;
import com.kaltura.kdpfl.model.ConfigProxy;
import com.kaltura.kdpfl.model.MediaProxy;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import org.osmf.events.MediaElementEvent;
import org.osmf.traits.DVRTrait;
import org.osmf.traits.MediaTraitType;
import org.puremvc.as3.interfaces.INotification;
import org.puremvc.as3.patterns.mediator.Mediator;
public class akamaiHDMediator extends Mediator
{
public static const NAME:String = "akamaiHDMediator";
/**
* default buffer length to be used when playing with HD Akamai plugin
*/
public static const DEFAULT_HD_BUFFER_LENGTH:int = 20;
/**
* default bandwith check time in seconds
*/
public static const DEFAULT_HD_BANDWIDTH_CHECK_TIME:int = 2;
private var _mediaProxy:MediaProxy;
private var _flashvars:Object;
public function akamaiHDMediator(viewComponent:Object=null)
{
super(NAME, viewComponent);
}
override public function onRegister():void
{
_mediaProxy = facade.retrieveProxy(MediaProxy.NAME) as MediaProxy;
_flashvars = (facade.retrieveProxy(ConfigProxy.NAME) as ConfigProxy).vo.flashvars;
super.onRegister();
}
override public function listNotificationInterests():Array
{
return [
NotificationType.MEDIA_READY,
NotificationType.PLAYER_PLAYED,
NotificationType.MEDIA_ELEMENT_READY
];
}
override public function handleNotification(notification:INotification):void
{
switch (notification.getName())
{
case NotificationType.PLAYER_PLAYED:
//workaround to display the bitrate that was automatically detected by akamai
if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true")
{
_mediaProxy.notifyStartingIndexChanged((facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).player.currentDynamicStreamIndex);
}
break;
case NotificationType.MEDIA_READY:
//add akamai metadata on the stream resource
//find last index of resource metadata flashvars.
var i:int = 0;
while (_flashvars.hasOwnProperty("objMetadataNamespace" + i) && _flashvars.hasOwnProperty("objMetadataValues" + i))
{
i++;
}
var bufferLength:int = DEFAULT_HD_BUFFER_LENGTH;
if (_flashvars.hdnetworkBufferLength && _flashvars.hdnetworkBufferLength!="")
{
bufferLength = _flashvars.hdnetworkBufferLength;
}
//Then add akamai resource metadata on the next index
_flashvars["objMetadataNamespace"+i] = AkamaiStrings.AKAMAI_ADVANCED_STREAMING_PLUGIN_METADATA_NAMESPACE;
//set buffer length
var akamaiMetadataValues:String = AkamaiStrings.AKAMAI_METADATA_KEY_MAX_BUFFER_LENGTH + "=" + bufferLength;
if (_flashvars.hdnetworkEnableBRDetection && _flashvars.hdnetworkEnableBRDetection=="true")
{
//var bwEstimationObject:Object = new Object();
//bwEstimationObject.enabled = true;
var bandwidthEstimationPeriodInSeconds:int;
if (_flashvars.hdnetworkBRDetectionTime && _flashvars.hdnetworkBRDetectionTime!="")
{
bandwidthEstimationPeriodInSeconds = _flashvars.hdnetworkBRDetectionTime;
}
else
{
bandwidthEstimationPeriodInSeconds = DEFAULT_HD_BANDWIDTH_CHECK_TIME;
}
//enable akamai BW detection
akamaiMetadataValues += "&"+ AkamaiStrings.AKAMAI_METADATA_KEY_SET_BANDWIDTH_ESTIMATION_ENABLED + "={enabled:true,bandwidthEstimationPeriodInSeconds:"+bandwidthEstimationPeriodInSeconds+"}";
}
else
{
var preferedIndex:int = _mediaProxy.getFlavorByBitrate(_mediaProxy.vo.preferedFlavorBR);
if (preferedIndex!=-1)
{
akamaiMetadataValues += "&" + AkamaiStrings.AKAMAI_METDATA_KEY_MBR_STARTING_INDEX + "=" + preferedIndex;
_mediaProxy.notifyStartingIndexChanged(preferedIndex);
}
}
_flashvars["objMetadataValues"+i] = akamaiMetadataValues;
break;
case NotificationType.MEDIA_ELEMENT_READY:
if (_mediaProxy.vo.isLive && _mediaProxy.vo.canSeek && _mediaProxy.vo.media)
{
_mediaProxy.vo.media.addEventListener(MediaElementEvent.TRAIT_ADD, onMediaTraitAdd);
}
break;
}
}
/**
* sets DVR window size according to actual window size (including Akamai's padding)
* @param e
*
*/
private function onMediaTraitAdd(e: MediaElementEvent) : void
{
if (e.traitType==MediaTraitType.DVR)
{
var dvrTrait:DVRTrait = _mediaProxy.vo.media.getTrait(MediaTraitType.DVR) as DVRTrait;
(facade.retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator).dvrWinSize = dvrTrait.windowDuration;
_mediaProxy.vo.media.removeEventListener(MediaElementEvent.TRAIT_ADD, onMediaTraitAdd);
}
}
}
}
|
fix livestream with dvr window size
|
fix livestream with dvr window size
|
ActionScript
|
agpl-3.0
|
kaltura/kdp,kaltura/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,shvyrev/kdp
|
cf4169c46930d0f2e3c6b6e208bb00f53e7df710
|
src/com/google/analytics/GATracker.as
|
src/com/google/analytics/GATracker.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
{
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.TrackerCache;
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.events.AnalyticsEvent;
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.events.Event;
import flash.events.EventDispatcher;
/* force import for type in the includes */
EventTracker;
ServerOperationMode;
/**
* Dispatched after the factory has built the tracker object.
* @eventType com.google.analytics.events.AnalyticsEvent.READY
*/
[Event(name="ready", type="com.google.analytics.events.AnalyticsEvent")]
/**
* Google Analytic Tracker Code (GATC)'s code-only component.
*/
public class GATracker implements AnalyticsTracker
{
private var _ready:Boolean = false;
private var _display:DisplayObject;
private var _eventDispatcher:EventDispatcher;
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;
//object properties
private var _account:String;
private var _mode:String;
private var _visualDebug:Boolean;
/**
* Indicates if the tracker is automatically build.
*/
public static var autobuild:Boolean = true;
/**
* The version of the tracker.
*/
public static var version:Version = API.version;
/**
* Creates a new GATracker instance.
* <p><b>Note:</b> the GATracker need to be instancied and added to the Stage or at least
* being placed in a display list.</p>
*/
public function GATracker( display:DisplayObject, account:String,
mode:String = "AS3", visualDebug:Boolean = false,
config:Configuration = null, debug:DebugConfiguration = null )
{
_display = display;
_eventDispatcher = new EventDispatcher( this ) ;
_tracker = new TrackerCache();
this.account = account;
this.mode = mode;
this.visualDebug = visualDebug;
if( !debug )
{
this.debug = new DebugConfiguration();
}
if( !config )
{
this.config = new Configuration( debug );
}
if( autobuild )
{
_factory();
}
}
/**
* @private
* Factory to build the different trackers
*/
private function _factory():void
{
_jsproxy = new JavascriptProxy( debug );
if( visualDebug )
{
debug.layout = new Layout( debug, _display );
debug.active = visualDebug;
}
var activeTracker:GoogleAnalyticsAPI;
var cache:TrackerCache = _tracker as TrackerCache;
switch( mode )
{
case TrackerMode.BRIDGE :
{
activeTracker = _bridgeFactory();
break;
}
case TrackerMode.AS3 :
default:
{
activeTracker = _trackerFactory();
}
}
if( !cache.isEmpty() )
{
cache.tracker = activeTracker;
cache.flush();
}
_tracker = activeTracker;
_ready = true;
dispatchEvent( new AnalyticsEvent( AnalyticsEvent.READY, this ) );
}
/**
* @private
* Factory method for returning a Tracker object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _trackerFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (AS3) v" + version +"\naccount: " + account );
/* note:
for unit testing and to avoid 2 different branches AIR/Flash
here we will detect if we are in the Flash Player or AIR
and pass the infos to the LocalInfo
By default we will define "Flash" for our local tests
*/
_adSense = new AdSenseGlobals( debug );
_dom = new HTMLDOM( debug );
_dom.cacheProperties();
_env = new Environment( "", "", "", debug, _dom );
_buffer = null;
_gifRequest = null;
/* note:
To be able to obtain the URL of the main SWF containing the GA API
we need to be able to access the stage property of a DisplayObject,
here we open the internal namespace to be able to set that reference
at instanciation-time.
We keep the implementation internal to be able to change it if required later.
*/
use namespace ga_internal;
_env.url = _display.stage.loaderInfo.url;
return new Tracker( account, config, debug, _env, _buffer, _gifRequest, _adSense, _display );
}
/**
* @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.
*/
public function get account():String
{
return _account;
}
/**
* @private
*/
public function set account( value:String ):void
{
_account = value;
}
/**
* Determinates the Configuration object of the tracker.
*/
public function get config():Configuration
{
return _config;
}
/**
* @private
*/
public function set config( value:Configuration ):void
{
_config = value;
}
/**
* Determinates the DebugConfiguration of the tracker.
*/
public function get debug():DebugConfiguration
{
return _debug;
}
/**
* @private
*/
public function set debug( value:DebugConfiguration ):void
{
_debug = value;
}
/**
* Indicates if the tracker is ready to use.
*/
public function isReady():Boolean
{
return _ready;
}
/**
* Indicates the mode of the tracking "AS3" or "Bridge".
*/
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.
*/
public function get visualDebug():Boolean
{
return _visualDebug;
}
/**
* @private
*/
public function set visualDebug( value:Boolean ):void
{
_visualDebug = value;
}
/**
* Builds the tracker.
*/
public function build():void
{
if( !isReady() )
{
_factory();
}
}
// IEventDispatcher implementation
/**
* Allows the registration of event listeners on the event target.
* @param type A string representing the event type to listen for. If eventName value is "ALL" addEventListener use addGlobalListener
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
* @param priority Determines the priority level of the event listener.
* @param useWeakReference Indicates if the listener is a weak reference.
*/
public function addEventListener( type:String, listener:Function, useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void
{
_eventDispatcher.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
/**
* Dispatches an event into the event flow.
* @param event The Event object that is dispatched into the event flow.
* @return <code class="prettyprint">true</code> if the Event is dispatched.
*/
public function dispatchEvent( event:Event ):Boolean
{
return _eventDispatcher.dispatchEvent( event );
}
/**
* Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
* This allows you to determine where altered handling of an event type has been introduced in the event flow heirarchy by an EventDispatcher object.
*/
public function hasEventListener( type:String ):Boolean
{
return _eventDispatcher.hasEventListener( type );
}
/**
* Removes a listener from the EventDispatcher object.
* If there is no matching listener registered with the <code class="prettyprint">EventDispatcher</code> object, then calling this method has no effect.
* @param type Specifies the type of event.
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
*/
public function removeEventListener( type:String, listener:Function, useCapture:Boolean = false ):void
{
_eventDispatcher.removeEventListener( type, listener, useCapture );
}
/**
* Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
* This method returns <code class="prettyprint">true</code> if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.
* @return A value of <code class="prettyprint">true</code> if a listener of the specified type will be triggered; <code class="prettyprint">false</code> otherwise.
*/
public function willTrigger( type:String ):Boolean
{
return _eventDispatcher.willTrigger( type );
}
include "common.txt"
}
}
|
/*
* 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
{
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.TrackerCache;
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.events.AnalyticsEvent;
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.events.Event;
import flash.events.EventDispatcher;
/* force import for type in the includes */
EventTracker;
ServerOperationMode;
/**
* Dispatched after the factory has built the tracker object.
* @eventType com.google.analytics.events.AnalyticsEvent.READY
*/
[Event(name="ready", type="com.google.analytics.events.AnalyticsEvent")]
/**
* Google Analytic Tracker Code (GATC)'s code-only component.
*/
public class GATracker implements AnalyticsTracker
{
private var _ready:Boolean = false;
private var _display:DisplayObject;
private var _eventDispatcher:EventDispatcher;
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;
//object properties
private var _account:String;
private var _mode:String;
private var _visualDebug:Boolean;
/**
* Indicates if the tracker is automatically build.
*/
public static var autobuild:Boolean = true;
/**
* The version of the tracker.
*/
public static var version:Version = API.version;
/**
* Creates a new GATracker instance.
* <p><b>Note:</b> the GATracker need to be instancied and added to the Stage or at least
* being placed in a display list.</p>
*/
public function GATracker( display:DisplayObject, account:String,
mode:String = "AS3", visualDebug:Boolean = false,
config:Configuration = null, debug:DebugConfiguration = null )
{
_display = display;
_eventDispatcher = new EventDispatcher( this ) ;
_tracker = new TrackerCache();
this.account = account;
this.mode = mode;
this.visualDebug = visualDebug;
if( !debug )
{
this.debug = new DebugConfiguration();
}
if( !config )
{
this.config = new Configuration( debug );
}
if( autobuild )
{
_factory();
}
}
/**
* @private
* Factory to build the different trackers
*/
private function _factory():void
{
_jsproxy = new JavascriptProxy( debug );
if( visualDebug )
{
debug.layout = new Layout( debug, _display );
debug.active = visualDebug;
}
var activeTracker:GoogleAnalyticsAPI;
var cache:TrackerCache = _tracker as TrackerCache;
switch( mode )
{
case TrackerMode.BRIDGE :
{
activeTracker = _bridgeFactory();
break;
}
case TrackerMode.AS3 :
default:
{
activeTracker = _trackerFactory();
}
}
if( !cache.isEmpty() )
{
cache.tracker = activeTracker;
cache.flush();
}
_tracker = activeTracker;
_ready = true;
dispatchEvent( new AnalyticsEvent( AnalyticsEvent.READY, this ) );
}
/**
* @private
* Factory method for returning a Tracker object.
*
* @return {GoogleAnalyticsAPI}
*/
private function _trackerFactory():GoogleAnalyticsAPI
{
debug.info( "GATracker (AS3) v" + version +"\naccount: " + account );
/* note:
for unit testing and to avoid 2 different branches AIR/Flash
here we will detect if we are in the Flash Player or AIR
and pass the infos to the LocalInfo
By default we will define "Flash" for our local tests
*/
_adSense = new AdSenseGlobals( debug );
_dom = new HTMLDOM( debug );
_dom.cacheProperties();
_env = new Environment( "", "", "", debug, _dom );
_buffer = null;
_gifRequest = null;
/* note:
To be able to obtain the URL of the main SWF containing the GA API
we need to be able to access the stage property of a DisplayObject,
here we open the internal namespace to be able to set that reference
at instanciation-time.
We keep the implementation internal to be able to change it if required later.
*/
use namespace ga_internal;
_env.url = _display.stage.loaderInfo.url;
return new Tracker( account, config, debug, _env, _buffer, _gifRequest, _adSense, _display );
}
/**
* @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.
*/
public function get account():String
{
return _account;
}
/**
* @private
*/
public function set account( value:String ):void
{
_account = value;
}
/**
* Determinates the Configuration object of the tracker.
*/
public function get config():Configuration
{
return _config;
}
/**
* @private
*/
public function set config( value:Configuration ):void
{
_config = value;
}
/**
* Determinates the DebugConfiguration of the tracker.
*/
public function get debug():DebugConfiguration
{
return _debug;
}
/**
* @private
*/
public function set debug( value:DebugConfiguration ):void
{
_debug = value;
}
/**
* Indicates if the tracker is ready to use.
*/
public function isReady():Boolean
{
return _ready;
}
/**
* Indicates the mode of the tracking "AS3" or "Bridge".
*/
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.
*/
public function get visualDebug():Boolean
{
return _visualDebug;
}
/**
* @private
*/
public function set visualDebug( value:Boolean ):void
{
_visualDebug = value;
}
/**
* Builds the tracker.
*/
public function build():void
{
if( !isReady() )
{
_factory();
}
}
// IEventDispatcher implementation
/**
* Allows the registration of event listeners on the event target.
* @param type A string representing the event type to listen for. If eventName value is "ALL" addEventListener use addGlobalListener
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
* @param priority Determines the priority level of the event listener.
* @param useWeakReference Indicates if the listener is a weak reference.
*/
public function addEventListener( type:String, listener:Function, useCapture:Boolean = false, priority:int = 0,
useWeakReference:Boolean = false):void
{
_eventDispatcher.addEventListener( type, listener, useCapture, priority, useWeakReference );
}
/**
* Dispatches an event into the event flow.
* @param event The Event object that is dispatched into the event flow.
* @return <code class="prettyprint">true</code> if the Event is dispatched.
*/
public function dispatchEvent( event:Event ):Boolean
{
return _eventDispatcher.dispatchEvent( event );
}
/**
* Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
* This allows you to determine where altered handling of an event type has been introduced in the event flow heirarchy by an EventDispatcher object.
*/
public function hasEventListener( type:String ):Boolean
{
return _eventDispatcher.hasEventListener( type );
}
/**
* Removes a listener from the EventDispatcher object.
* If there is no matching listener registered with the <code class="prettyprint">EventDispatcher</code> object, then calling this method has no effect.
* @param type Specifies the type of event.
* @param listener The Function that receives a notification when an event of the specified type occurs.
* @param useCapture Determinates if the event flow use capture or not.
*/
public function removeEventListener( type:String, listener:Function, useCapture:Boolean = false ):void
{
_eventDispatcher.removeEventListener( type, listener, useCapture );
}
/**
* Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
* This method returns <code class="prettyprint">true</code> if an event listener is triggered during any phase of the event flow when an event of the specified type is dispatched to this EventDispatcher object or any of its descendants.
* @return A value of <code class="prettyprint">true</code> if a listener of the specified type will be triggered; <code class="prettyprint">false</code> otherwise.
*/
public function willTrigger( type:String ):Boolean
{
return _eventDispatcher.willTrigger( type );
}
include "common.txt"
}
}
|
Fix - eat blank lines
|
Fix - eat blank lines
|
ActionScript
|
apache-2.0
|
dli-iclinic/gaforflash,dli-iclinic/gaforflash,drflash/gaforflash,jisobkim/gaforflash,minimedj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash,mrthuanvn/gaforflash,Vigmar/gaforflash,jeremy-wischusen/gaforflash,Miyaru/gaforflash,DimaBaliakin/gaforflash,jeremy-wischusen/gaforflash,soumavachakraborty/gaforflash,drflash/gaforflash,mrthuanvn/gaforflash,Miyaru/gaforflash,soumavachakraborty/gaforflash,nsdevaraj/gaforflash,DimaBaliakin/gaforflash,jisobkim/gaforflash,Vigmar/gaforflash
|
73d85907685f62bc090a7d9e0e06592f6791f305
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import dolly.utils.PropertyUtil;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.AccessorAccess;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
use namespace dolly_internal;
public class Cloner {
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function failIfTypeIsNotCloneable(type:Type):void {
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
}
dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> {
failIfTypeIsNotCloneable(type);
const result:Vector.<Field> = new Vector.<Field>();
for each(var field:Field in type.properties) {
if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) {
result.push(field);
}
}
return result;
}
dolly_internal static function doClone(source:*, deep:int, type:Type = null):* {
const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type);
const clonedInstance:* = new (type.clazz)();
for each(var field:Field in fieldsToClone) {
PropertyUtil.cloneProperty(source, clonedInstance, field.name);
}
return clonedInstance;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
failIfTypeIsNotCloneable(type);
const deep:int = 2;
return doClone(source, deep, type);
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import dolly.utils.PropertyUtil;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.AccessorAccess;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
use namespace dolly_internal;
public class Cloner {
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function failIfTypeIsNotCloneable(type:Type):void {
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
}
dolly_internal static function findAllWritableFieldsForType(type:Type):Vector.<Field> {
failIfTypeIsNotCloneable(type);
const result:Vector.<Field> = new Vector.<Field>();
for each(var field:Field in type.properties) {
if (!(field is Accessor) || (field as Accessor).access == AccessorAccess.READ_WRITE) {
result.push(field);
}
}
return result;
}
dolly_internal static function doClone(source:*, deep:int, type:Type = null):* {
if(!type) {
type = Type.forInstance(source);
}
const fieldsToClone:Vector.<Field> = findAllWritableFieldsForType(type);
const clonedInstance:* = new (type.clazz)();
for each(var field:Field in fieldsToClone) {
PropertyUtil.cloneProperty(source, clonedInstance, field.name);
}
return clonedInstance;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
failIfTypeIsNotCloneable(type);
const deep:int = 2;
return doClone(source, deep, type);
}
}
}
|
Initialize "type" parameter in Cloner.doClone() method.
|
Initialize "type" parameter in Cloner.doClone() method.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
4d88f44c5ad6325d27dbdad0fc49780827cce87e
|
src/aerys/minko/scene/node/Mesh.as
|
src/aerys/minko/scene/node/Mesh.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.mesh.VisibilityController;
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.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractSceneNode
{
public static const DEFAULT_MATERIAL : Material = new BasicMaterial();
private var _geometry : Geometry;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : VisibilityController;
private var _frame : uint;
private var _cloned : Signal;
private var _materialChanged : Signal;
private var _frameChanged : Signal;
private var _geometryChanged : Signal;
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
_material = value;
if (value)
_bindings.addProvider(value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
if (oldGeometry)
oldGeometry.changed.remove(geometryChangedHandler);
_geometry = value;
if (value)
_geometry.changed.add(geometryChangedHandler);
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh is visible or not.
*
* @return
*
*/
public function get visible() : Boolean
{
return _visibility.visible;
}
public function set visible(value : Boolean) : void
{
_visibility.visible = value;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null)
{
super();
initialize(geometry, material, name);
}
private function initialize(geometry : Geometry,
material : Material,
name : String) : void
{
if (name)
this.name = name;
_cloned = new Signal('Mesh.clones');
_materialChanged = new Signal('Mesh.materialChanged');
_frameChanged = new Signal('Mesh.frameChanged');
_geometryChanged = new Signal('Mesh.geometryChanged');
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
this.geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
_visibility = new VisibilityController();
// _visibility.frustumCulling = FrustumCulling.BOX ^ FrustumCulling.TOP_BOX;
addController(_visibility);
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
worldToLocal,
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.addedToSceneHandler(child, scene);
if (child === this)
_bindings.addProvider(transformData);
}
override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.removedFromSceneHandler(child, scene);
if (child === this)
_bindings.removeProvider(transformData);
}
private function geometryChangedHandler(geometry : Geometry) : void
{
_geometryChanged.execute(this, _geometry, _geometry);
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.mesh.VisibilityController;
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.math.Ray;
use namespace minko_scene;
/**
* Mesh objects are a visible instance of a Geometry rendered using a specific
* Effect with specific rendering properties.
*
* <p>
* Those rendering properties are stored in a DataBindings object so they can
* be directly used by the shaders in the rendering API.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public class Mesh extends AbstractSceneNode
{
public static const DEFAULT_MATERIAL : Material = new BasicMaterial();
private var _geometry : Geometry;
private var _properties : DataProvider;
private var _material : Material;
private var _bindings : DataBindings;
private var _visibility : VisibilityController;
private var _frame : uint;
private var _cloned : Signal;
private var _materialChanged : Signal;
private var _frameChanged : Signal;
private var _geometryChanged : Signal;
/**
* A DataProvider object already bound to the Mesh bindings.
*
* <pre>
* // set the "diffuseColor" property to 0x0000ffff
* mesh.properties.diffuseColor = 0x0000ffff;
*
* // animate the "diffuseColor" property
* mesh.addController(
* new AnimationController(
* new <ITimeline>[new ColorTimeline(
* "dataProvider.diffuseColor",
* 5000,
* new <uint>[0xffffffff, 0xffffff00, 0xffffffff]
* )]
* )
* );
* </pre>
*
* @return
*
*/
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get material() : Material
{
return _material;
}
public function set material(value : Material) : void
{
if (_material != value)
{
if (_material)
_bindings.removeProvider(_material);
var oldMaterial : Material = _material;
_material = value;
if (value)
_bindings.addProvider(value);
_materialChanged.execute(this, oldMaterial, value);
}
}
/**
* The rendering properties provided to the shaders to customize
* how the mesh will appear on screen.
*
* @return
*
*/
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The Geometry of the mesh.
* @return
*
*/
public function get geometry() : Geometry
{
return _geometry;
}
public function set geometry(value : Geometry) : void
{
if (_geometry != value)
{
var oldGeometry : Geometry = _geometry;
if (oldGeometry)
oldGeometry.changed.remove(geometryChangedHandler);
_geometry = value;
if (value)
_geometry.changed.add(geometryChangedHandler);
_geometryChanged.execute(this, oldGeometry, value);
}
}
/**
* Whether the mesh is visible or not.
*
* @return
*
*/
public function get visible() : Boolean
{
return _visibility.visible;
}
public function set visible(value : Boolean) : void
{
_visibility.visible = value;
}
public function get frustumCulling() : uint
{
return _visibility.frustumCulling;
}
public function set frustumCulling(value : uint) : void
{
_visibility.frustumCulling = value;
}
public function get cloned() : Signal
{
return _cloned;
}
public function get materialChanged() : Signal
{
return _materialChanged;
}
public function get frameChanged() : Signal
{
return _frameChanged;
}
public function get geometryChanged() : Signal
{
return _geometryChanged;
}
public function get frame() : uint
{
return _frame;
}
public function set frame(value : uint) : void
{
if (_frame != value)
{
var oldFrame : uint = _frame;
_frame = value;
_frameChanged.execute(this, oldFrame, value);
}
}
public function Mesh(geometry : Geometry = null,
material : Material = null,
name : String = null)
{
super();
initialize(geometry, material, name);
}
private function initialize(geometry : Geometry,
material : Material,
name : String) : void
{
if (name)
this.name = name;
_cloned = new Signal('Mesh.clones');
_materialChanged = new Signal('Mesh.materialChanged');
_frameChanged = new Signal('Mesh.frameChanged');
_geometryChanged = new Signal('Mesh.geometryChanged');
_bindings = new DataBindings(this);
this.properties = new DataProvider(properties, 'meshProperties', DataProviderUsage.EXCLUSIVE);
this.geometry = geometry;
this.material = material || DEFAULT_MATERIAL;
_visibility = new VisibilityController();
// _visibility.frustumCulling = FrustumCulling.BOX ^ FrustumCulling.TOP_BOX;
addController(_visibility);
}
public function cast(ray : Ray, maxDistance : Number = Number.POSITIVE_INFINITY) : Number
{
return _geometry.boundingBox.testRay(
ray,
worldToLocal,
maxDistance
);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var clone : Mesh = new Mesh();
clone.name = name;
clone.geometry = _geometry;
clone.properties = DataProvider(_properties.clone());
clone._bindings.copySharedProvidersFrom(_bindings);
clone.transform.copyFrom(transform);
clone.material = _material;
this.cloned.execute(this, clone);
return clone;
}
override protected function addedToSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.addedToSceneHandler(child, scene);
if (child === this)
_bindings.addProvider(transformData);
}
override protected function removedFromSceneHandler(child : ISceneNode, scene : Scene) : void
{
super.removedFromSceneHandler(child, scene);
if (child === this)
_bindings.removeProvider(transformData);
}
private function geometryChangedHandler(geometry : Geometry) : void
{
_geometryChanged.execute(this, _geometry, _geometry);
}
}
}
|
fix Mesh.materialChanged signal never executed
|
fix Mesh.materialChanged signal never executed
|
ActionScript
|
mit
|
aerys/minko-as3
|
f62fc2441bbec8e7a6f64d97c3cf471ecef2bdca
|
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.Viewport;
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;
import flash.display.BitmapData;
/**
* 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.Viewport;
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;
import flash.display.BitmapData;
/**
* 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 TMP_VECTOR4_2 : 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, TMP_VECTOR4);
var scale : Vector4 = transform.deltaTransformVector(Vector4.ONE, TMP_VECTOR4_2);
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();
}
}
}
|
use pre-allocated Vector4 in MeshVisibilityController.meshLocalToWorldChangedHandler()
|
use pre-allocated Vector4 in MeshVisibilityController.meshLocalToWorldChangedHandler()
|
ActionScript
|
mit
|
aerys/minko-as3
|
6bf47ac029639814ce3ff4b61982d800b4fcf548
|
src/com/esri/viewer/utils/LayerObjectUtil.as
|
src/com/esri/viewer/utils/LayerObjectUtil.as
|
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2012 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.viewer.utils
{
import com.esri.ags.clusterers.ESRIClusterer;
import com.esri.ags.layers.Layer;
import com.esri.ags.renderers.IRenderer;
import com.esri.ags.symbols.Symbol;
public class LayerObjectUtil
{
public static function getLayerObject(obj:XML, num:Number, isOpLayer:Boolean, bingKey:String, layer:Layer = null, proxyUrl:String = null):Object
{
var label:String = isOpLayer ? 'OpLayer ' + num : 'Map ' + num; // default label
if (obj.@label[0]) // check that label attribute exist
{
label = obj.@label; // set basemap label if specified in configuration file
}
var type:String;
if (!isOpLayer)
{
type = "tiled"; // default basemap type
}
if (obj.@type[0]) // check that type attribute exist
{
type = obj.@type; // set basemap type if specified in configuration file
}
// wms
var wkid:String;
if (obj.@wkid[0])
{
wkid = obj.@wkid;
}
var visible:Boolean = obj.@visible == "true";
var alpha:Number = 1.0;
if (obj.@alpha[0])
{
if (!isNaN(parseFloat(obj.@alpha)))
{
alpha = parseFloat(obj.@alpha);
}
}
var maxAllowableOffset:Number;
if (obj.@maxallowableoffset[0])
{
if (!isNaN(parseFloat(obj.@maxallowableoffset)))
{
maxAllowableOffset = parseFloat(obj.@maxallowableoffset);
}
}
var minScale:Number;
if (obj.@minscale[0])
{
if (!isNaN(parseFloat(obj.@minscale)))
{
minScale = parseFloat(obj.@minscale);
}
}
var maxScale:Number;
if (obj.@maxscale[0])
{
if (!isNaN(parseFloat(obj.@maxscale)))
{
maxScale = parseFloat(obj.@maxscale);
}
}
var maxImageWidth:Number;
if (obj.@maximagewidth[0])
{
if (!isNaN(parseInt(obj.@maximagewidth)))
{
maxImageWidth = parseInt(obj.@maximagewidth);
}
}
var maxImageHeight:Number;
if (obj.@maximageheight[0])
{
if (!isNaN(parseInt(obj.@maximageheight)))
{
maxImageHeight = parseInt(obj.@maximageheight);
}
}
var noData:Number;
if (obj.@nodata[0])
{
if (!isNaN(parseFloat(obj.@nodata)))
{
noData = parseFloat(obj.@nodata);
}
}
var autoRefresh:Number = 0;
if (obj.@autorefresh[0])
{
if (!isNaN(parseInt(obj.@autorefresh)))
{
autoRefresh = parseInt(obj.@autorefresh);
}
}
var copyright:String = obj.@copyright[0];
var clustererParser:ClustererParser = new ClustererParser();
var clusterer:ESRIClusterer = clustererParser.parseClusterer(obj.clustering[0]);
var rendererParser:RendererParser = new RendererParser();
var renderer:IRenderer = rendererParser.parseRenderer(obj);
var useProxy:Boolean = obj.@useproxy[0] && obj.@useproxy == "true"; // default false
var useMapTime:Boolean = obj.@usemaptime[0] ? obj.@usemaptime == "true" : true; // default true
var useAMF:String = obj.@useamf[0] ? obj.@useamf : "";
var token:String = obj.@token[0] ? obj.@token : "";
var mode:String = obj.@mode[0] ? obj.@mode : "";
var icon:String = isSupportedImageType(obj.@icon[0]) ? obj.@icon : 'assets/images/defaultBasemapIcon.png';
var layerId:String = obj.@layerid[0];
var imageFormat:String = obj.@imageformat;
var visibleLayers:String = obj.@visiblelayers;
var displayLevels:String = obj.@displaylevels;
var bandIds:String = obj.@bandids;
var skipGetCapabilities:String = obj.@skipgetcapabilities[0];
var version:String = obj.@version[0];
var url:String = obj.@url;
var serviceURL:String = obj.@serviceurl[0];
var serviceMode:String = obj.@servicemode[0];
var tileMatrixSetId:String = obj.@tilematrixsetid[0];
var username:String = obj.@username;
var password:String = obj.@password;
var disableClientCaching:Boolean = obj.@disableclientcaching[0] && obj.@disableclientcaching == "true"; // default false
// ve tiled layer or wmts layer
var style:String = obj.@style[0] ? obj.@style : "";
var key:String;
if (bingKey)
{
key = bingKey;
}
else
{
key = obj.@key[0] ? obj.@key : "";
}
var culture:String = obj.@culture[0] ? obj.@culture : "";
// arcims layer
var serviceHost:String = obj.@servicehost[0] ? obj.@servicehost : "";
var serviceName:String = obj.@servicename[0] ? obj.@servicename : "";
// definitionExpression for featurelayer
var definitionExpression:String = obj.@definitionexpression[0] ? obj.@definitionexpression : "";
var gdbVersion:String = obj.@gdbversion[0];
// isEditable for feature layer
var isEditable:Boolean = true;
if (obj.@iseditable[0])
{
isEditable = obj.iseditable == "true";
}
//sublayers
var subLayers:Array = [];
if (type == "tiled" || type == "dynamic")
{
var subLayersList:XMLList = obj.sublayer;
for (var i:int = 0; i < subLayersList.length(); i++)
{
subLayers.push({ id: String(subLayersList[i].@id), info: subLayersList[i].@info, infoConfig: subLayersList[i].@infoconfig, popUpConfig: subLayersList[i].@popupconfig, definitionExpression: String(subLayersList[i].@definitionexpression)});
}
}
//csv layer
var latitudeFieldName:String = obj.@latitudefieldname;
var longitudeFieldName:String = obj.@longitudefieldname;
var sourceFields:String = obj.@sourcefields;
var columnDelimiter:String = obj.@columndelimiter;
//web tiled layer
var subDomains:String = obj.@subdomains[0];
var symbolParser:SymbolParser = new SymbolParser();
var markerSymbol:Symbol;
if (obj.simplemarkersymbol[0])
{
markerSymbol = symbolParser.parseSimpleMarkerSymbol(obj.simplemarkersymbol[0]);
}
else if (obj.simplemarkersymbol[0])
{
markerSymbol = symbolParser.parsePictureMarkerSymbol(obj.picturemarkersymbol[0]);
}
var lineSymbol:Symbol;
if (obj.simplelinesymbol[0])
{
lineSymbol = symbolParser.parseSimpleLineSymbol(obj.simplelinesymbol[0]);
}
var fillSymbol:Symbol;
if (obj.simplefillsymbol[0])
{
fillSymbol = symbolParser.parseSimpleFillSymbol(obj.simplefillsymbol[0]);
}
var resultObject:Object =
{
id: String(num),
alpha: alpha,
bandIds: bandIds,
autoRefresh: autoRefresh,
columnDelimiter: columnDelimiter,
copyright: copyright,
culture: culture,
clusterer: clusterer,
definitionExpression: definitionExpression,
disableClientCaching: disableClientCaching,
displayLevels: displayLevels,
fillSymbol: fillSymbol,
gdbVersion: gdbVersion,
icon: icon,
imageFormat: imageFormat,
isEditable: isEditable,
key: key,
label: label,
layerId: layerId,
latitudeFieldName: latitudeFieldName,
lineSymbol: lineSymbol,
longitudeFieldName: longitudeFieldName,
markerSymbol: markerSymbol,
maxAllowableOffset: maxAllowableOffset,
maxImageHeight: maxImageHeight,
maxImageWidth: maxImageWidth,
minScale: minScale,
maxScale: maxScale,
mode: mode,
noData: noData,
password: password,
proxyUrl: proxyUrl,
renderer: renderer,
serviceHost: serviceHost,
serviceName: serviceName,
serviceMode: serviceMode,
serviceURL: serviceURL,
skipGetCapabilities: skipGetCapabilities,
sourceFields: sourceFields,
style: style,
subDomains: subDomains,
subLayers: subLayers,
tileMatrixSetId: tileMatrixSetId,
token: token,
type: type,
url: url,
useAMF: useAMF,
useMapTime: useMapTime,
useProxy: useProxy,
username: username,
version: version,
visible: visible,
visibleLayers: visibleLayers,
wkid: wkid
};
// look for info, infoconfig and popupconfig on basemaps and operational layers
var opLayerInfo:String = obj.@info;
var opLayerInfoConfig:String = obj.@infoconfig;
var opLayerPopUpConfig:String = obj.@popupconfig;
resultObject.popUpConfig = opLayerPopUpConfig;
resultObject.infoConfig = opLayerInfoConfig;
resultObject.infoUrl = opLayerInfo;
resultObject.layer = layer;
if (!isOpLayer)
{
var reference:Boolean = obj.@reference[0] && obj.@reference == "true";
resultObject.reference = reference;
}
return resultObject;
}
private static function isSupportedImageType(filePath:String):Boolean
{
var fp:String = filePath;
if (!fp)
{
return false;
}
var tokenIndex:int = fp.indexOf("?");
var hasToken:Boolean = (tokenIndex > -1);
fp = hasToken ? fp.substr(0, tokenIndex) : fp;
var endsWithSupportedImageFileType:RegExp = /\.(png|gif|jpg)$/i;
return endsWithSupportedImageFileType.test(fp);
}
}
}
|
///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2012 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.viewer.utils
{
import com.esri.ags.clusterers.ESRIClusterer;
import com.esri.ags.layers.Layer;
import com.esri.ags.renderers.IRenderer;
import com.esri.ags.symbols.Symbol;
public class LayerObjectUtil
{
public static function getLayerObject(obj:XML, num:Number, isOpLayer:Boolean, bingKey:String, layer:Layer = null, proxyUrl:String = null):Object
{
var label:String = isOpLayer ? 'OpLayer ' + num : 'Map ' + num; // default label
if (obj.@label[0]) // check that label attribute exist
{
label = obj.@label; // set basemap label if specified in configuration file
}
var type:String;
if (!isOpLayer)
{
type = "tiled"; // default basemap type
}
if (obj.@type[0]) // check that type attribute exist
{
type = obj.@type; // set basemap type if specified in configuration file
}
// wms
var wkid:String;
if (obj.@wkid[0])
{
wkid = obj.@wkid;
}
var visible:Boolean = obj.@visible == "true";
var alpha:Number = 1.0;
if (obj.@alpha[0])
{
if (!isNaN(parseFloat(obj.@alpha)))
{
alpha = parseFloat(obj.@alpha);
}
}
var maxAllowableOffset:Number;
if (obj.@maxallowableoffset[0])
{
if (!isNaN(parseFloat(obj.@maxallowableoffset)))
{
maxAllowableOffset = parseFloat(obj.@maxallowableoffset);
}
}
var minScale:Number;
if (obj.@minscale[0])
{
if (!isNaN(parseFloat(obj.@minscale)))
{
minScale = parseFloat(obj.@minscale);
}
}
var maxScale:Number;
if (obj.@maxscale[0])
{
if (!isNaN(parseFloat(obj.@maxscale)))
{
maxScale = parseFloat(obj.@maxscale);
}
}
var maxImageWidth:Number;
if (obj.@maximagewidth[0])
{
if (!isNaN(parseInt(obj.@maximagewidth)))
{
maxImageWidth = parseInt(obj.@maximagewidth);
}
}
var maxImageHeight:Number;
if (obj.@maximageheight[0])
{
if (!isNaN(parseInt(obj.@maximageheight)))
{
maxImageHeight = parseInt(obj.@maximageheight);
}
}
var noData:Number;
if (obj.@nodata[0])
{
if (!isNaN(parseFloat(obj.@nodata)))
{
noData = parseFloat(obj.@nodata);
}
}
var autoRefresh:Number = 0;
if (obj.@autorefresh[0])
{
if (!isNaN(parseInt(obj.@autorefresh)))
{
autoRefresh = parseInt(obj.@autorefresh);
}
}
var copyright:String = obj.@copyright[0];
var clustererParser:ClustererParser = new ClustererParser();
var clusterer:ESRIClusterer = clustererParser.parseClusterer(obj.clustering[0]);
var rendererParser:RendererParser = new RendererParser();
var renderer:IRenderer = rendererParser.parseRenderer(obj);
var useProxy:Boolean = obj.@useproxy[0] && obj.@useproxy == "true"; // default false
var useMapTime:Boolean = obj.@usemaptime[0] ? obj.@usemaptime == "true" : true; // default true
var useAMF:String = obj.@useamf[0] ? obj.@useamf : "";
var token:String = obj.@token[0] ? obj.@token : "";
var mode:String = obj.@mode[0] ? obj.@mode : "";
var icon:String = isSupportedImageType(obj.@icon[0]) ? obj.@icon : 'assets/images/defaultBasemapIcon.png';
var layerId:String = obj.@layerid[0];
var imageFormat:String = obj.@imageformat;
var visibleLayers:String = obj.@visiblelayers;
var displayLevels:String = obj.@displaylevels;
var bandIds:String = obj.@bandids;
var skipGetCapabilities:String = obj.@skipgetcapabilities[0];
var version:String = obj.@version[0];
var url:String = obj.@url;
var serviceURL:String = obj.@serviceurl[0];
var serviceMode:String = obj.@servicemode[0];
var tileMatrixSetId:String = obj.@tilematrixsetid[0];
var username:String = obj.@username;
var password:String = obj.@password;
var disableClientCaching:Boolean = obj.@disableclientcaching[0] && obj.@disableclientcaching == "true"; // default false
// ve tiled layer or wmts layer
var style:String = obj.@style[0] ? obj.@style : "";
var key:String;
if (bingKey)
{
key = bingKey;
}
else
{
key = obj.@key[0] ? obj.@key : "";
}
var culture:String = obj.@culture[0] ? obj.@culture : "";
// arcims layer
var serviceHost:String = obj.@servicehost[0] ? obj.@servicehost : "";
var serviceName:String = obj.@servicename[0] ? obj.@servicename : "";
// definitionExpression for featurelayer
var definitionExpression:String = obj.@definitionexpression[0] ? obj.@definitionexpression : "";
var gdbVersion:String = obj.@gdbversion[0];
// isEditable for feature layer
var isEditable:Boolean = true;
if (obj.@iseditable[0])
{
isEditable = obj.iseditable == "true";
}
//sublayers
var subLayers:Array = [];
if (type == "tiled" || type == "dynamic")
{
var subLayersList:XMLList = obj.sublayer;
for (var i:int = 0; i < subLayersList.length(); i++)
{
subLayers.push({ id: String(subLayersList[i].@id), info: subLayersList[i].@info, infoConfig: subLayersList[i].@infoconfig, popUpConfig: subLayersList[i].@popupconfig, definitionExpression: String(subLayersList[i].@definitionexpression)});
}
}
//csv layer
var latitudeFieldName:String = obj.@latitudefieldname;
var longitudeFieldName:String = obj.@longitudefieldname;
var sourceFields:String = obj.@sourcefields;
var columnDelimiter:String = obj.@columndelimiter;
//web tiled layer
var subDomains:String = obj.@subdomains[0];
var symbolParser:SymbolParser = new SymbolParser();
var markerSymbol:Symbol;
if (obj.simplemarkersymbol[0])
{
markerSymbol = symbolParser.parseSimpleMarkerSymbol(obj.simplemarkersymbol[0]);
}
else if (obj.picturemarkersymbol[0])
{
markerSymbol = symbolParser.parsePictureMarkerSymbol(obj.picturemarkersymbol[0]);
}
var lineSymbol:Symbol;
if (obj.simplelinesymbol[0])
{
lineSymbol = symbolParser.parseSimpleLineSymbol(obj.simplelinesymbol[0]);
}
var fillSymbol:Symbol;
if (obj.simplefillsymbol[0])
{
fillSymbol = symbolParser.parseSimpleFillSymbol(obj.simplefillsymbol[0]);
}
var resultObject:Object =
{
id: String(num),
alpha: alpha,
bandIds: bandIds,
autoRefresh: autoRefresh,
columnDelimiter: columnDelimiter,
copyright: copyright,
culture: culture,
clusterer: clusterer,
definitionExpression: definitionExpression,
disableClientCaching: disableClientCaching,
displayLevels: displayLevels,
fillSymbol: fillSymbol,
gdbVersion: gdbVersion,
icon: icon,
imageFormat: imageFormat,
isEditable: isEditable,
key: key,
label: label,
layerId: layerId,
latitudeFieldName: latitudeFieldName,
lineSymbol: lineSymbol,
longitudeFieldName: longitudeFieldName,
markerSymbol: markerSymbol,
maxAllowableOffset: maxAllowableOffset,
maxImageHeight: maxImageHeight,
maxImageWidth: maxImageWidth,
minScale: minScale,
maxScale: maxScale,
mode: mode,
noData: noData,
password: password,
proxyUrl: proxyUrl,
renderer: renderer,
serviceHost: serviceHost,
serviceName: serviceName,
serviceMode: serviceMode,
serviceURL: serviceURL,
skipGetCapabilities: skipGetCapabilities,
sourceFields: sourceFields,
style: style,
subDomains: subDomains,
subLayers: subLayers,
tileMatrixSetId: tileMatrixSetId,
token: token,
type: type,
url: url,
useAMF: useAMF,
useMapTime: useMapTime,
useProxy: useProxy,
username: username,
version: version,
visible: visible,
visibleLayers: visibleLayers,
wkid: wkid
};
// look for info, infoconfig and popupconfig on basemaps and operational layers
var opLayerInfo:String = obj.@info;
var opLayerInfoConfig:String = obj.@infoconfig;
var opLayerPopUpConfig:String = obj.@popupconfig;
resultObject.popUpConfig = opLayerPopUpConfig;
resultObject.infoConfig = opLayerInfoConfig;
resultObject.infoUrl = opLayerInfo;
resultObject.layer = layer;
if (!isOpLayer)
{
var reference:Boolean = obj.@reference[0] && obj.@reference == "true";
resultObject.reference = reference;
}
return resultObject;
}
private static function isSupportedImageType(filePath:String):Boolean
{
var fp:String = filePath;
if (!fp)
{
return false;
}
var tokenIndex:int = fp.indexOf("?");
var hasToken:Boolean = (tokenIndex > -1);
fp = hasToken ? fp.substr(0, tokenIndex) : fp;
var endsWithSupportedImageFileType:RegExp = /\.(png|gif|jpg)$/i;
return endsWithSupportedImageFileType.test(fp);
}
}
}
|
Fix typo that prevented parsing PictureMarkerSymbols.
|
Fix typo that prevented parsing PictureMarkerSymbols.
|
ActionScript
|
apache-2.0
|
CanterburyRegionalCouncil/arcgis-viewer-flex,Esri/arcgis-viewer-flex,Esri/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex,CanterburyRegionalCouncil/arcgis-viewer-flex
|
ce91eaa903906cc6f15ea75553dd02498fda75bf
|
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 _invalidDepth : Boolean = false;
private var _localToWorld : Matrix4x4 = null;
private var _worldToScreen : Matrix4x4 = null;
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;
}
public function get depth() : Number
{
if (_invalidDepth)
{
_invalidDepth = false;
if (_localToWorld != null && _worldToScreen != null)
{
_localToWorld.transformVector(Vector4.ZERO, TMP_VECTOR4);
var screenSpacePosition : Vector4 = _worldToScreen.transformVector(TMP_VECTOR4, 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);
updateGeometry(geometry);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
for (var parameter : String in _bindings)
{
meshBindings.removeCallback(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.concat();
_fsConstants = program._fsConstants.concat();
_fsTextures = program._fsTextures.concat();
_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
{
_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);
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).getNativeTexture(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
{
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 _invalidDepth : Boolean = false;
private var _localToWorld : Matrix4x4 = null;
private var _worldToScreen : Matrix4x4 = null;
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;
}
public function get depth() : Number
{
if (_invalidDepth)
{
_invalidDepth = false;
if (_localToWorld != null && _worldToScreen != null)
{
var worldSpacePosition : Vector4 = _localToWorld.transformVector(
Vector4.ZERO, 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);
updateGeometry(geometry);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
for (var parameter : String in _bindings)
{
meshBindings.removeCallback(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.concat();
_fsConstants = program._fsConstants.concat();
_fsTextures = program._fsTextures.concat();
_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
{
_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);
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).getNativeTexture(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
{
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.depth getter to avoid instanciating Vector4 objects
|
fix DrawCall.depth getter to avoid instanciating Vector4 objects
|
ActionScript
|
mit
|
aerys/minko-as3
|
e101f9a8e87c82079b91f2a08f348855a3805fea
|
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 _bindingsConsumer : DrawCallBindingsConsumer;
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 (_bindingsConsumer)
_bindingsConsumer.enabled = value;
}
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
{
_invalidDepth = computeDepth;
setProgram(program);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
if (_bindingsConsumer != null)
{
meshBindings.removeConsumer(_bindingsConsumer);
sceneBindings.removeConsumer(_bindingsConsumer);
}
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;
_bindingsConsumer = new DrawCallBindingsConsumer(
_bindings,
_cpuConstants,
_vsConstants,
_fsConstants,
_fsTextures
);
_bindingsConsumer.enabled = _enabled;
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;
var hasNormals : Boolean = vertexFormat.hasComponent(VertexComponent.NORMAL);
if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0
&& !vertexFormat.hasComponent(VertexComponent.TANGENT))
{
geometry.computeTangentSpace(!hasNormals);
}
else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !hasNormals)
{
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
{
meshBindings.addConsumer(_bindingsConsumer);
sceneBindings.addConsumer(_bindingsConsumer);
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
{
_bindingsConsumer.setProperty(name, value);
}
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 _bindingsConsumer : DrawCallBindingsConsumer;
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 (_bindingsConsumer)
_bindingsConsumer.enabled = value;
}
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
{
_invalidDepth = computeDepth;
setProgram(program);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
if (_bindingsConsumer != null)
{
meshBindings.removeConsumer(_bindingsConsumer);
sceneBindings.removeConsumer(_bindingsConsumer);
}
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;
_bindingsConsumer = new DrawCallBindingsConsumer(
_bindings,
_cpuConstants,
_vsConstants,
_fsConstants,
_fsTextures
);
_bindingsConsumer.enabled = _enabled;
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;
var hasNormals : Boolean = vertexFormat.hasComponent(VertexComponent.NORMAL);
if (_vsInputComponents.indexOf(VertexComponent.TANGENT) >= 0
&& !vertexFormat.hasComponent(VertexComponent.TANGENT))
{
geometry.computeTangentSpace(!hasNormals);
}
else if (_vsInputComponents.indexOf(VertexComponent.NORMAL) >= 0 && !hasNormals)
{
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
{
meshBindings.addConsumer(_bindingsConsumer);
sceneBindings.addConsumer(_bindingsConsumer);
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
{
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
{
_bindingsConsumer.setProperty(name, value);
}
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;
}
}
}
|
remove test of _enabled because it should now be done before calling DrawCall.apply()
|
remove test of _enabled because it should now be done before calling DrawCall.apply()
|
ActionScript
|
mit
|
aerys/minko-as3
|
b32e5541fb4874f7796c68f9907a3c2f5b1f8139
|
as/main/frame4.as
|
as/main/frame4.as
|
var historia_txt:String ="";
var baixa_mc:MovieClip;
var puja_mc:MovieClip;
var buttonsUI:Array = new Array ("puja_mc", "baixa_mc");
this.historia_txt.html = true;
this.historia.htmlText =true;
this.historia_txt.wordWrap = true;
this.historia_txt.multiline = true;
this.onEnterFrame = function ():Void
{
buttonsUI[i].oOver();
this.stop();
};
function textScroll():Void
{
this.onPress = this.oOut;
this.onRollOver =this.oOver;
this.onRollOut = this.oOut;
this.onRelease = this.oOut;
};
function oOver():Void
{
pressing = true;
movement = -1;
};
function oOut():Void
{
pressing = false;
};
var Private_lv = new LoadVars ();
Private_lv.load ("/assets/tendes.txt");
Private_lv.onLoad = function ():Void
{
this.historia_txt.htmlText = this.Privat;
this.play ();
textScroll();
};
|
var historia_txt:String ="";
var baixa_mc:MovieClip;
var puja_mc:MovieClip;
var buttonsUI:Array = new Array ("puja_mc", "baixa_mc");
this.historia_txt.html = true;
this.historia.htmlText =true;
this.historia_txt.wordWrap = true;
this.historia_txt.multiline = true;
this.onEnterFrame = function ():Void
{
buttonsUI[i].oOver();
this.stop();
};
function textScroll():Void
{
this.onPress = this.oOut;
this.onRollOver =this.oOver;
this.onRollOut = this.oOut;
this.onRelease = this.oOut;
};
function oOver():Void
{
pressing = true;
movement = -1;
};
function oOut():Void
{
pressing = false;
};
var Privat = new LoadVars ();
Privat.load ("/assets/tendes.txt");
Privat.onLoad = function ():Void
{
this.historia_txt.htmlText = this.Privat;
this.play ();
textScroll();
};
|
Update frame4.as
|
Update frame4.as
|
ActionScript
|
bsd-3-clause
|
delfiramirez/web-talking-wear,delfiramirez/web-talking-wear,delfiramirez/web-talking-wear
|
5caaf48295e0295ac11486059b8b122ae2d1b800
|
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])
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, 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;
}
}
}
|
fix TransformController.updateAncestorsAndSelfLocalToWorld() to read the flags properly
|
fix TransformController.updateAncestorsAndSelfLocalToWorld() to read the flags properly
|
ActionScript
|
mit
|
aerys/minko-as3
|
8de4aad10f12ace70ac30edf692106f522800170
|
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 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;
}
}
}
|
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 : 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 wrong values for GeometrySanitizer.INDEX_LIMIT and GeometrySanitizer.VERTEX_LIMIT
|
fix wrong values for GeometrySanitizer.INDEX_LIMIT and GeometrySanitizer.VERTEX_LIMIT
|
ActionScript
|
mit
|
aerys/minko-as3
|
5df1335471a3953c9efc91c692893f03c4602d34
|
src/as/com/threerings/io/TypedArray.as
|
src/as/com/threerings/io/TypedArray.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.io {
import flash.utils.ByteArray;
import com.threerings.util.ClassUtil;
import com.threerings.util.Cloneable;
public dynamic class TypedArray extends Array
implements Cloneable
{
/**
* Convenience method to get the java type of an array containing objects of the specified
* class.
*/
public static function getJavaType (of :Class) :String
{
if (of === Boolean) {
return "[Z";
} else if (of === int) { // Number will be int if something like 3.0
return "[I";
} else if (of === Number) {
return "[D";
} else if (of === ByteArray) {
return "[[B";
}
var cname :String = Translations.getToServer(ClassUtil.getClassName(of));
return "[L" + cname + ";";
}
/**
* A factory method to create a TypedArray for holding objects of the specified type.
*/
public static function create (of :Class) :TypedArray
{
return new TypedArray(getJavaType(of));
}
/**
* Create a TypedArray
*
* @param jtype The java classname of this array, for example "[I" to represent an int[], or
* "[Ljava.lang.Object;" for Object[].
*/
public function TypedArray (jtype :String)
{
_jtype = jtype;
}
/**
* Adds all of the elements of the supplied array to this typed array. The types of the
* elements of the target array must, of course, be of the type specified for this array
* otherwise badness will ensue.
*
* @return this array instance for handy call chainability.
*/
public function addAll (other :Array) :TypedArray
{
push.apply(this, other);
return this;
}
public function getJavaType () :String
{
return _jtype;
}
// from Cloneable
public function clone () :Object
{
var clazz :Class = ClassUtil.getClass(this);
var copy :TypedArray = new clazz(_jtype);
copy.addAll(this);
return copy;
}
/** The 'type' of this array, which doesn't really mean anything except gives it a clue as to
* how to stream to our server. */
protected var _jtype :String;
}
}
|
//
// $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.io {
import flash.utils.ByteArray;
import com.threerings.util.ClassUtil;
import com.threerings.util.Cloneable;
public dynamic class TypedArray extends Array
implements Cloneable
{
/**
* Convenience method to get the java type of an array containing objects of the specified
* class.
*/
public static function getJavaType (of :Class) :String
{
if (of === Boolean) {
return "[Z";
} else if (of === int) { // Number will be int if something like 3.0
return "[I";
} else if (of === Number) {
return "[D";
} else if (of === ByteArray) {
return "[[B";
}
var cname :String = Translations.getToServer(ClassUtil.getClassName(of));
return "[L" + cname + ";";
}
/**
* A factory method to create a TypedArray for holding objects of the specified type.
*/
public static function create (of :Class, initialValues :Array = null) :TypedArray
{
var ta :TypedArray = new TypedArray(getJavaType(of));
if (initialValues != null) {
ta.addAll(initialValues);
}
return ta;
}
/**
* Create a TypedArray
*
* @param jtype The java classname of this array, for example "[I" to represent an int[], or
* "[Ljava.lang.Object;" for Object[].
*/
public function TypedArray (jtype :String)
{
_jtype = jtype;
}
/**
* Adds all of the elements of the supplied array to this typed array. The types of the
* elements of the target array must, of course, be of the type specified for this array
* otherwise badness will ensue.
*
* @return this array instance for handy call chainability.
*/
public function addAll (other :Array) :TypedArray
{
push.apply(this, other);
return this;
}
public function getJavaType () :String
{
return _jtype;
}
// from Cloneable
public function clone () :Object
{
var clazz :Class = ClassUtil.getClass(this);
var copy :TypedArray = new clazz(_jtype);
copy.addAll(this);
return copy;
}
/** The 'type' of this array, which doesn't really mean anything except gives it a clue as to
* how to stream to our server. */
protected var _jtype :String;
}
}
|
Add an easy way to initialize. Jeez, this whole thing could *almost* go away if we moved to flash 10 and used Vector, but of course, there's no way to get the type of Vector. Maybe there is, with describeType(). Can't experiment now. I'd fall out of my chair if there were. We need to know in case sending an empty array to the server, it's still gotta be the right type (with non-empty we could try examining the first element).
|
Add an easy way to initialize.
Jeez, this whole thing could *almost* go away if we moved to flash 10
and used Vector, but of course, there's no way to get the type of
Vector. Maybe there is, with describeType(). Can't experiment now.
I'd fall out of my chair if there were.
We need to know in case sending an empty array to the server,
it's still gotta be the right type (with non-empty we could
try examining the first element).
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5742 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
10b65b608ecc24d8145b2a748b6c8f9baf71cb16
|
runtime/src/main/as/flump/display/Movie.as
|
runtime/src/main/as/flump/display/Movie.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.display {
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flump.mold.LayerMold;
import flump.mold.MovieMold;
import react.Signal;
import starling.animation.IAnimatable;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
import starling.utils.MatrixUtil;
/**
* A movie created from flump-exported data. It has children corresponding to the layers in the
* movie in Flash, in the same order and with the same names. It fills in those children
* initially with the image or movie of the symbol on that exported layer. After the initial
* population, it only applies the keyframe-based transformations to the child at the index
* corresponding to the layer. This means it's safe to swap in other DisplayObjects at those
* positions to have them animated in place of the initial child.
*
* <p>A Movie will not animate unless it's added to a Juggler (or its advanceTime() function
* is otherwise called). When the movie is added to a juggler, it advances its playhead with the
* frame ticks if isPlaying is true. It will automatically remove itself from its juggler when
* removed from the stage.</p>
*
* @see Library and LibraryLoader to create instances of Movie.
*/
public class Movie extends Sprite
implements IAnimatable
{
/** A label fired by all movies when entering their first frame. */
public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME";
/** A label fired by all movies when entering their last frame. */
public static const LAST_FRAME :String = "flump.movie.LAST_FRAME";
/** Fires the label string whenever it's passed in playing. */
public const labelPassed :Signal = new Signal(String);
/** @private */
public function Movie (src :MovieMold, frameRate :Number, library :Library) {
this.name = src.id;
_labels = src.labels;
_frameRate = frameRate;
if (src.flipbook) {
_layers = new Vector.<Layer>(1, true);
_layers[0] = createLayer(this, src.layers[0], library, /*flipbook=*/true);
_numFrames = src.layers[0].frames;
} else {
_layers = new Vector.<Layer>(src.layers.length, true);
for (var ii :int = 0; ii < _layers.length; ii++) {
_layers[ii] = createLayer(this, src.layers[ii], library, /*flipbook=*/false);
_numFrames = Math.max(src.layers[ii].frames, _numFrames);
}
}
_duration = _numFrames / _frameRate;
updateFrame(0, 0);
// When we're removed from the stage, remove ourselves from any juggler animating us.
addEventListener(Event.REMOVED_FROM_STAGE, function (..._) :void {
dispatchEventWith(Event.REMOVE_FROM_JUGGLER);
});
}
/** @return the frame being displayed. */
public function get frame () :int { return _frame; }
/** @return the number of frames in the movie. */
public function get numFrames () :int { return _numFrames; }
/** @return true if the movie is currently playing. */
public function get isPlaying () :Boolean { return _state == PLAYING; }
/** @return true if the movie contains the given label. */
public function hasLabel (label :String) :Boolean {
return getFrameForLabel(label) >= 0;
}
/** @return the frame index for the given label, or -1 if the label doesn't exist. */
public function getFrameForLabel (label :String) :int {
for (var ii :int = 0; ii < _labels.length; ii++) {
if (_labels[ii] != null && _labels[ii].indexOf(label) != -1) return ii;
}
return -1;
}
/** Plays the movie from its current frame. The movie will loop forever. */
public function loop () :Movie {
_state = PLAYING;
_stopFrame = NO_FRAME;
return this;
}
/** Plays the movie from its current frame, stopping when it reaches its last frame. */
public function playOnce () :Movie { return playTo(LAST_FRAME); }
/**
* Moves to the given String label or int frame. Doesn't alter playing status or stop frame.
* If there are labels at the given position, they're fired as part of the goto, even if the
* current frame is equal to the destination. Labels between the current frame and the
* destination frame are not fired.
*
* @param position the int frame or String label to goto.
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie
*/
public function goTo (position :Object) :Movie {
const frame :int = extractFrame(position);
updateFrame(frame, 0);
return this;
}
/**
* Plays the movie from its current frame. The movie will stop when it reaches the given label
* or frame.
*
* @param position to int frame or String label to stop at
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie.
*/
public function playTo (position :Object) :Movie {
// won't play if we're already at the stop position
return stopAt(position).play();
}
/**
* Sets the stop frame for this Movie.
*
* @param position the int frame or String label to stop at.
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie.
*/
public function stopAt (position :Object) :Movie {
_stopFrame = extractFrame(position);
return this;
}
/**
* Sets the movie playing. It will automatically stop at its stopFrame, if one is set,
* otherwise it will loop forever.
*
* @return this movie for chaining
*/
public function play () :Movie {
// set playing to true unless movie is at the stop frame
_state = (_frame != _stopFrame ? PLAYING : STOPPED);
return this;
}
/** Stops playback if it's currently active. Doesn't alter the current frame or stop frame. */
public function stop () :Movie {
_state = STOPPED;
return this;
}
/** Stops playback of this movie, but not its children */
public function playChildrenOnly () :Movie {
_state = PLAYING_CHILDREN_ONLY;
return this;
}
/** Advances the playhead by the give number of seconds. From IAnimatable. */
public function advanceTime (dt :Number) :void {
if (dt < 0) {
throw new Error("Invalid time [dt=" + dt + "]");
}
if (_skipAdvanceTime) {
_skipAdvanceTime = false;
return;
}
if (_state == STOPPED) {
return;
}
if (_state == PLAYING && _numFrames > 1) {
_playTime += dt;
var actualPlaytime :Number = _playTime;
if (_playTime >= _duration) {
_playTime %= _duration;
}
// If _playTime is very close to _duration, rounding error can cause us to
// land on lastFrame + 1. Protect against that.
var newFrame :int = int(_playTime * _frameRate);
if (newFrame < 0) {
newFrame = 0;
} else if (newFrame >= _numFrames) {
newFrame = _numFrames - 1;
}
// If the update crosses or goes to the stopFrame:
// go to the stopFrame, stop the movie, clear the stopFrame
if (_stopFrame != NO_FRAME) {
// how many frames remain to the stopframe?
var framesRemaining :int =
(_frame <= _stopFrame ? _stopFrame - _frame : _numFrames - _frame + _stopFrame);
var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame;
if (framesElapsed >= framesRemaining) {
_state = STOPPED;
newFrame = _stopFrame;
}
}
updateFrame(newFrame, dt);
}
for each (var layer :Layer in _layers) {
layer.advanceTime(dt);
}
}
/**
* @public
*
* Modified from starling.display.DisplayObjectContainer
*/
public override function getBounds (targetSpace :DisplayObject, resultRect :Rectangle=null) :Rectangle {
if (resultRect == null) {
resultRect = new Rectangle();
} else {
resultRect.setEmpty();
}
// get bounds from layer contents
for each (var layer :Layer in _layers) {
layer.expandBounds(targetSpace, resultRect);
}
// if no contents exist, simply include this movie's position in the bounds
if (resultRect.isEmpty()) {
getTransformationMatrix(targetSpace, IDENTITY_MATRIX);
MatrixUtil.transformCoords(IDENTITY_MATRIX, 0.0, 0.0, HELPER_POINT);
resultRect.setTo(HELPER_POINT.x, HELPER_POINT.y, 0, 0);
}
return resultRect;
}
/**
* @private
*
* Called when the Movie has been newly added to a layer.
*/
internal function addedToLayer () :void {
goTo(0);
_skipAdvanceTime = true;
}
/** @private */
protected function extractFrame (position :Object) :int {
if (position is int) return int(position);
if (!(position is String)) throw new Error("Movie position must be an int frame or String label");
const label :String = String(position);
var frame :int = getFrameForLabel(label);
if (frame < 0) {
throw new Error("No such label '" + label + "'");
}
return frame;
}
/**
* @private
*
* @param dt the timeline's elapsed time since the last update. This should be 0
* for updates that are the result of a "goTo" call.
*/
protected function updateFrame (newFrame :int, dt :Number) :void {
if (newFrame < 0 || newFrame >= _numFrames) {
throw new Error("Invalid frame [frame=" + newFrame + ", validRange=0-" + (_numFrames - 1) + "]");
}
if (_isUpdatingFrame) {
_pendingFrame = newFrame;
return;
}
_pendingFrame = NO_FRAME;
_isUpdatingFrame = true;
const isGoTo :Boolean = (dt <= 0);
const wrapped :Boolean = (dt >= _duration) || (newFrame < _frame);
if (newFrame != _frame) {
for each (var layer :Layer in _layers) {
layer.drawFrame(newFrame);
}
}
if (isGoTo) {
_playTime = newFrame / _frameRate;
}
// Update the frame before firing frame label signals, so if firing changes the frame,
// it sticks.
const oldFrame :int = _frame;
_frame = newFrame;
// determine which labels to fire signals for
var startFrame :int;
var frameCount :int;
if (isGoTo) {
startFrame = newFrame;
frameCount = 1;
} else {
startFrame = (oldFrame + 1 < _numFrames ? oldFrame + 1 : 0);
frameCount = (_frame - oldFrame);
if (wrapped) {
frameCount += _numFrames;
}
}
// Fire signals. Stop if pendingFrame is updated, which indicates that the client
// has called goTo()
var frameIdx :int = startFrame;
for (var ii :int = 0; ii < frameCount; ++ii) {
if (_pendingFrame != NO_FRAME) break;
if (_labels[frameIdx] != null) {
for each (var label :String in _labels[frameIdx]) {
labelPassed.emit(label);
if (_pendingFrame != NO_FRAME) break;
}
}
// avoid modulo division by updating frameIdx each time through the loop
if (++frameIdx == _numFrames) {
frameIdx = 0;
}
}
_isUpdatingFrame = false;
// If we were interrupted by a goTo(), update to that frame now.
if (_pendingFrame != NO_FRAME) {
newFrame = _pendingFrame;
updateFrame(newFrame, 0);
}
}
protected function createLayer (movie :Movie, src :LayerMold, library :Library, flipbook :Boolean) :Layer {
return new Layer(movie, src, library, flipbook);
}
/** @private */
protected var _isUpdatingFrame :Boolean;
/** @private */
protected var _pendingFrame :int = NO_FRAME;
/** @private */
protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME;
/** @private */
protected var _state :int = PLAYING;
/** @private */
protected var _playTime :Number = 0;
/** @private */
protected var _duration :Number;
/** @private */
protected var _layers :Vector.<Layer>;
/** @private */
protected var _numFrames :int;
/** @private */
protected var _frameRate :Number;
/** @private */
protected var _labels :Vector.<Vector.<String>>;
/** @private */
private var _skipAdvanceTime :Boolean = false;
/** @private */
internal var _playerData :MoviePlayerNode;
private static const HELPER_POINT :Point = new Point();
private static const IDENTITY_MATRIX :Matrix = new Matrix();
private static const NO_FRAME :int = -1;
private static const STOPPED :int = 0;
private static const PLAYING_CHILDREN_ONLY :int = 1;
private static const PLAYING :int = 2;
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.display {
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
import flump.mold.LayerMold;
import flump.mold.MovieMold;
import react.Signal;
import starling.animation.IAnimatable;
import starling.display.DisplayObject;
import starling.display.Sprite;
import starling.events.Event;
import starling.utils.MatrixUtil;
/**
* A movie created from flump-exported data. It has children corresponding to the layers in the
* movie in Flash, in the same order and with the same names. It fills in those children
* initially with the image or movie of the symbol on that exported layer. After the initial
* population, it only applies the keyframe-based transformations to the child at the index
* corresponding to the layer. This means it's safe to swap in other DisplayObjects at those
* positions to have them animated in place of the initial child.
*
* <p>A Movie will not animate unless it's added to a Juggler (or its advanceTime() function
* is otherwise called). When the movie is added to a juggler, it advances its playhead with the
* frame ticks if isPlaying is true. It will automatically remove itself from its juggler when
* removed from the stage.</p>
*
* @see Library and LibraryLoader to create instances of Movie.
*/
public class Movie extends Sprite
implements IAnimatable
{
/** A label fired by all movies when entering their first frame. */
public static const FIRST_FRAME :String = "flump.movie.FIRST_FRAME";
/** A label fired by all movies when entering their last frame. */
public static const LAST_FRAME :String = "flump.movie.LAST_FRAME";
/** Fires the label string whenever it's passed in playing. */
public const labelPassed :Signal = new Signal(String);
/** @private */
public function Movie (src :MovieMold, frameRate :Number, library :Library) {
this.name = src.id;
_labels = src.labels;
_frameRate = frameRate;
if (src.flipbook) {
_layers = new Vector.<Layer>(1, true);
_layers[0] = createLayer(this, src.layers[0], library, /*flipbook=*/true);
_numFrames = src.layers[0].frames;
} else {
_layers = new Vector.<Layer>(src.layers.length, true);
for (var ii :int = 0; ii < _layers.length; ii++) {
_layers[ii] = createLayer(this, src.layers[ii], library, /*flipbook=*/false);
_numFrames = Math.max(src.layers[ii].frames, _numFrames);
}
}
_duration = _numFrames / _frameRate;
updateFrame(0, 0);
// When we're removed from the stage, remove ourselves from any juggler animating us.
addEventListener(Event.REMOVED_FROM_STAGE, function (..._) :void {
dispatchEventWith(Event.REMOVE_FROM_JUGGLER);
});
}
/** @return the frame being displayed. */
public function get frame () :int { return _frame; }
/** @return the number of frames in the movie. */
public function get numFrames () :int { return _numFrames; }
/** @return true if the movie is currently playing. */
public function get isPlaying () :Boolean { return _state == PLAYING; }
/** @return true if the movie contains the given label. */
public function hasLabel (label :String) :Boolean {
return getFrameForLabel(label) >= 0;
}
/** @return the frame index for the given label, or -1 if the label doesn't exist. */
public function getFrameForLabel (label :String) :int {
for (var ii :int = 0; ii < _labels.length; ii++) {
if (_labels[ii] != null && _labels[ii].indexOf(label) != -1) return ii;
}
return -1;
}
/** Plays the movie from its current frame. The movie will loop forever. */
public function loop () :Movie {
_state = PLAYING;
_stopFrame = NO_FRAME;
return this;
}
/** Plays the movie from its current frame, stopping when it reaches its last frame. */
public function playOnce () :Movie { return playTo(LAST_FRAME); }
/**
* Moves to the given String label or int frame. Doesn't alter playing status or stop frame.
* If there are labels at the given position, they're fired as part of the goto, even if the
* current frame is equal to the destination. Labels between the current frame and the
* destination frame are not fired.
*
* @param position the int frame or String label to goto.
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie
*/
public function goTo (position :Object) :Movie {
const frame :int = extractFrame(position);
updateFrame(frame, 0);
return this;
}
/**
* Plays the movie from its current frame. The movie will stop when it reaches the given label
* or frame.
*
* @param position to int frame or String label to stop at
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie.
*/
public function playTo (position :Object) :Movie {
// won't play if we're already at the stop position
return stopAt(position).play();
}
/**
* Sets the stop frame for this Movie.
*
* @param position the int frame or String label to stop at.
*
* @return this movie for chaining
*
* @throws Error if position isn't an int or String, or if it is a String and that String isn't
* a label on this movie.
*/
public function stopAt (position :Object) :Movie {
_stopFrame = extractFrame(position);
return this;
}
/**
* Sets the movie playing. It will automatically stop at its stopFrame, if one is set,
* otherwise it will loop forever.
*
* @return this movie for chaining
*/
public function play () :Movie {
// set playing to true unless movie is at the stop frame
_state = (_frame != _stopFrame ? PLAYING : STOPPED);
return this;
}
/** Stops playback if it's currently active. Doesn't alter the current frame or stop frame. */
public function stop () :Movie {
_state = STOPPED;
return this;
}
/** Stops playback of this movie, but not its children */
public function playChildrenOnly () :Movie {
_state = PLAYING_CHILDREN_ONLY;
return this;
}
/** Advances the playhead by the give number of seconds. From IAnimatable. */
public function advanceTime (dt :Number) :void {
if (dt < 0) {
throw new Error("Invalid time [dt=" + dt + "]");
}
if (_skipAdvanceTime) {
_skipAdvanceTime = false;
return;
}
if (_state == STOPPED) {
return;
}
if (_state == PLAYING && _numFrames > 1) {
_playTime += dt;
var actualPlaytime :Number = _playTime;
if (_playTime >= _duration) {
_playTime %= _duration;
}
// If _playTime is very close to _duration, rounding error can cause us to
// land on lastFrame + 1. Protect against that.
var newFrame :int = int(_playTime * _frameRate);
if (newFrame < 0) {
newFrame = 0;
} else if (newFrame >= _numFrames) {
newFrame = _numFrames - 1;
}
// If the update crosses or goes to the stopFrame:
// go to the stopFrame, stop the movie, clear the stopFrame
if (_stopFrame != NO_FRAME) {
// how many frames remain to the stopframe?
var framesRemaining :int =
(_frame <= _stopFrame ? _stopFrame - _frame : _numFrames - _frame + _stopFrame);
var framesElapsed :int = int(actualPlaytime * _frameRate) - _frame;
if (framesElapsed >= framesRemaining) {
_state = STOPPED;
newFrame = _stopFrame;
}
}
updateFrame(newFrame, dt);
}
for each (var layer :Layer in _layers) {
layer.advanceTime(dt);
}
}
/**
* @public
*
* Modified from starling.display.DisplayObjectContainer
*/
public override function getBounds (targetSpace :DisplayObject, resultRect :Rectangle=null) :Rectangle {
if (resultRect == null) {
resultRect = new Rectangle();
} else {
resultRect.setEmpty();
}
// get bounds from layer contents
for each (var layer :Layer in _layers) {
layer.expandBounds(targetSpace, resultRect);
}
// if no contents exist, simply include this movie's position in the bounds
if (resultRect.isEmpty()) {
getTransformationMatrix(targetSpace, IDENTITY_MATRIX);
MatrixUtil.transformCoords(IDENTITY_MATRIX, 0.0, 0.0, HELPER_POINT);
resultRect.setTo(HELPER_POINT.x, HELPER_POINT.y, 0, 0);
}
return resultRect;
}
/**
* @private
*
* Called when the Movie has been newly added to a layer.
*/
internal function addedToLayer () :void {
goTo(0);
_skipAdvanceTime = true;
}
/** @private */
protected function extractFrame (position :Object) :int {
if (position is int) return int(position);
if (!(position is String)) throw new Error("Movie position must be an int frame or String label");
const label :String = String(position);
var frame :int = getFrameForLabel(label);
if (frame < 0) {
throw new Error("No such label '" + label + "'");
}
return frame;
}
/**
* @private
*
* @param dt the timeline's elapsed time since the last update. This should be 0
* for updates that are the result of a "goTo" call.
*/
protected function updateFrame (newFrame :int, dt :Number) :void {
if (newFrame < 0 || newFrame >= _numFrames) {
throw new Error("Invalid frame [frame=" + newFrame + ", validRange=0-" + (_numFrames - 1) + "]");
}
if (_isUpdatingFrame) {
_pendingFrame = newFrame;
return;
}
_pendingFrame = NO_FRAME;
_isUpdatingFrame = true;
const isGoTo :Boolean = (dt <= 0);
const wrapped :Boolean = (dt >= _duration) || (newFrame < _frame);
if (newFrame != _frame) {
for each (var layer :Layer in _layers) {
layer.drawFrame(newFrame);
}
}
if (isGoTo) {
_playTime = newFrame / _frameRate;
}
// Update the frame before firing frame label signals, so if firing changes the frame,
// it sticks.
const oldFrame :int = _frame;
_frame = newFrame;
// determine which labels to fire signals for
var startFrame :int;
var frameCount :int;
if (isGoTo) {
startFrame = newFrame;
frameCount = 1;
} else {
startFrame = (oldFrame + 1 < _numFrames ? oldFrame + 1 : 0);
frameCount = (_frame - oldFrame);
if (wrapped) {
frameCount += _numFrames;
}
}
// Fire signals. Stop if pendingFrame is updated, which indicates that the client
// has called goTo()
var frameIdx :int = startFrame;
for (var ii :int = 0; ii < frameCount; ++ii) {
if (_pendingFrame != NO_FRAME) break;
if (_labels[frameIdx] != null) {
for each (var label :String in _labels[frameIdx]) {
labelPassed.emit(label);
if (_pendingFrame != NO_FRAME) break;
}
}
// avoid modulo division by updating frameIdx each time through the loop
if (++frameIdx == _numFrames) {
frameIdx = 0;
}
}
_isUpdatingFrame = false;
// If we were interrupted by a goTo(), update to that frame now.
if (_pendingFrame != NO_FRAME) {
newFrame = _pendingFrame;
updateFrame(newFrame, 0);
}
}
protected function createLayer (movie :Movie, src :LayerMold, library :Library, flipbook :Boolean) :Layer {
return new Layer(movie, src, library, flipbook);
}
/** @private */
protected var _isUpdatingFrame :Boolean;
/** @private */
protected var _pendingFrame :int = NO_FRAME;
/** @private */
protected var _frame :int = NO_FRAME, _stopFrame :int = NO_FRAME;
/** @private */
protected var _state :String = PLAYING;
/** @private */
protected var _playTime :Number = 0;
/** @private */
protected var _duration :Number;
/** @private */
protected var _layers :Vector.<Layer>;
/** @private */
protected var _numFrames :int;
/** @private */
protected var _frameRate :Number;
/** @private */
protected var _labels :Vector.<Vector.<String>>;
/** @private */
private var _skipAdvanceTime :Boolean = false;
/** @private */
internal var _playerData :MoviePlayerNode;
private static const HELPER_POINT :Point = new Point();
private static const IDENTITY_MATRIX :Matrix = new Matrix();
private static const NO_FRAME :int = -1;
private static const STOPPED :String = "STOPPED";
private static const PLAYING_CHILDREN_ONLY :String = "PLAYING_CHILDREN_ONLY";
private static const PLAYING :String = "PLAYING";
}
}
|
use Strings for states
|
use Strings for states
|
ActionScript
|
mit
|
mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump,tconkling/flump
|
9cef884c60fa5c4cea7eb1fa092c9fb53a8a1550
|
ProxyPair.as
|
ProxyPair.as
|
package
{
import flash.errors.IllegalOperationError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TextEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
import swfcat;
public class ProxyPair extends EventDispatcher
{
private var ui:swfcat;
protected var client_addr:Object;
/* Not defined here: subclasses should define their own
* protected var client_socket:Object;
*/
private var c2r_schedule:Array;
private var relay_addr:Object;
private var relay_socket:Socket;
private var r2c_schedule:Array;
// Callback id.
private var flush_id:uint;
public function ProxyPair(self:ProxyPair, ui:swfcat)
{
if (self != this) {
//only a subclass can pass a valid reference to self
throw new IllegalOperationError("ProxyPair cannot be instantiated directly.");
}
this.ui = ui;
this.c2r_schedule = new Array();
this.r2c_schedule = new Array();
setup_relay_socket();
/* client_socket setup should be taken */
/* care of in the subclass constructor */
}
public function close():void
{
if (relay_socket != null && relay_socket.connected) {
relay_socket.close();
}
/* subclasses should override to close */
/* their client_socket according to impl. */
}
public function get connected():Boolean
{
return (relay_socket != null && relay_socket.connected);
/* subclasses should override to check */
/* connectivity of their client_socket. */
}
public function set client(client_addr:Object):void
{
/* subclasses should override to */
/* connect the client_socket here */
}
public function set relay(relay_addr:Object):void
{
this.relay_addr = relay_addr;
log("Relay: connecting to " + relay_addr.host + ":" + relay_addr.port + ".");
relay_socket.connect(relay_addr.host, relay_addr.port);
}
protected function transfer_bytes(src:Object, dst:Object, num_bytes:uint):void
{
/* No-op: must be overridden by subclasses */
}
protected function socket_error(message:String):Function
{
return function(e:Event):void {
if (e is TextEvent)
log(message + ": " + (e as TextEvent).text + ".");
else
log(message + ".");
close();
};
}
private function setup_relay_socket():void
{
relay_socket = new Socket();
relay_socket.addEventListener(Event.CONNECT, function (e:Event):void {
log("Relay: connected to " + relay_addr.host + ":" + relay_addr.port + ".");
if (connected) {
dispatchEvent(new Event(Event.CONNECT));
}
});
relay_socket.addEventListener(Event.CLOSE, socket_error("Relay: closed"));
relay_socket.addEventListener(IOErrorEvent.IO_ERROR, socket_error("Relay: I/O error"))
relay_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, socket_error("Relay: security error"))
relay_socket.addEventListener(ProgressEvent.SOCKET_DATA, relay_to_client);
}
protected function client_to_relay(e:ProgressEvent):void
{
c2r_schedule.push(e.bytesLoaded);
flush();
}
private function relay_to_client(e:ProgressEvent):void
{
r2c_schedule.push(e.bytesLoaded);
flush();
}
/* Send as much data as the rate limit currently allows. */
private function flush():void
{
if (flush_id)
clearTimeout(flush_id);
flush_id = undefined;
if (!connected)
/* Can't do anything until connected. */
return;
while (!ui.rate_limit.is_limited() && (c2r_schedule.length > 0 || r2c_schedule.length > 0)) {
var num_bytes:uint;
if (c2r_schedule.length > 0) {
num_bytes = c2r_schedule.shift();
transfer_bytes(null, relay_socket, num_bytes);
ui.rate_limit.update(num_bytes);
}
if (r2c_schedule.length > 0) {
num_bytes = r2c_schedule.shift();
transfer_bytes(relay_socket, null, num_bytes);
ui.rate_limit.update(num_bytes);
}
}
/* Call again when safe, if necessary. */
if (c2r_schedule.length > 0 || r2c_schedule.length > 0)
flush_id = setTimeout(flush, ui.rate_limit.when() * 1000);
}
/* Helper function to write output to the
* swfcat console. Set as protected for
* subclasses */
protected function log(s:String):void
{
ui.puts(s);
}
}
}
|
package
{
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.events.TextEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
import flash.utils.clearTimeout;
import flash.utils.setTimeout;
/* An instance of a client-relay connection. */
public class ProxyPair extends EventDispatcher
{
// Socket to client.
private var s_c:*;
private var connect_c:Function;
// Socket to relay.
private var s_r:*;
private var connect_r:Function;
// Parent swfcat, for UI updates and rate meter.
private var ui:swfcat;
// Pending byte read counts for relay and client sockets.
private var r2c_schedule:Array;
private var c2r_schedule:Array;
// Callback id.
private var flush_id:uint;
public function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
public function id():String
{
return "<>";
}
public function ProxyPair(ui:swfcat, s_c:*, connect_c:Function, s_r:*, connect_r:Function)
{
this.ui = ui;
/* s_c is a socket for connecting to the client. connect_c is a
function that, when called, connects s_c. Likewise for s_r and
connect_r. */
this.s_c = s_c;
this.connect_c = connect_c;
this.s_r = s_r;
this.connect_r = connect_r;
this.c2r_schedule = [];
this.r2c_schedule = [];
}
/* Return a function that shows an error message and closes the other half
of a communication pair. */
private function socket_error(message:String, other:*):Function
{
return function(e:Event):void {
if (e is TextEvent)
log(message + ": " + (e as TextEvent).text + ".");
else
log(message + ".");
if (other && other.connected)
other.close();
dispatchEvent(new Event(Event.COMPLETE));
};
}
public function connect():void
{
s_r.addEventListener(Event.CONNECT, relay_connected);
s_r.addEventListener(Event.CLOSE, socket_error("Relay: closed", s_c));
s_r.addEventListener(IOErrorEvent.IO_ERROR, socket_error("Relay: I/O error", s_c));
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, socket_error("Relay: security error", s_c));
s_r.addEventListener(ProgressEvent.SOCKET_DATA, relay_to_client);
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, socket_error("Client: closed", s_r));
s_c.addEventListener(IOErrorEvent.IO_ERROR, socket_error("Client: I/O error", s_r));
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, socket_error("Client: security error", s_r));
s_c.addEventListener(ProgressEvent.SOCKET_DATA, client_to_relay);
log("Relay: connecting.");
connect_r();
log("Client: connecting.");
connect_c();
}
private function relay_connected(e:Event):void
{
log("Relay: connected.");
}
private function client_connected(e:Event):void
{
log("Client: connected.");
}
private function relay_to_client(e:ProgressEvent):void
{
r2c_schedule.push(e.bytesLoaded);
flush();
}
private function client_to_relay(e:ProgressEvent):void
{
c2r_schedule.push(e.bytesLoaded);
flush();
}
private function transfer_chunk(s_from:*, s_to:*, n:uint,
label:String):void
{
var bytes:ByteArray;
bytes = new ByteArray();
s_from.readBytes(bytes, 0, n);
s_to.writeBytes(bytes);
ui.rate_limit.update(n);
log(label + ": read " + bytes.length + ".");
}
/* Send as much data as the rate limit currently allows. */
private function flush():void
{
if (flush_id)
clearTimeout(flush_id);
flush_id = undefined;
if (!(s_r.connected && s_c.connected))
/* Can't do anything until both sockets are connected. */
return;
while (!ui.rate_limit.is_limited() &&
(r2c_schedule.length > 0 || c2r_schedule.length > 0)) {
if (r2c_schedule.length > 0)
transfer_chunk(s_r, s_c, r2c_schedule.shift(), "Relay");
if (c2r_schedule.length > 0)
transfer_chunk(s_c, s_r, c2r_schedule.shift(), "Client");
}
/* Call again when safe, if necessary. */
if (r2c_schedule.length > 0 || c2r_schedule.length > 0)
flush_id = setTimeout(flush, ui.rate_limit.when() * 1000);
}
}
}
|
Rewrite ProxyPair to be more generic.
|
Rewrite ProxyPair to be more generic.
|
ActionScript
|
mit
|
glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,infinity0/flashproxy,infinity0/flashproxy,glamrock/flashproxy
|
26ddb9481158e3e56e61b9aca8915a4e8c1f5b6a
|
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 _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 each (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(
Vector4.ZERO, 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);
updateGeometry(geometry);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
_changes = {};
for (var parameter : String in _bindings)
{
meshBindings.removeCallback(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.concat();
_fsConstants = program._fsConstants.concat();
_fsTextures = program._fsTextures.concat();
_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
{
_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);
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).getNativeTexture(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 _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(
Vector4.ZERO, 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);
updateGeometry(geometry);
setGeometry(geometry);
setBindings(meshBindings, sceneBindings, computeDepth);
}
public function unsetBindings(meshBindings : DataBindings,
sceneBindings : DataBindings) : void
{
_changes = {};
for (var parameter : String in _bindings)
{
meshBindings.removeCallback(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.concat();
_fsConstants = program._fsConstants.concat();
_fsTextures = program._fsTextures.concat();
_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
{
_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);
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).getNativeTexture(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.enabled setter using a 'for each' instead of a 'for' to loop on the changed bindings
|
fix DrawCall.enabled setter using a 'for each' instead of a 'for' to loop on the changed bindings
|
ActionScript
|
mit
|
aerys/minko-as3
|
3086f976e2f5996cc56552ce9930496ad9d218b2
|
src/battlecode/world/signals/RobotInfoSignal.as
|
src/battlecode/world/signals/RobotInfoSignal.as
|
package battlecode.world.signals {
import battlecode.common.AttackType;
import battlecode.common.MapLocation;
public class RobotInfoSignal implements Signal {
private var robotID:uint;
private var health:Number;
public function RobotInfoSignal(robotID:uint, health:Number) {
this.robotID = robotID;
this.health = health;
}
public function getRobotID():uint {
return robotID;
}
public function getHealth():Number {
return health;
}
public function accept(handler:SignalHandler):* {
return handler.visitRobotInfoSignal(this);
}
}
}
|
package battlecode.world.signals {
public class RobotInfoSignal implements Signal {
private var robotID:uint;
private var health:Number;
public function RobotInfoSignal(robotID:uint, health:Number) {
this.robotID = robotID;
this.health = health;
}
public function getRobotID():uint {
return robotID;
}
public function getHealth():Number {
return health;
}
public function accept(handler:SignalHandler):* {
return handler.visitRobotInfoSignal(this);
}
}
}
|
remove unused imports
|
remove unused imports
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
8dd8a6a762ad7e087b4e94d77d3df766a4b5b8a7
|
src/org/openPyro/controls/Image.as
|
src/org/openPyro/controls/Image.as
|
package org.openPyro.controls
{
import org.openPyro.core.UIControl;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLRequest;
import flash.system.LoaderContext;
public class Image extends UIControl
{
private var _sourceURL:String = "";
private var _loader:Loader;
public function Image() {
super();
}
override protected function createChildren():void
{
super.createChildren();
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
addChild(_loader);
if(!_loaderContext)
{
_loaderContext = new LoaderContext(true);
}
if(_autoLoad && (_sourceURL != "")){
_loader.load(new URLRequest(_sourceURL), _loaderContext);
}
}
protected var _autoLoad:Boolean = true;
public function set autoLoad(b:Boolean):void
{
_autoLoad = b;
}
public function get autoLoad():Boolean
{
return _autoLoad;
}
public function set source(url:String):void
{
if(url == _sourceURL) return;
_sourceURL = url;
if(_loader && _autoLoad){
_loader.load(new URLRequest(url), _loaderContext);
}
}
private var _loaderContext:LoaderContext
/**
* The LoaderContext that is used when loading an
* image.
*/
public function set loaderContext(context:LoaderContext):void
{
_loaderContext = context;
}
/**
* @private
*/
public function get loaderContext():LoaderContext
{
return _loaderContext;
}
/**
* Returns the raw loader being used to load the image
*/
public function get loader():Loader
{
return _loader;
}
protected var _originalContentWidth:Number = NaN;
protected var _originalContentHeight:Number = NaN;
protected function onLoadComplete(event:Event):void
{
_originalContentWidth = _loader.content.width;
_originalContentHeight = _loader.content.height;
dispatchEvent(new Event(Event.COMPLETE));
forceInvalidateDisplayList = true;
invalidateSize();
invalidateDisplayList()
}
override protected function doChildBasedValidation():void{
if(!_loader || !_loader.content) return;
if(isNaN(this._explicitWidth) && isNaN(this._percentWidth) && isNaN(_percentUnusedWidth)){
measuredWidth = _originalContentWidth + _padding.left + _padding.right;
}
if(isNaN(this._explicitHeight) && isNaN(this._percentHeight) && isNaN(_percentUnusedHeight))
{
measuredHeight = _originalContentWidth + _padding.top + _padding.bottom;
}
}
public function get contentWidth():Number{
return _loader.content.width;
}
public function get contentHeight():Number{
return _loader.content.height;
}
public function get originalContentWidth():Number{
return _originalContentWidth
}
public function get originalContentHeight():Number{
return _originalContentHeight;
}
protected function onIOError(event:IOErrorEvent):void
{
//todo: Put broken thumb skin here//
}
protected var _scaleToFit:Boolean = true;
public function get scaleToFit():Boolean
{
return _scaleToFit;
}
public function set scaleToFit(value:Boolean):void
{
_scaleToFit = value;
if(_scaleToFit && _loader && _loader.content)
{
scaleImageContent()
}
}
protected var _maintainAspectRatio:Boolean = true;
public function set maintainAspectRatio(value:Boolean):void
{
_maintainAspectRatio = value;
}
public function get maintainAspectRatio():Boolean
{
return _maintainAspectRatio;
}
protected function scaleImageContent():void
{
var scaleX:Number;
var scaleY:Number;
scaleX = width / _originalContentWidth;
scaleY = height / _originalContentHeight;
if(_maintainAspectRatio)
{
var scale:Number = Math.min(scaleX, scaleY);
_loader.content.width = _originalContentWidth*scale;
_loader.content.height = _originalContentHeight*scale;
}
else
{
_loader.content.width = _originalContentWidth*scaleX;
_loader.content.height = _originalContentHeight*scaleY;
}
}
override public function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
if(_loader && _loader.content && _scaleToFit){
scaleImageContent()
}
_loader.x = _padding.left
_loader.y = _padding.top;
}
}
}
|
package org.openPyro.controls
{
import org.openPyro.core.UIControl;
import flash.display.Loader;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.URLRequest;
import flash.system.LoaderContext;
public class Image extends UIControl
{
private var _sourceURL:String = "";
private var _loader:Loader;
public function Image() {
super();
}
override protected function createChildren():void
{
super.createChildren();
_loader = new Loader();
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
addChild(_loader);
_loader.visible = false;
if(!_loaderContext)
{
_loaderContext = new LoaderContext(true);
}
if(_autoLoad && (_sourceURL != "")){
_loader.load(new URLRequest(_sourceURL), _loaderContext);
}
}
protected var _autoLoad:Boolean = true;
public function set autoLoad(b:Boolean):void
{
_autoLoad = b;
}
public function get autoLoad():Boolean
{
return _autoLoad;
}
public function set source(url:String):void
{
if(url == _sourceURL) return;
_sourceURL = url;
if(_loader && _autoLoad){
_loader.load(new URLRequest(url), _loaderContext);
}
}
private var _loaderContext:LoaderContext
/**
* The LoaderContext that is used when loading an
* image.
*/
public function set loaderContext(context:LoaderContext):void
{
_loaderContext = context;
}
/**
* @private
*/
public function get loaderContext():LoaderContext
{
return _loaderContext;
}
/**
* Returns the raw loader being used to load the image
*/
public function get loader():Loader
{
return _loader;
}
protected var _originalContentWidth:Number = NaN;
protected var _originalContentHeight:Number = NaN;
protected function onLoadComplete(event:Event):void
{
_originalContentWidth = _loader.content.width;
_originalContentHeight = _loader.content.height;
dispatchEvent(new Event(Event.COMPLETE));
forceInvalidateDisplayList = true;
invalidateSize();
invalidateDisplayList()
}
override protected function doChildBasedValidation():void{
if(!_loader || !_loader.content) return;
if(isNaN(this._explicitWidth) && isNaN(this._percentWidth) && isNaN(_percentUnusedWidth)){
measuredWidth = _originalContentWidth + _padding.left + _padding.right;
}
if(isNaN(this._explicitHeight) && isNaN(this._percentHeight) && isNaN(_percentUnusedHeight))
{
measuredHeight = _originalContentWidth + _padding.top + _padding.bottom;
}
}
public function get contentWidth():Number{
return _loader.content.width;
}
public function get contentHeight():Number{
return _loader.content.height;
}
public function get originalContentWidth():Number{
return _originalContentWidth
}
public function get originalContentHeight():Number{
return _originalContentHeight;
}
protected function onIOError(event:IOErrorEvent):void
{
//todo: Put broken thumb skin here//
}
protected var _scaleToFit:Boolean = true;
public function get scaleToFit():Boolean
{
return _scaleToFit;
}
public function set scaleToFit(value:Boolean):void
{
_scaleToFit = value;
if(_scaleToFit && _loader && _loader.content)
{
scaleImageContent()
}
}
protected var _maintainAspectRatio:Boolean = true;
public function set maintainAspectRatio(value:Boolean):void
{
_maintainAspectRatio = value;
}
public function get maintainAspectRatio():Boolean
{
return _maintainAspectRatio;
}
protected function scaleImageContent():void
{
var scaleX:Number;
var scaleY:Number;
scaleX = width / _originalContentWidth;
scaleY = height / _originalContentHeight;
if(_maintainAspectRatio)
{
var scale:Number = Math.min(scaleX, scaleY);
_loader.content.width = _originalContentWidth*scale;
_loader.content.height = _originalContentHeight*scale;
}
else
{
_loader.content.width = _originalContentWidth*scaleX;
_loader.content.height = _originalContentHeight*scaleY;
}
}
override public function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
{
super.updateDisplayList(unscaledWidth, unscaledHeight);
if(_loader && _loader.content){
_loader.visible = true;
if(_scaleToFit){
scaleImageContent();
}
}
_loader.x = _padding.left
_loader.y = _padding.top;
}
}
}
|
Fix to Image class so loader remains invisible till the content has been resized.
|
Fix to Image class so loader remains invisible till the content has been resized.
|
ActionScript
|
mit
|
arpit/openpyro
|
e6d03a1d3d8d05df4dd92aea9651cabec2455cc9
|
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
|
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers.supportClasses
{
import com.esri.builder.model.Model;
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.system.ApplicationDomain;
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;
import mx.resources.ResourceManager;
public class WidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader);
private var _moduleInfoArr:Array = [];
private var _widgetTypeArr:Array = [];
public function loadWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('Loading modules...');
}
const modulesDirectory:File = WellKnownDirectories.getInstance().bundledModules;
loadCustomWidgetTypes(WellKnownDirectories.getInstance().customModules);
// Find all swf files under the modules folder.
const swfList:Array = [];
if (modulesDirectory.isDirectory)
{
getSWFList(modulesDirectory, swfList);
}
// Load the found modules.
swfList.forEach(function(file:File, index:int, source:Array):void
{
if (Log.isDebug())
{
LOG.debug('loading module {0}', file.url);
}
var fileBytes:ByteArray = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
fileStream.readBytes(fileBytes);
fileStream.close();
const moduleInfo:IModuleInfo = ModuleManager.getModule(file.url);
_moduleInfoArr.push(moduleInfo);
moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.load(ApplicationDomain.currentDomain, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory);
});
checkIfNoMoreModuleInfosLeft();
}
private function loadCustomWidgetTypes(modulesDirectory:File):void
{
var moduleDirectoryContents:Array = modulesDirectory.getDirectoryListing();
for each (var fileOrFolder:File in moduleDirectoryContents)
{
loadCustomWidgetTypeConfig(fileOrFolder);
}
}
public function loadCustomWidgetTypeConfig(configFile:File):void
{
const customModuleFileName:RegExp = /^.*Module\.xml$/;
if (!configFile.isDirectory && customModuleFileName.test(configFile.name))
{
var customModule:IBuilderModule = createCustomModuleFromConfig(configFile);
if (customModule)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(new WidgetType(customModule));
}
}
}
private function createCustomModuleFromConfig(configFile:File):IBuilderModule
{
var fileStream:FileStream = new FileStream();
var customModule:CustomXMLModule;
try
{
fileStream.open(configFile, FileMode.READ);
const configXML:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
customModule = parseCustomModule(configXML);
}
catch (e:Error)
{
if (Log.isWarn())
{
LOG.warn('Error creating custom module {0}', configFile.nativePath);
}
}
finally
{
fileStream.close();
}
return customModule;
}
private function parseCustomModule(configXML:XML):CustomXMLModule
{
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:String = configXML.configuration[0];
var widgetVersion:String = configXML.widgetversion[0];
customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName);
customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName;
customModule.widgetVersion = widgetVersion;
customModule.widgetDescription = widgetDescription ? widgetDescription : "";
customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : "";
customModule.configXML = widgetConfiguration ? widgetConfiguration : "<configuration></configuration>";
return customModule;
}
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;
}
/**
* This will go through all sub folders in 'modules' looking for .swf files.
*/
private function getSWFList(parentFile:File, arr:Array):void
{
const moduleFileName:RegExp = /^.*Module\.swf$/;
const list:Array = parentFile.getDirectoryListing();
list.forEach(function(file:File, index:int, source:Array):void
{
if (file.isDirectory)
{
getSWFList(file, arr);
}
else if (moduleFileName.test(file.name))
{
arr.push(file);
}
}
);
}
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);
const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule;
if (builderModule)
{
const widgetType:WidgetType = new WidgetType(builderModule);
_widgetTypeArr.push(widgetType);
// Resolve the object
// FlexGlobals.topLevelApplication.registry.resolve(builderModule, ApplicationDomain.currentDomain);
if (Log.isDebug())
{
LOG.debug('Module {0} is resolved', widgetType.name);
}
removeModuleInfo(event.module);
}
}
private function removeModuleInfo(moduleInfo:IModuleInfo):void
{
const index:int = _moduleInfoArr.indexOf(moduleInfo);
if (index > -1)
{
_moduleInfoArr.splice(index, 1);
checkIfNoMoreModuleInfosLeft();
}
}
private function checkIfNoMoreModuleInfosLeft():void
{
if (_moduleInfoArr.length === 0)
{
sortAndAssignWidgetTypes();
}
}
private function sortAndAssignWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('All modules resolved');
}
_widgetTypeArr.sort(compareWidgetTypes);
var widgetTypes:Array = _widgetTypeArr.filter(widgetTypeFilter);
for each (var widgetType:WidgetType in widgetTypes)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType);
}
var layoutWidgetTypes:Array = _widgetTypeArr.filter(layoutWidgetTypeFilter);
for each (var layoutWidgetType:WidgetType in layoutWidgetTypes)
{
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(layoutWidgetType);
}
function widgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean
{
return item.isManaged;
}
function layoutWidgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean
{
return !item.isManaged;
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_TYPES_COMPLETE));
}
private function compareWidgetTypes(lhs:WidgetType, rhs:WidgetType):int
{
const lhsLabel:String = lhs.label.toLowerCase();
const rhsLabel:String = rhs.label.toLowerCase();
if (lhsLabel < rhsLabel)
{
return -1;
}
if (lhsLabel > rhsLabel)
{
return 1;
}
return 0;
}
private function moduleInfo_errorHandler(event:ModuleEvent):void
{
if (Log.isWarn())
{
LOG.warn('Module error: {0}', event.errorText);
}
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
removeModuleInfo(event.module);
Model.instance.status = event.errorText;
BuilderAlert.show(event.errorText,
ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers.supportClasses
{
import com.esri.builder.model.Model;
import com.esri.builder.model.WidgetType;
import com.esri.builder.model.WidgetTypeRegistryModel;
import com.esri.builder.supportClasses.LogUtil;
import com.esri.builder.views.BuilderAlert;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.system.ApplicationDomain;
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;
import mx.resources.ResourceManager;
public class WidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader);
private var _moduleInfoArr:Array = [];
private var _widgetTypeArr:Array = [];
public function loadWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('Loading modules...');
}
const modulesDirectory:File = WellKnownDirectories.getInstance().bundledModules;
loadCustomWidgetTypes(WellKnownDirectories.getInstance().customModules);
const swfList:Array = getModuleSWFs(modulesDirectory);
// Load the found modules.
swfList.forEach(function(file:File, index:int, source:Array):void
{
if (Log.isDebug())
{
LOG.debug('loading module {0}', file.url);
}
var fileBytes:ByteArray = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
fileStream.readBytes(fileBytes);
fileStream.close();
const moduleInfo:IModuleInfo = ModuleManager.getModule(file.url);
_moduleInfoArr.push(moduleInfo);
moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.load(ApplicationDomain.currentDomain, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory);
});
checkIfNoMoreModuleInfosLeft();
}
private function loadCustomWidgetTypes(modulesDirectory:File):void
{
var moduleDirectoryContents:Array = modulesDirectory.getDirectoryListing();
for each (var fileOrFolder:File in moduleDirectoryContents)
{
loadCustomWidgetTypeConfig(fileOrFolder);
}
}
public function loadCustomWidgetTypeConfig(configFile:File):void
{
const customModuleFileName:RegExp = /^.*Module\.xml$/;
if (!configFile.isDirectory && customModuleFileName.test(configFile.name))
{
var customModule:IBuilderModule = createCustomModuleFromConfig(configFile);
if (customModule)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(new WidgetType(customModule));
}
}
}
private function createCustomModuleFromConfig(configFile:File):IBuilderModule
{
var fileStream:FileStream = new FileStream();
var customModule:CustomXMLModule;
try
{
fileStream.open(configFile, FileMode.READ);
const configXML:XML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
customModule = parseCustomModule(configXML);
}
catch (e:Error)
{
if (Log.isWarn())
{
LOG.warn('Error creating custom module {0}', configFile.nativePath);
}
}
finally
{
fileStream.close();
}
return customModule;
}
private function parseCustomModule(configXML:XML):CustomXMLModule
{
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:String = configXML.configuration[0];
var widgetVersion:String = configXML.widgetversion[0];
customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName);
customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName;
customModule.widgetVersion = widgetVersion;
customModule.widgetDescription = widgetDescription ? widgetDescription : "";
customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : "";
customModule.configXML = widgetConfiguration ? widgetConfiguration : "<configuration></configuration>";
return customModule;
}
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;
}
/* Finds module SWF files at the parent-directory level */
private function getModuleSWFs(directory:File):Array
{
var swfFiles:Array = [];
if (directory.isDirectory)
{
const moduleFileName:RegExp = /^.*Module\.swf$/;
const files:Array = directory.getDirectoryListing();
for each (var file:File in files)
{
if (!file.isDirectory && moduleFileName.test(file.name))
{
swfFiles.push(file);
}
}
}
return swfFiles;
}
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);
const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule;
if (builderModule)
{
const widgetType:WidgetType = new WidgetType(builderModule);
_widgetTypeArr.push(widgetType);
// Resolve the object
// FlexGlobals.topLevelApplication.registry.resolve(builderModule, ApplicationDomain.currentDomain);
if (Log.isDebug())
{
LOG.debug('Module {0} is resolved', widgetType.name);
}
removeModuleInfo(event.module);
}
}
private function removeModuleInfo(moduleInfo:IModuleInfo):void
{
const index:int = _moduleInfoArr.indexOf(moduleInfo);
if (index > -1)
{
_moduleInfoArr.splice(index, 1);
checkIfNoMoreModuleInfosLeft();
}
}
private function checkIfNoMoreModuleInfosLeft():void
{
if (_moduleInfoArr.length === 0)
{
sortAndAssignWidgetTypes();
}
}
private function sortAndAssignWidgetTypes():void
{
if (Log.isInfo())
{
LOG.info('All modules resolved');
}
_widgetTypeArr.sort(compareWidgetTypes);
var widgetTypes:Array = _widgetTypeArr.filter(widgetTypeFilter);
for each (var widgetType:WidgetType in widgetTypes)
{
WidgetTypeRegistryModel.getInstance().widgetTypeRegistry.addWidgetType(widgetType);
}
var layoutWidgetTypes:Array = _widgetTypeArr.filter(layoutWidgetTypeFilter);
for each (var layoutWidgetType:WidgetType in layoutWidgetTypes)
{
WidgetTypeRegistryModel.getInstance().layoutWidgetTypeRegistry.addWidgetType(layoutWidgetType);
}
function widgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean
{
return item.isManaged;
}
function layoutWidgetTypeFilter(item:WidgetType, index:int, source:Array):Boolean
{
return !item.isManaged;
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_TYPES_COMPLETE));
}
private function compareWidgetTypes(lhs:WidgetType, rhs:WidgetType):int
{
const lhsLabel:String = lhs.label.toLowerCase();
const rhsLabel:String = rhs.label.toLowerCase();
if (lhsLabel < rhsLabel)
{
return -1;
}
if (lhsLabel > rhsLabel)
{
return 1;
}
return 0;
}
private function moduleInfo_errorHandler(event:ModuleEvent):void
{
if (Log.isWarn())
{
LOG.warn('Module error: {0}', event.errorText);
}
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
removeModuleInfo(event.module);
Model.instance.status = event.errorText;
BuilderAlert.show(event.errorText,
ResourceManager.getInstance().getString('BuilderStrings', 'error'));
}
}
}
|
Simplify logic for finding module SWFs.
|
Simplify logic for finding module SWFs.
* Expects widget SWFs to be at the parent-directory level.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
1e57e9c36d53d24d515e7019bb3a41a9a36a57a3
|
flash/Recorder.as
|
flash/Recorder.as
|
package
{
import com.adobe.audio.format.WAVWriter;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.events.ErrorEvent;
import flash.events.SampleDataEvent;
import flash.external.ExternalInterface;
import flash.media.Microphone;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.system.Capabilities;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.system.Security;
import flash.system.SecurityPanel;
import flash.events.StatusEvent;
import flash.utils.getQualifiedClassName;
import mx.collections.ArrayCollection;
import ru.inspirit.net.MultipartURLLoader;
public class Recorder
{
public function Recorder(logger)
{
this.logger = logger;
}
private var logger;
public function addExternalInterfaceCallbacks():void {
ExternalInterface.addCallback("record", this.record);
ExternalInterface.addCallback("_stop", this.stop);
ExternalInterface.addCallback("_play", this.play);
ExternalInterface.addCallback("upload", this.upload);
ExternalInterface.addCallback("audioData", this.audioData);
ExternalInterface.addCallback("showFlash", this.showFlash);
ExternalInterface.addCallback("recordingDuration", this.recordingDuration);
triggerEvent("initialized", {});
logger.log("Recorder initialized");
}
protected var isRecording:Boolean = false;
protected var isPlaying:Boolean = false;
protected var microphoneWasMuted:Boolean;
protected var playingProgressTimer:Timer;
protected var microphone:Microphone;
protected var buffer:ByteArray;
protected var sound:Sound;
protected var channel:SoundChannel;
protected var recordingStartTime = 0;
protected static var sampleRate = 44.1;
protected function record():void
{
if(!microphone){
setupMicrophone();
}
microphoneWasMuted = microphone.muted;
if(microphoneWasMuted){
logger.log('showFlashRequired');
triggerEvent('showFlash','');
}else{
notifyRecordingStarted();
}
buffer = new ByteArray();
microphone.addEventListener(SampleDataEvent.SAMPLE_DATA, recordSampleDataHandler);
}
protected function recordStop():int
{
logger.log('stopRecording');
isRecording = false;
triggerEvent('recordingStop', {duration: recordingDuration()});
microphone.removeEventListener(SampleDataEvent.SAMPLE_DATA, recordSampleDataHandler);
return recordingDuration();
}
protected function play():void
{
logger.log('startPlaying');
isPlaying = true;
triggerEvent('playingStart', {});
buffer.position = 0;
sound = new Sound();
sound.addEventListener(SampleDataEvent.SAMPLE_DATA, playSampleDataHandler);
channel = sound.play();
channel.addEventListener(Event.SOUND_COMPLETE, function(){
playStop();
});
if(playingProgressTimer){
playingProgressTimer.reset();
}
playingProgressTimer = new Timer(250);
playingProgressTimer.addEventListener(TimerEvent.TIMER, function playingProgressTimerHandler(event:TimerEvent){
triggerEvent('playingProgress', int(channel.position));
});
playingProgressTimer.start();
}
protected function stop():int
{
playStop();
return recordStop();
}
protected function playStop():void
{
logger.log('stopPlaying');
if(channel){
channel.stop();
playingProgressTimer.reset();
triggerEvent('playingStop', {});
isPlaying = false;
}
}
/* Networking functions */
protected function upload(uri:String, audioParam:String, parameters): void
{
logger.log("upload");
buffer.position = 0;
var wav:ByteArray = prepareWav();
var ml:MultipartURLLoader = new MultipartURLLoader();
ml.addEventListener(Event.COMPLETE, onReady);
function onReady(e:Event):void
{
triggerEvent('uploadSuccess', externalInterfaceEncode(e.target.loader.data));
logger.log('uploading done');
}
if(getQualifiedClassName(parameters.constructor) == "Array"){
for(var i=0; i<parameters.length; i++){
ml.addVariable(parameters[i][0], parameters[i][1]);
}
}else{
for(var k in parameters){
ml.addVariable(k, parameters[k]);
}
}
ml.addFile(wav, 'audio.wav', audioParam);
ml.load(uri, false);
}
private function externalInterfaceEncode(data:String){
return data.split("%").join("%25").split("\\").join("%5c").split("\"").join("%22").split("&").join("%26");
}
protected function audioData():String
{
var ret:String="";
buffer.position = 0;
while (buffer.bytesAvailable > 0)
{
ret += buffer.readFloat().toString() + ";";
}
return ret;
}
protected function showFlash():void
{
Security.showSettings(SecurityPanel.PRIVACY);
triggerEvent('showFlash','');
}
/* Recording Helper */
protected function setupMicrophone():void
{
logger.log('setupMicrophone');
microphone = Microphone.getMicrophone();
microphone.setSilenceLevel(0);
microphone.rate = sampleRate;
microphone.gain = 50;
microphone.addEventListener(StatusEvent.STATUS, function statusHandler(e:Event) {
logger.log('Microphone Status Change');
if(microphone.muted){
triggerEvent('recordingCancel','');
}else{
if(!isRecording){
notifyRecordingStarted();
}
}
});
logger.log('setupMicrophone done: ' + microphone.name + ' ' + microphone.muted);
}
protected function notifyRecordingStarted():void
{
if(microphoneWasMuted){
microphoneWasMuted = false;
triggerEvent('hideFlash','');
}
recordingStartTime = getTimer();
triggerEvent('recordingStart', {});
logger.log('startRecording');
isRecording = true;
}
/* Sample related */
protected function prepareWav():ByteArray
{
var wavData:ByteArray = new ByteArray();
var wavWriter:WAVWriter = new WAVWriter();
buffer.position = 0;
wavWriter.numOfChannels = 1; // set the inital properties of the Wave Writer
wavWriter.sampleBitRate = 16;
wavWriter.samplingRate = sampleRate * 1000;
wavWriter.processSamples(wavData, buffer, sampleRate * 1000, 1);
return wavData;
}
protected function recordingDuration():int
{
var latency = 650;
var duration = int(getTimer() - recordingStartTime - latency);
return Math.max(duration, 0);
}
protected function recordSampleDataHandler(event:SampleDataEvent):void
{
while(event.data.bytesAvailable)
{
var sample:Number = event.data.readFloat();
buffer.writeFloat(sample);
if(buffer.length % 40000 == 0){
triggerEvent('recordingProgress', recordingDuration(), microphone.activityLevel);
}
}
}
protected function playSampleDataHandler(event:SampleDataEvent):void
{
for (var i:int = 0; i < 8192 && buffer.bytesAvailable; i++)
{
var sample:Number = buffer.readFloat();
event.data.writeFloat(sample);
event.data.writeFloat(sample);
}
}
/* ExternalInterface Communication */
protected function triggerEvent(eventName:String, arg0, arg1 = null):void
{
ExternalInterface.call("Recorder.triggerEvent", eventName, arg0, arg1);
}
}
}
|
package
{
import com.adobe.audio.format.WAVWriter;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.events.ErrorEvent;
import flash.events.SampleDataEvent;
import flash.external.ExternalInterface;
import flash.media.Microphone;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.system.Capabilities;
import flash.utils.ByteArray;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.system.Security;
import flash.system.SecurityPanel;
import flash.events.StatusEvent;
import flash.utils.getQualifiedClassName;
import mx.collections.ArrayCollection;
import ru.inspirit.net.MultipartURLLoader;
public class Recorder
{
public function Recorder(logger)
{
this.logger = logger;
}
private var logger;
public function addExternalInterfaceCallbacks():void {
ExternalInterface.addCallback("record", this.record);
ExternalInterface.addCallback("_stop", this.stop);
ExternalInterface.addCallback("_play", this.play);
ExternalInterface.addCallback("upload", this.upload);
ExternalInterface.addCallback("audioData", this.audioData);
ExternalInterface.addCallback("showFlash", this.showFlash);
ExternalInterface.addCallback("recordingDuration", this.recordingDuration);
triggerEvent("initialized", {});
logger.log("Recorder initialized");
}
protected var isRecording:Boolean = false;
protected var isPlaying:Boolean = false;
protected var microphoneWasMuted:Boolean;
protected var playingProgressTimer:Timer;
protected var microphone:Microphone;
protected var buffer:ByteArray;
protected var sound:Sound;
protected var channel:SoundChannel;
protected var recordingStartTime = 0;
protected static var sampleRate = 44.1;
protected function record():void
{
if(!microphone){
setupMicrophone();
}
microphoneWasMuted = microphone.muted;
if(microphoneWasMuted){
logger.log('showFlashRequired');
triggerEvent('showFlash','');
}else{
notifyRecordingStarted();
}
buffer = new ByteArray();
microphone.addEventListener(SampleDataEvent.SAMPLE_DATA, recordSampleDataHandler);
}
protected function recordStop():int
{
logger.log('stopRecording');
isRecording = false;
triggerEvent('recordingStop', {duration: recordingDuration()});
microphone.removeEventListener(SampleDataEvent.SAMPLE_DATA, recordSampleDataHandler);
return recordingDuration();
}
protected function play():void
{
logger.log('startPlaying');
isPlaying = true;
triggerEvent('playingStart', {});
buffer.position = 0;
sound = new Sound();
sound.addEventListener(SampleDataEvent.SAMPLE_DATA, playSampleDataHandler);
channel = sound.play();
channel.addEventListener(Event.SOUND_COMPLETE, function(){
playStop();
});
if(playingProgressTimer){
playingProgressTimer.reset();
}
playingProgressTimer = new Timer(250);
playingProgressTimer.addEventListener(TimerEvent.TIMER, function playingProgressTimerHandler(event:TimerEvent){
triggerEvent('playingProgress', int(channel.position));
});
playingProgressTimer.start();
}
protected function stop():int
{
playStop();
return recordStop();
}
protected function playStop():void
{
logger.log('stopPlaying');
if(channel){
channel.stop();
playingProgressTimer.reset();
triggerEvent('playingStop', {});
isPlaying = false;
}
}
/* Networking functions */
protected function upload(uri:String, audioParam:String, parameters): void
{
logger.log("upload");
buffer.position = 0;
var wav:ByteArray = prepareWav();
var ml:MultipartURLLoader = new MultipartURLLoader();
ml.addEventListener(Event.COMPLETE, onReady);
function onReady(e:Event):void
{
triggerEvent('uploadSuccess', externalInterfaceEncode(e.target.loader.data));
logger.log('uploading done');
}
if(getQualifiedClassName(parameters.constructor) == "Array"){
for(var i=0; i<parameters.length; i++){
ml.addVariable(parameters[i][0], parameters[i][1]);
}
}else{
for(var k in parameters){
ml.addVariable(k, parameters[k]);
}
}
ml.addFile(wav, 'audio.wav', audioParam);
ml.load(uri, false);
}
private function externalInterfaceEncode(data:String){
return data.split("%").join("%25").split("\\").join("%5c").split("\"").join("%22").split("&").join("%26");
}
protected function audioData():String
{
var ret:String="";
buffer.position = 0;
while (buffer.bytesAvailable > 0)
{
ret += buffer.readFloat().toString() + ";";
}
return ret;
}
protected function showFlash():void
{
Security.showSettings(SecurityPanel.PRIVACY);
triggerEvent('showFlash','');
}
/* Recording Helper */
protected function setupMicrophone():void
{
logger.log('setupMicrophone');
microphone = Microphone.getMicrophone();
microphone.codec = "Nellymoser";
microphone.setSilenceLevel(0);
microphone.rate = sampleRate;
microphone.gain = 50;
microphone.addEventListener(StatusEvent.STATUS, function statusHandler(e:Event) {
logger.log('Microphone Status Change');
if(microphone.muted){
triggerEvent('recordingCancel','');
}else{
if(!isRecording){
notifyRecordingStarted();
}
}
});
logger.log('setupMicrophone done: ' + microphone.name + ' ' + microphone.muted);
}
protected function notifyRecordingStarted():void
{
if(microphoneWasMuted){
microphoneWasMuted = false;
triggerEvent('hideFlash','');
}
recordingStartTime = getTimer();
triggerEvent('recordingStart', {});
logger.log('startRecording');
isRecording = true;
}
/* Sample related */
protected function prepareWav():ByteArray
{
var wavData:ByteArray = new ByteArray();
var wavWriter:WAVWriter = new WAVWriter();
buffer.position = 0;
wavWriter.numOfChannels = 1; // set the inital properties of the Wave Writer
wavWriter.sampleBitRate = 16;
wavWriter.samplingRate = sampleRate * 1000;
wavWriter.processSamples(wavData, buffer, sampleRate * 1000, 1);
return wavData;
}
protected function recordingDuration():int
{
var latency = 650;
var duration = int(getTimer() - recordingStartTime - latency);
return Math.max(duration, 0);
}
protected function recordSampleDataHandler(event:SampleDataEvent):void
{
while(event.data.bytesAvailable)
{
var sample:Number = event.data.readFloat();
buffer.writeFloat(sample);
if(buffer.length % 40000 == 0){
triggerEvent('recordingProgress', recordingDuration(), microphone.activityLevel);
}
}
}
protected function playSampleDataHandler(event:SampleDataEvent):void
{
for (var i:int = 0; i < 8192 && buffer.bytesAvailable; i++)
{
var sample:Number = buffer.readFloat();
event.data.writeFloat(sample);
event.data.writeFloat(sample);
}
}
/* ExternalInterface Communication */
protected function triggerEvent(eventName:String, arg0, arg1 = null):void
{
ExternalInterface.call("Recorder.triggerEvent", eventName, arg0, arg1);
}
}
}
|
Update flash/Recorder.as
|
Update flash/Recorder.as
Explicitly setting the codec used. If this library is used in conjunction with another flash library that makes use of the microphone, and that library changes the codec to Speex, then the sampling rate will be forever stuck at "16". This causes recordings to sound like "chipmunks".
|
ActionScript
|
mit
|
jwagener/recorder.js
|
31fd4b65167054c2013966ef07d6bde86d451986
|
WEB-INF/lps/lfc/kernel/swf/dojo/flash8/DojoExternalInterface.as
|
WEB-INF/lps/lfc/kernel/swf/dojo/flash8/DojoExternalInterface.as
|
/**
A wrapper around Flash 8's ExternalInterface; DojoExternalInterface is needed so that we
can do a Flash 6 implementation of ExternalInterface, and be able
to support having a single codebase that uses DojoExternalInterface
across Flash versions rather than having two seperate source bases,
where one uses ExternalInterface and the other uses DojoExternalInterface.
DojoExternalInterface class does a variety of optimizations to bypass ExternalInterface's
unbelievably bad performance so that we can have good performance
on Safari; see the blog post
http://codinginparadise.org/weblog/2006/02/how-to-speed-up-flash-8s.html
for details.
@author Brad Neuberg, [email protected]
*/
#include "kernel/swf/dojo/flash8/ExpressInstall.as"
class DojoExternalInterfaceClass {
var available = null;
var flashMethods = [];
var numArgs = null;
var argData = null;
var resultData = null;
var _id;
function DojoExternalInterfaceClass(id){
// extract the dojo base path
//Debug.write('initialize', flash.external.ExternalInterface.addCallback);
// see if we need to do an express install
var install = new ExpressInstall();
if(install.needsUpdate){
install.init();
}
this._id = id;
// register our callback functions
var s = flash.external.ExternalInterface.addCallback("startExec", this, this.startExec);
//Debug.write('addCallback', s, this, this.startExec);
flash.external.ExternalInterface.addCallback("setNumberArguments", this, this.setNumberArguments);
flash.external.ExternalInterface.addCallback("chunkArgumentData", this, this.chunkArgumentData);
flash.external.ExternalInterface.addCallback("exec", this, this.exec);
flash.external.ExternalInterface.addCallback("getReturnLength", this, this.getReturnLength);
flash.external.ExternalInterface.addCallback("chunkReturnData", this, this.chunkReturnData);
flash.external.ExternalInterface.addCallback("endExec", this, this.endExec);
// set whether communication is available
DojoExternalInterface.available = flash.external.ExternalInterface.available;
DojoExternalInterface.call("loaded");
}
function addCallback(methodName, instance, method) {
//Debug.write('addCallback', methodName, instance, method);
// register DojoExternalInterface methodName with it's instance
this.flashMethods[methodName] = instance;
// tell JavaScript about DojoExternalInterface new method so we can create a proxy
//Debug.write('calling dojo.flash.comm.' + this._id + "._addExternalInterfaceCallback", methodName, this._id);
flash.external.ExternalInterface.call("dojo.flash.comm." + this._id + "._addExternalInterfaceCallback", methodName, this._id);
return true;
}
function call(methodName, resultsCallback) {
// we might have any number of optional arguments, so we have to
// pass them in dynamically; strip out the results callback
var parameters = [];
for(var i = 0; i < arguments.length; i++){
if(i != 1){ // skip the callback
parameters.push(arguments[i]);
}
}
var results = flash.external.ExternalInterface.call.apply(flash.external.ExternalInterface, parameters);
// immediately give the results back, since ExternalInterface is
// synchronous
if(resultsCallback != null && typeof resultsCallback != "undefined"){
resultsCallback.call(null, results);
}
}
/**
Called by Flash to indicate to JavaScript that we are ready to have
our Flash functions called. Calling loaded()
will fire the dojo.flash.loaded() event, so that JavaScript can know that
Flash has finished loading and adding its callbacks, and can begin to
interact with the Flash file.
*/
function loaded(){
DojoExternalInterface.call("dojo.flash.loaded", null, this._id);
LzBrowserKernel.__jsready();
}
function startExec(){
//Debug.write('startExec');
DojoExternalInterface.numArgs = null;
DojoExternalInterface.argData = null;
DojoExternalInterface.resultData = null;
}
function setNumberArguments(numArgs){
//Debug.write('setNumberArguments', numArgs);
DojoExternalInterface.numArgs = numArgs;
DojoExternalInterface.argData = [];
}
function chunkArgumentData(value, argIndex){
//Debug.write('chunkArgumentData', value, argIndex);
//getURL("javascript:dojo.debug('FLASH: chunkArgumentData, value="+value+", argIndex="+argIndex+"')");
var currentValue = DojoExternalInterface.argData[argIndex];
if(currentValue == null || typeof currentValue == "undefined"){
DojoExternalInterface.argData[argIndex] = value;
}else{
DojoExternalInterface.argData[argIndex] += value;
}
}
function exec(methodName){
//Debug.write('exec', methodName);
// decode all of the arguments that were passed in
for(var i = 0; i < DojoExternalInterface.argData.length; i++){
DojoExternalInterface.argData[i] =
DojoExternalInterface.decodeData(DojoExternalInterface.argData[i]);
}
var instance = DojoExternalInterface.flashMethods[methodName];
//Debug.write('instance', instance, instance[methodName]);
DojoExternalInterface.resultData = instance[methodName].apply(
instance, DojoExternalInterface.argData) + '';
//Debug.write('result', DojoExternalInterface.resultData);
// encode the result data
DojoExternalInterface.resultData =
DojoExternalInterface.encodeData(DojoExternalInterface.resultData);
//Debug.write('resultData', DojoExternalInterface.resultData);
//getURL("javascript:dojo.debug('FLASH: encoded result data="+DojoExternalInterface.resultData+"')");
}
function getReturnLength(){
if(DojoExternalInterface.resultData == null ||
typeof DojoExternalInterface.resultData == "undefined"){
return 0;
}
var segments = Math.ceil(DojoExternalInterface.resultData.length / 1024);
//Debug.write('getReturnLength', typeof DojoExternalInterface.resultData, DojoExternalInterface.resultData.length, segments);
return segments;
}
function chunkReturnData(segment){
var numSegments = DojoExternalInterface.getReturnLength();
var startCut = segment * 1024;
var endCut = segment * 1024 + 1024;
if(segment == (numSegments - 1)){
endCut = segment * 1024 + DojoExternalInterface.resultData.length;
}
var piece = DojoExternalInterface.resultData.substring(startCut, endCut);
//getURL("javascript:dojo.debug('FLASH: chunking return piece="+piece+"')");
return piece;
}
function endExec(){
}
function decodeData(data){
// we have to use custom encodings for certain characters when passing
// them over; for example, passing a backslash over as //// from JavaScript
// to Flash doesn't work
data = DojoExternalInterface.replaceStr(data, "&custom_backslash;", "\\");
data = DojoExternalInterface.replaceStr(data, "\\\'", "\'");
data = DojoExternalInterface.replaceStr(data, "\\\"", "\"");
//Debug.write('decodeData', data);
return data;
}
function encodeData(data){
//getURL("javascript:dojo.debug('inside flash, data before="+data+"')");
// double encode all entity values, or they will be mis-decoded
// by Flash when returned
data = DojoExternalInterface.replaceStr(data, "&", "&");
// certain XMLish characters break Flash's wire serialization for
// ExternalInterface; encode these into a custom encoding, rather than
// the standard entity encoding, because otherwise we won't be able to
// differentiate between our own encoding and any entity characters
// that are being used in the string itself
data = DojoExternalInterface.replaceStr(data, '<', '&custom_lt;');
data = DojoExternalInterface.replaceStr(data, '>', '&custom_gt;');
// encode control characters and JavaScript delimiters
data = DojoExternalInterface.replaceStr(data, "\n", "\\n");
data = DojoExternalInterface.replaceStr(data, "\r", "\\r");
data = DojoExternalInterface.replaceStr(data, "\f", "\\f");
data = DojoExternalInterface.replaceStr(data, "'", "\\'");
data = DojoExternalInterface.replaceStr(data, '"', '\"');
//Debug.write('encodeData', data);
//getURL("javascript:dojo.debug('inside flash, data after="+data+"')");
return data;
}
/**
Flash ActionScript has no String.replace method or support for
Regular Expressions! We roll our own very simple one.
*/
function replaceStr(inputStr, replaceThis, withThis){
var splitStr = inputStr.split(replaceThis)
inputStr = splitStr.join(withThis)
return inputStr;
}
function getDojoPath(){
var url = _root._url;
var start = url.indexOf("baseRelativePath=") + "baseRelativePath=".length;
var path = url.substring(start);
var end = path.indexOf("&");
if(end != -1){
path = path.substring(0, end);
}
return path;
}
}
/* X_LZ_COPYRIGHT_BEGIN ***************************************************
* Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. *
* Use is subject to license terms. *
* X_LZ_COPYRIGHT_END ******************************************************/
// vim:ts=4:noet:tw=0:
|
/**
A wrapper around Flash 8's ExternalInterface; DojoExternalInterface is needed so that we
can do a Flash 6 implementation of ExternalInterface, and be able
to support having a single codebase that uses DojoExternalInterface
across Flash versions rather than having two seperate source bases,
where one uses ExternalInterface and the other uses DojoExternalInterface.
DojoExternalInterface class does a variety of optimizations to bypass ExternalInterface's
unbelievably bad performance so that we can have good performance
on Safari; see the blog post
http://codinginparadise.org/weblog/2006/02/how-to-speed-up-flash-8s.html
for details.
@author Brad Neuberg, [email protected]
*/
#include "kernel/swf/dojo/flash8/ExpressInstall.as"
class DojoExternalInterfaceClass {
var available = null;
var flashMethods = [];
var numArgs = null;
var argData = null;
var resultData = null;
var _id;
function DojoExternalInterfaceClass(id){
// extract the dojo base path
//Debug.write('initialize', flash.external.ExternalInterface.addCallback);
// see if we need to do an express install
var install = new ExpressInstall();
if(install.needsUpdate){
install.init();
}
// not loaded from the wrapper JS...
if (id == null) return;
this._id = id;
// register our callback functions
var s = flash.external.ExternalInterface.addCallback("startExec", this, this.startExec);
//Debug.write('addCallback', s, this, this.startExec);
flash.external.ExternalInterface.addCallback("setNumberArguments", this, this.setNumberArguments);
flash.external.ExternalInterface.addCallback("chunkArgumentData", this, this.chunkArgumentData);
flash.external.ExternalInterface.addCallback("exec", this, this.exec);
flash.external.ExternalInterface.addCallback("getReturnLength", this, this.getReturnLength);
flash.external.ExternalInterface.addCallback("chunkReturnData", this, this.chunkReturnData);
flash.external.ExternalInterface.addCallback("endExec", this, this.endExec);
// set whether communication is available
DojoExternalInterface.available = flash.external.ExternalInterface.available;
DojoExternalInterface.call("loaded");
}
function addCallback(methodName, instance, method) {
//Debug.write('addCallback', methodName, instance, method);
// register DojoExternalInterface methodName with it's instance
this.flashMethods[methodName] = instance;
// tell JavaScript about DojoExternalInterface new method so we can create a proxy
//Debug.write('calling dojo.flash.comm.' + this._id + "._addExternalInterfaceCallback", methodName, this._id);
flash.external.ExternalInterface.call("dojo.flash.comm." + this._id + "._addExternalInterfaceCallback", methodName, this._id);
return true;
}
function call(methodName, resultsCallback) {
// we might have any number of optional arguments, so we have to
// pass them in dynamically; strip out the results callback
var parameters = [];
for(var i = 0; i < arguments.length; i++){
if(i != 1){ // skip the callback
parameters.push(arguments[i]);
}
}
var results = flash.external.ExternalInterface.call.apply(flash.external.ExternalInterface, parameters);
// immediately give the results back, since ExternalInterface is
// synchronous
if(resultsCallback != null && typeof resultsCallback != "undefined"){
resultsCallback.call(null, results);
}
}
/**
Called by Flash to indicate to JavaScript that we are ready to have
our Flash functions called. Calling loaded()
will fire the dojo.flash.loaded() event, so that JavaScript can know that
Flash has finished loading and adding its callbacks, and can begin to
interact with the Flash file.
*/
function loaded(){
DojoExternalInterface.call("dojo.flash.loaded", null, this._id);
LzBrowserKernel.__jsready();
}
function startExec(){
//Debug.write('startExec');
DojoExternalInterface.numArgs = null;
DojoExternalInterface.argData = null;
DojoExternalInterface.resultData = null;
}
function setNumberArguments(numArgs){
//Debug.write('setNumberArguments', numArgs);
DojoExternalInterface.numArgs = numArgs;
DojoExternalInterface.argData = [];
}
function chunkArgumentData(value, argIndex){
//Debug.write('chunkArgumentData', value, argIndex);
//getURL("javascript:dojo.debug('FLASH: chunkArgumentData, value="+value+", argIndex="+argIndex+"')");
var currentValue = DojoExternalInterface.argData[argIndex];
if(currentValue == null || typeof currentValue == "undefined"){
DojoExternalInterface.argData[argIndex] = value;
}else{
DojoExternalInterface.argData[argIndex] += value;
}
}
function exec(methodName){
//Debug.write('exec', methodName);
// decode all of the arguments that were passed in
for(var i = 0; i < DojoExternalInterface.argData.length; i++){
DojoExternalInterface.argData[i] =
DojoExternalInterface.decodeData(DojoExternalInterface.argData[i]);
}
var instance = DojoExternalInterface.flashMethods[methodName];
//Debug.write('instance', instance, instance[methodName]);
DojoExternalInterface.resultData = instance[methodName].apply(
instance, DojoExternalInterface.argData) + '';
//Debug.write('result', DojoExternalInterface.resultData);
// encode the result data
DojoExternalInterface.resultData =
DojoExternalInterface.encodeData(DojoExternalInterface.resultData);
//Debug.write('resultData', DojoExternalInterface.resultData);
//getURL("javascript:dojo.debug('FLASH: encoded result data="+DojoExternalInterface.resultData+"')");
}
function getReturnLength(){
if(DojoExternalInterface.resultData == null ||
typeof DojoExternalInterface.resultData == "undefined"){
return 0;
}
var segments = Math.ceil(DojoExternalInterface.resultData.length / 1024);
//Debug.write('getReturnLength', typeof DojoExternalInterface.resultData, DojoExternalInterface.resultData.length, segments);
return segments;
}
function chunkReturnData(segment){
var numSegments = DojoExternalInterface.getReturnLength();
var startCut = segment * 1024;
var endCut = segment * 1024 + 1024;
if(segment == (numSegments - 1)){
endCut = segment * 1024 + DojoExternalInterface.resultData.length;
}
var piece = DojoExternalInterface.resultData.substring(startCut, endCut);
//getURL("javascript:dojo.debug('FLASH: chunking return piece="+piece+"')");
return piece;
}
function endExec(){
}
function decodeData(data){
// we have to use custom encodings for certain characters when passing
// them over; for example, passing a backslash over as //// from JavaScript
// to Flash doesn't work
data = DojoExternalInterface.replaceStr(data, "&custom_backslash;", "\\");
data = DojoExternalInterface.replaceStr(data, "\\\'", "\'");
data = DojoExternalInterface.replaceStr(data, "\\\"", "\"");
//Debug.write('decodeData', data);
return data;
}
function encodeData(data){
//getURL("javascript:dojo.debug('inside flash, data before="+data+"')");
// double encode all entity values, or they will be mis-decoded
// by Flash when returned
data = DojoExternalInterface.replaceStr(data, "&", "&");
// certain XMLish characters break Flash's wire serialization for
// ExternalInterface; encode these into a custom encoding, rather than
// the standard entity encoding, because otherwise we won't be able to
// differentiate between our own encoding and any entity characters
// that are being used in the string itself
data = DojoExternalInterface.replaceStr(data, '<', '&custom_lt;');
data = DojoExternalInterface.replaceStr(data, '>', '&custom_gt;');
// encode control characters and JavaScript delimiters
data = DojoExternalInterface.replaceStr(data, "\n", "\\n");
data = DojoExternalInterface.replaceStr(data, "\r", "\\r");
data = DojoExternalInterface.replaceStr(data, "\f", "\\f");
data = DojoExternalInterface.replaceStr(data, "'", "\\'");
data = DojoExternalInterface.replaceStr(data, '"', '\"');
//Debug.write('encodeData', data);
//getURL("javascript:dojo.debug('inside flash, data after="+data+"')");
return data;
}
/**
Flash ActionScript has no String.replace method or support for
Regular Expressions! We roll our own very simple one.
*/
function replaceStr(inputStr, replaceThis, withThis){
var splitStr = inputStr.split(replaceThis)
inputStr = splitStr.join(withThis)
return inputStr;
}
function getDojoPath(){
var url = _root._url;
var start = url.indexOf("baseRelativePath=") + "baseRelativePath=".length;
var path = url.substring(start);
var end = path.indexOf("&");
if(end != -1){
path = path.substring(0, end);
}
return path;
}
}
/* X_LZ_COPYRIGHT_BEGIN ***************************************************
* Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved. *
* Use is subject to license terms. *
* X_LZ_COPYRIGHT_END ******************************************************/
// vim:ts=4:noet:tw=0:
|
Change 20080521-maxcarlson-m by maxcarlson@Roboto on 2008-05-21 14:39:56 PDT in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20080521-maxcarlson-m by maxcarlson@Roboto on 2008-05-21 14:39:56 PDT
in /Users/maxcarlson/openlaszlo/trunk-clean
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: Don't init flash/js communication when apps are running outside the html wrappers.
New Features:
Bugs Fixed: LPP-5383 - Refresh Or Close Of SWF 8 Solo App In IE7 Causes Javascript 'No Object' Errors
Technical Reviewer: promanik
QA Reviewer: hminsky
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details: Return after running the installer if a null id is passed into the constructor, which happens when there is no id init arg. It's a shame the flash.external.ExternalInterface.available API does nothing to help in this case!
Tests: Compile a non-proxied version of an app, then load it in IE 7 directly Reloading the app should no longer produce Javascript warnings in IE... I used http://192.168.1.119:8080/trunk/my-apps/copy-of-hello.lzx?lzr=swf8&lzproxied=false followed by http://192.168.1.119:8080/trunk/my-apps/copy-of-hello.lzx.lzr%3Dswf8.swf
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@9285 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
9cb51568c37c5ffec45d001c69cae5d3969cfb83
|
plugins/wvPlugin/src/com/kaltura/kdpfl/plugin/WVLoader.as
|
plugins/wvPlugin/src/com/kaltura/kdpfl/plugin/WVLoader.as
|
package com.kaltura.kdpfl.plugin
{
import org.osmf.traits.LoaderBase;
public class WVLoader extends LoaderBase
{
public function WVLoader()
{
super();
}
}
}
|
package com.kaltura.kdpfl.plugin
{
import flash.external.ExternalInterface;
import org.osmf.media.MediaResourceBase;
import org.osmf.traits.LoaderBase;
public class WVLoader extends LoaderBase
{
public function WVLoader()
{
super();
}
override public function canHandleResource(resource:MediaResourceBase):Boolean
{
if (resource.hasOwnProperty("url") && resource["url"].toString().indexOf(".wvm") > -1 )
{
try
{
ExternalInterface.call("mediaURL" , resource["url"].toString());
}
catch(error:Error)
{
trace("Failed to call external interface");
}
return true;
}
return false;
}
}
}
|
Fix a bug that caused "ChangeMedia" to fail
|
Fix a bug that caused "ChangeMedia" to fail
|
ActionScript
|
agpl-3.0
|
kaltura/kdp,shvyrev/kdp,shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp
|
432c5a4a336bbe9adcc8fece955a0787aba9056b
|
src/goplayer/ConfigurationParser.as
|
src/goplayer/ConfigurationParser.as
|
package goplayer
{
public class ConfigurationParser
{
private const result : Configuration = new Configuration
private var parameters : Object
public function ConfigurationParser(parameters : Object)
{ this.parameters = parameters }
public function execute() : void
{
// XXX: Clean up the host stuff.
result.host = parameters.host || "staging.streamio.se"
result.skinURL = parameters.skinUrl
|| "http://" + result.host + "/swfs/goplayer-black-skin.swf"
result.movieID = parameters.movieId
result.trackerID = parameters.trackerId || "global"
result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST)
result.enableRTMP = getBoolean("rtmp", true)
result.enableAutoplay = getBoolean("autoplay", false)
result.enableLooping = getBoolean("loop", false)
result.enableChrome = getBoolean("chrome", true)
result.enableTitleBar = getBoolean("titleBar", true)
}
public static function parse(parameters : Object) : Configuration
{
const parser : ConfigurationParser
= new ConfigurationParser(parameters)
parser.execute()
return parser.result
}
// -----------------------------------------------------
private function getBitratePolicy
(name : String, fallback : BitratePolicy) : BitratePolicy
{
if (name in parameters)
return $getBitratePolicy(name, parameters[name], fallback)
else
return fallback
}
private function $getBitratePolicy
(name : String, value : String,
fallback : BitratePolicy) : BitratePolicy
{
try
{ return $$getBitratePolicy(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, BITRATE_POLICY_VALUES)
return fallback
}
throw new Error
}
private const BITRATE_POLICY_VALUES : Array =
["<number>kbps", "min", "max", "best"]
private function $$getBitratePolicy(value : String) : BitratePolicy
{
if (value == "max")
return BitratePolicy.MAX
else if (value == "min")
return BitratePolicy.MIN
else if (value == "best")
return BitratePolicy.BEST
else if (Bitrate.parse(value))
return BitratePolicy.specific(Bitrate.parse(value))
else
throw new Error
}
// -----------------------------------------------------
private function getBoolean
(name : String, fallback : Boolean) : Boolean
{
if (name in parameters)
return $getBoolean(name, parameters[name], fallback)
else
return fallback
}
private function $getBoolean
(name : String, value : String, fallback : Boolean) : Boolean
{
try
{ return $$getBoolean(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, ["on", "off"])
return fallback
}
throw new Error
}
private function $$getBoolean(value : String) : Boolean
{
if (value == "on")
return true
else if (value == "off")
return false
else
throw new Error
}
// -----------------------------------------------------
private function reportInvalidParameter
(name : String, value : String, validValues : Array) : void
{
debug("Error: Invalid parameter: “" + name + "=" + value + "”; " +
getInvalidParameterHint(validValues) + ".")
}
private function getInvalidParameterHint(values : Array) : String
{ return $getInvalidParameterHint(getQuotedValues(values)) }
private function $getInvalidParameterHint(values : Array) : String
{
return "please use " +
"either " + values.slice(0, -1).join(", ") + " " +
"or " + values[values.length - 1]
}
private function getQuotedValues(values : Array) : Array
{
var result : Array = []
for each (var value : String in values)
result.push("“" + value + "”")
return result
}
}
}
|
package goplayer
{
public class ConfigurationParser
{
private const result : Configuration = new Configuration
private var parameters : Object
public function ConfigurationParser(parameters : Object)
{ this.parameters = parameters }
public function execute() : void
{
// XXX: Clean up the host stuff.
result.host = parameters.host || "staging.streamio.se"
result.skinURL = parameters.skinUrl
|| "http://" + result.host + "/swfs/goplayer-black-skin.swf"
result.movieID = parameters.movieId
result.trackerID = parameters.trackerId || "global"
result.bitratePolicy = getBitratePolicy("bitrate", BitratePolicy.BEST)
result.enableRTMP = getBoolean("rtmp", true)
result.enableAutoplay = getBoolean("autoplay", false)
result.enableLooping = getBoolean("loop", false)
result.enableChrome = getBoolean("chrome", true)
result.enableTitleBar = getBoolean("titleBar", true)
}
public static function parse(parameters : Object) : Configuration
{
const parser : ConfigurationParser
= new ConfigurationParser(parameters)
parser.execute()
return parser.result
}
// -----------------------------------------------------
private function getBitratePolicy
(name : String, fallback : BitratePolicy) : BitratePolicy
{
if (name in parameters)
return $getBitratePolicy(name, parameters[name], fallback)
else
return fallback
}
private function $getBitratePolicy
(name : String, value : String,
fallback : BitratePolicy) : BitratePolicy
{
try
{ return $$getBitratePolicy(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, BITRATE_POLICY_VALUES)
return fallback
}
throw new Error
}
private const BITRATE_POLICY_VALUES : Array =
["<number>kbps", "min", "max", "best"]
private function $$getBitratePolicy(value : String) : BitratePolicy
{
if (value == "max")
return BitratePolicy.MAX
else if (value == "min")
return BitratePolicy.MIN
else if (value == "best")
return BitratePolicy.BEST
else if (Bitrate.parse(value))
return BitratePolicy.specific(Bitrate.parse(value))
else
throw new Error
}
// -----------------------------------------------------
private function getBoolean
(name : String, fallback : Boolean) : Boolean
{
if (name in parameters)
return $getBoolean(name, parameters[name], fallback)
else
return fallback
}
private function $getBoolean
(name : String, value : String, fallback : Boolean) : Boolean
{
try
{ return $$getBoolean(value) }
catch (error : Error)
{
reportInvalidParameter(name, value, ["true", "false"])
return fallback
}
throw new Error
}
private function $$getBoolean(value : String) : Boolean
{
if (value == "true")
return true
else if (value == "false")
return false
else
throw new Error
}
// -----------------------------------------------------
private function reportInvalidParameter
(name : String, value : String, validValues : Array) : void
{
debug("Error: Invalid parameter: “" + name + "=" + value + "”; " +
getInvalidParameterHint(validValues) + ".")
}
private function getInvalidParameterHint(values : Array) : String
{ return $getInvalidParameterHint(getQuotedValues(values)) }
private function $getInvalidParameterHint(values : Array) : String
{
return "please use " +
"either " + values.slice(0, -1).join(", ") + " " +
"or " + values[values.length - 1]
}
private function getQuotedValues(values : Array) : Array
{
var result : Array = []
for each (var value : String in values)
result.push("“" + value + "”")
return result
}
}
}
|
Use ‘true’ and ‘false’ instead of ‘on’ and ‘off’.
|
Use ‘true’ and ‘false’ instead of ‘on’ and ‘off’.
|
ActionScript
|
mit
|
dbrock/goplayer,dbrock/goplayer
|
8b860d2ef18e4a57894152ab60e261f4408f29ed
|
src/aerys/minko/render/shader/compiler/graph/visitors/AbstractVisitor.as
|
src/aerys/minko/render/shader/compiler/graph/visitors/AbstractVisitor.as
|
package aerys.minko.render.shader.compiler.graph.visitors
{
import aerys.minko.render.shader.compiler.graph.ShaderGraph;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Attribute;
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;
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.register.Components;
import flash.utils.Dictionary;
/**
* @private
* @author Romain Gilliotte
*/
public class AbstractVisitor
{
private var _visited : Vector.<AbstractNode>;
protected var _shaderGraph : ShaderGraph;
public function AbstractVisitor()
{
_visited = new Vector.<AbstractNode>();
}
public function process(shaderGraph : ShaderGraph) : void
{
_shaderGraph = shaderGraph;
start();
visit(_shaderGraph.position, true);
visit(_shaderGraph.color, false);
for each (var kill : AbstractNode in _shaderGraph.kills)
visit(kill, false);
finish();
}
protected function start() : void
{
}
protected function finish() : void
{
_visited.length = 0;
_shaderGraph = null;
}
protected function visit(node : AbstractNode, isVertexShader : Boolean) : void
{
if (_visited.indexOf(node) == -1)
{
_visited.push(node);
if (node is Extract || node is Instruction || node is Interpolate || node is Overwriter || node is VariadicExtract)
visitTraversable(node, isVertexShader);
else
visitNonTraversable(node, isVertexShader);
}
}
protected function visitArguments(node : AbstractNode, isVertexShader : Boolean) : void
{
var numArguments : uint = node.numArguments;
for (var argumentId : uint = 0; argumentId < numArguments; ++argumentId)
visit(node.getArgumentAt(argumentId), isVertexShader);
}
protected function replaceInParents(oldNode : AbstractNode, newNode : AbstractNode) : void
{
var numParents : uint = oldNode.numParents;
var parents : Vector.<AbstractNode> = new Vector.<AbstractNode>(numParents, true);
var parentId : uint;
for (parentId = 0; parentId < numParents; ++parentId)
parents[parentId] = oldNode.getParentAt(parentId);
for (parentId = 0; parentId < numParents; ++parentId)
parents[parentId].replaceArgument(oldNode, newNode);
if (_shaderGraph.position === oldNode)
_shaderGraph.position = newNode;
if (_shaderGraph.color === oldNode)
_shaderGraph.color = newNode;
var kills : Vector.<AbstractNode> = _shaderGraph.kills;
var numKills : uint = kills.length;
for (var killId : uint = 0; killId < numKills; ++killId)
if (kills[killId] === oldNode)
kills[killId] = newNode;
}
protected function swizzleParents(node : AbstractNode,
modifier : uint) : void
{
var numParents : uint = node.numParents;
var visitedParents : Dictionary = new Dictionary();
for (var parentId : uint = 0; parentId < numParents; ++parentId)
{
var parent : AbstractNode = node.getParentAt(parentId);
if (visitedParents[parent])
continue;
visitedParents[parent] = true;
var numArgument : uint = parent.numArguments;
// loop backward, because we are removing elements from the parents array
for (var argumentId : int = numArgument - 1; argumentId >= 0; --argumentId)
if (parent.getArgumentAt(argumentId) === node)
parent.setComponentAt(argumentId,
Components.applyCombination(modifier, parent.getComponentAt(argumentId))
);
}
if (_shaderGraph.position == node)
_shaderGraph.positionComponents = Components.applyCombination(modifier, _shaderGraph.positionComponents);
if (_shaderGraph.color == node)
_shaderGraph.colorComponents = Components.applyCombination(modifier, _shaderGraph.colorComponents);
var kills : Vector.<AbstractNode> = _shaderGraph.kills;
var killComponents : Vector.<uint> = _shaderGraph.killComponents;
var numKills : uint = kills.length;
for (var killId : uint = 0; killId < numKills; ++killId)
if (kills[killId] === node)
killComponents[killId] = Components.applyCombination(modifier, killComponents[killId]);
}
protected function replaceInParentsAndSwizzle(oldNode : AbstractNode,
newNode : AbstractNode,
modifier : uint) : void
{
swizzleParents(oldNode, modifier);
replaceInParents(oldNode, newNode);
}
protected function visitTraversable(node : AbstractNode, isVertexShader : Boolean) : void
{
if (node is Extract)
visitExtract(Extract(node), isVertexShader);
else if (node is Instruction)
visitInstruction(Instruction(node), isVertexShader);
else if (node is Interpolate)
visitInterpolate(Interpolate(node), isVertexShader);
else if (node is Overwriter)
visitOverwriter(Overwriter(node), isVertexShader);
else if (node is VariadicExtract)
visitVariadicExtract(VariadicExtract(node), isVertexShader);
}
protected function visitNonTraversable(node : AbstractNode, isVertexShader : Boolean) : void
{
if (node is Attribute)
visitAttribute(Attribute(node), isVertexShader);
else if (node is Constant)
visitConstant(Constant(node), isVertexShader);
else if (node is BindableConstant)
visitBindableConstant(BindableConstant(node), isVertexShader);
else if (node is Sampler)
visitSampler(Sampler(node), isVertexShader);
else if (node is BindableSampler)
visitBindableSampler(BindableSampler(node), isVertexShader);
}
protected function visitAttribute(attribute : Attribute,
isVertexShader : Boolean) : void
{
}
protected function visitConstant(constant : Constant,
isVertexShader : Boolean) : void
{
}
protected function visitBindableConstant(bindableConstant : BindableConstant,
isVertexShader : Boolean) : void
{
}
protected function visitSampler(sampler : Sampler,
isVertexShader : Boolean) : void
{
}
protected function visitBindableSampler(bindableSampler : BindableSampler,
isVertexShader : Boolean) : void
{
}
protected function visitExtract(extract : Extract,
isVertexShader : Boolean) : void
{
}
protected function visitInstruction(instruction : Instruction,
isVertexShader : Boolean) : void
{
}
protected function visitInterpolate(interpolate : Interpolate,
isVertexShader : Boolean) : void
{
}
protected function visitOverwriter(overwriter : Overwriter,
isVertexShader : Boolean) : void
{
}
protected function visitVariadicExtract(variadicExtract : VariadicExtract,
isVertexShader : Boolean) : void
{
}
}
}
|
package aerys.minko.render.shader.compiler.graph.visitors
{
import aerys.minko.render.shader.compiler.graph.ShaderGraph;
import aerys.minko.render.shader.compiler.graph.nodes.AbstractNode;
import aerys.minko.render.shader.compiler.graph.nodes.leaf.Attribute;
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;
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.register.Components;
import flash.utils.Dictionary;
/**
* @private
* @author Romain Gilliotte
*/
public class AbstractVisitor
{
private var _visited : Vector.<AbstractNode>;
protected var _shaderGraph : ShaderGraph;
public function AbstractVisitor()
{
_visited = new Vector.<AbstractNode>();
}
public function process(shaderGraph : ShaderGraph) : void
{
_shaderGraph = shaderGraph;
start();
visit(_shaderGraph.position, true);
visit(_shaderGraph.color, false);
for each (var kill : AbstractNode in _shaderGraph.kills)
visit(kill, false);
finish();
}
protected function start() : void
{
}
protected function finish() : void
{
_visited.length = 0;
_shaderGraph = null;
}
protected function visit(node : AbstractNode, isVertexShader : Boolean) : void
{
if (_visited.indexOf(node) == -1)
{
_visited.push(node);
if (node is Extract || node is Instruction || node is Interpolate || node is Overwriter || node is VariadicExtract)
visitTraversable(node, isVertexShader);
else
visitNonTraversable(node, isVertexShader);
}
}
protected function visitArguments(node : AbstractNode, isVertexShader : Boolean) : void
{
var numArguments : uint = node.numArguments;
for (var argumentId : uint = 0; argumentId < numArguments; ++argumentId)
visit(node.getArgumentAt(argumentId), isVertexShader);
}
protected function replaceInParents(oldNode : AbstractNode, newNode : AbstractNode) : void
{
var numParents : uint = oldNode.numParents;
var parents : Vector.<AbstractNode> = new Vector.<AbstractNode>(numParents, true);
var parentId : uint;
for (parentId = 0; parentId < numParents; ++parentId)
parents[parentId] = oldNode.getParentAt(parentId);
for (parentId = 0; parentId < numParents; ++parentId)
parents[parentId].replaceArgument(oldNode, newNode);
if (_shaderGraph.position === oldNode)
_shaderGraph.position = newNode;
if (_shaderGraph.color === oldNode)
_shaderGraph.color = newNode;
var kills : Vector.<AbstractNode> = _shaderGraph.kills;
var numKills : uint = kills.length;
for (var killId : uint = 0; killId < numKills; ++killId)
if (kills[killId] === oldNode)
kills[killId] = newNode;
}
protected function swizzleParents(node : AbstractNode,
modifier : uint) : void
{
var numParents : uint = node.numParents;
var visitedParents : Dictionary = new Dictionary();
for (var parentId : uint = 0; parentId < numParents; ++parentId)
{
var parent : AbstractNode = node.getParentAt(parentId);
if (visitedParents[parent])
continue;
visitedParents[parent] = true;
var numArgument : uint = parent.numArguments;
// loop backward, because we are removing elements from the parents array
for (var argumentId : int = numArgument - 1; argumentId >= 0; --argumentId)
if (parent.getArgumentAt(argumentId) === node)
parent.setComponentAt(argumentId,
Components.applyCombination(modifier, parent.getComponentAt(argumentId))
);
}
if (_shaderGraph.position == node)
_shaderGraph.positionComponents = Components.applyCombination(modifier, _shaderGraph.positionComponents);
if (_shaderGraph.color == node)
_shaderGraph.colorComponents = Components.applyCombination(modifier, _shaderGraph.colorComponents);
var kills : Vector.<AbstractNode> = _shaderGraph.kills;
var killComponents : Vector.<uint> = _shaderGraph.killComponents;
var numKills : uint = kills.length;
for (var killId : uint = 0; killId < numKills; ++killId)
if (kills[killId] === node)
killComponents[killId] = Components.applyCombination(modifier, killComponents[killId]);
}
protected function replaceInParentsAndSwizzle(oldNode : AbstractNode,
newNode : AbstractNode,
modifier : uint) : void
{
swizzleParents(oldNode, modifier);
replaceInParents(oldNode, newNode);
}
protected function visitTraversable(node : AbstractNode, isVertexShader : Boolean) : void
{
if (node is Extract)
visitExtract(Extract(node), isVertexShader);
else if (node is Instruction)
visitInstruction(Instruction(node), isVertexShader);
else if (node is Interpolate)
visitInterpolate(Interpolate(node), isVertexShader);
else if (node is Overwriter)
visitOverwriter(Overwriter(node), isVertexShader);
else if (node is VariadicExtract)
visitVariadicExtract(VariadicExtract(node), isVertexShader);
}
protected function visitNonTraversable(node : AbstractNode, isVertexShader : Boolean) : void
{
if (node is Attribute)
visitAttribute(Attribute(node), isVertexShader);
else if (node is Constant)
visitConstant(Constant(node), isVertexShader);
else if (node is BindableConstant)
visitBindableConstant(BindableConstant(node), isVertexShader);
else if (node is Sampler)
visitSampler(Sampler(node), isVertexShader);
else if (node is BindableSampler)
visitBindableSampler(BindableSampler(node), isVertexShader);
}
protected function visitAttribute(attribute : Attribute,
isVertexShader : Boolean) : void
{
}
protected function visitConstant(constant : Constant,
isVertexShader : Boolean) : void
{
}
protected function visitBindableConstant(bindableConstant : BindableConstant,
isVertexShader : Boolean) : void
{
}
protected function visitSampler(sampler : Sampler,
isVertexShader : Boolean) : void
{
}
protected function visitBindableSampler(bindableSampler : BindableSampler,
isVertexShader : Boolean) : void
{
}
protected function visitExtract(extract : Extract,
isVertexShader : Boolean) : void
{
}
protected function visitInstruction(instruction : Instruction,
isVertexShader : Boolean) : void
{
}
protected function visitInterpolate(interpolate : Interpolate,
isVertexShader : Boolean) : void
{
}
protected function visitOverwriter(overwriter : Overwriter,
isVertexShader : Boolean) : void
{
}
protected function visitVariadicExtract(variadicExtract : VariadicExtract,
isVertexShader : Boolean) : void
{
}
}
}
|
fix coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
219f32e3f837dc4a4baf65bd58c2ab00318be67d
|
src/aerys/minko/scene/controller/mesh/DynamicTextureController.as
|
src/aerys/minko/scene/controller/mesh/DynamicTextureController.as
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.render.Viewport;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.scene.controller.EnterFrameController;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataProvider;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.geom.Matrix;
import flash.geom.Rectangle;
/**
* The DynamicTextureController makes it possible to use Flash DisplayObjects
* as dynamic textures.
*
* <p>
* The DynamicTextureController listen for the Scene.enterFrame signal and
* update the specified texture property of the targeted Meshes by rasterizing
* the source Flash DisplayObject.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public final class DynamicTextureController extends EnterFrameController
{
private var _data : DataProvider;
private var _source : DisplayObject;
private var _framerate : Number;
private var _mipMapping : Boolean;
private var _propertyName : String;
private var _matrix : Matrix;
private var _forceBitmapDataClear : Boolean;
private var _bitmapData : BitmapData;
private var _texture : TextureResource;
private var _lastDraw : Number;
/**
* Create a new DynamicTextureController.
*
* @param source The source DisplayObject to use as a dynamic texture.
* @param width The width of the dynamic texture.
* @param height The height of the dynamic texture.
* @param mipMapping Whether mip-mapping should be enabled or not. Default value is 'true'.
* @param framerate The frame rate of the dynamic texture. Default value is '30'.
* @param propertyName The name of the bindings property that should be set with the
* dynamic texture. Default value if 'diffuseMap'.
* @param matrix The Matrix object that shall be used when rasterizing the DisplayObject
* into the dynamic texture. Default value is 'null'.
*
*/
public function DynamicTextureController(source : DisplayObject,
width : Number,
height : Number,
mipMapping : Boolean = true,
framerate : Number = 30.,
propertyName : String = 'diffuseMap',
matrix : Matrix = null,
forceBitmapDataClear : Boolean = false)
{
super();
_source = source;
_texture = new TextureResource(width, height);
_framerate = framerate;
_mipMapping = mipMapping;
_propertyName = propertyName;
_matrix = matrix;
_forceBitmapDataClear = forceBitmapDataClear;
_data = new DataProvider();
_data.setProperty(propertyName, _texture);
}
public function get forceBitmapDataClear():Boolean
{
return _forceBitmapDataClear;
}
public function set forceBitmapDataClear(value:Boolean):void
{
_forceBitmapDataClear = value;
}
override protected function targetAddedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
super.targetAddedHandler(ctrl, target);
if (target is Scene)
(target as Scene).bindings.addProvider(_data);
else if (target is Mesh)
(target as Mesh).bindings.addProvider(_data);
else
throw new Error();
}
override protected function targetRemovedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
super.targetRemovedHandler(ctrl, target);
if (target is Scene)
(target as Scene).bindings.removeProvider(_data);
else if (target is Mesh)
(target as Mesh).bindings.removeProvider(_data);
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
target : BitmapData,
time : Number) : void
{
if (!_lastDraw || time - _lastDraw > 1000. / _framerate)
{
_lastDraw = time;
_bitmapData ||= new BitmapData(_source.width, _source.height);
if (_forceBitmapDataClear)
_bitmapData.fillRect(
new Rectangle(0, 0, _bitmapData.width, _bitmapData.height),
0
);
_bitmapData.draw(_source, _matrix);
_texture.setContentFromBitmapData(_bitmapData, _mipMapping);
}
}
}
}
|
package aerys.minko.scene.controller.mesh
{
import aerys.minko.render.Viewport;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.scene.controller.EnterFrameController;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.DataProvider;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.geom.Matrix;
import flash.geom.Rectangle;
/**
* The DynamicTextureController makes it possible to use Flash DisplayObjects
* as dynamic textures.
*
* <p>
* The DynamicTextureController listen for the Scene.enterFrame signal and
* update the specified texture property of the targeted Meshes by rasterizing
* the source Flash DisplayObject.
* </p>
*
* @author Jean-Marc Le Roux
*
*/
public final class DynamicTextureController extends EnterFrameController
{
private var _data : DataProvider;
private var _source : Object;
private var _framerate : Number;
private var _mipMapping : Boolean;
private var _propertyName : String;
private var _matrix : Matrix;
private var _forceBitmapDataClear : Boolean;
private var _tmpBitmapData : BitmapData;
private var _texture : TextureResource;
private var _lastDraw : Number;
/**
* Create a new DynamicTextureController.
*
* @param source The source (BitmapData or DisplayObject) to use as a dynamic texture.
* @param mipMapping Whether mip-mapping should be enabled or not. Default value is 'true'.
* @param framerate The frame rate of the dynamic texture. Default value is '30'.
* @param propertyName The name of the bindings property that should be set with the
* dynamic texture. Default value if 'diffuseMap'.
* @param matrix The Matrix object that shall be used when rasterizing the DisplayObject
* into the dynamic texture. Default value is 'null'.
*
*/
public function DynamicTextureController(source : Object,
mipMapping : Boolean = true,
framerate : Number = 30.,
propertyName : String = 'diffuseMap',
matrix : Matrix = null,
forceBitmapDataClear : Boolean = false)
{
super();
if (!(source is DisplayObject) && !(source is BitmapData))
throw new Error("Invalid argument: source must be of type DisplayObject or BitmapData.");
_source = source;
_texture = new TextureResource();
_framerate = framerate;
_mipMapping = mipMapping;
_propertyName = propertyName;
_matrix = matrix;
_forceBitmapDataClear = forceBitmapDataClear;
_data = new DataProvider();
_data.setProperty(propertyName, _texture);
}
public function get forceBitmapDataClear():Boolean
{
return _forceBitmapDataClear;
}
public function set forceBitmapDataClear(value:Boolean):void
{
_forceBitmapDataClear = value;
}
override protected function targetAddedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
super.targetAddedHandler(ctrl, target);
if (target is Scene)
(target as Scene).bindings.addProvider(_data);
else if (target is Mesh)
(target as Mesh).bindings.addProvider(_data);
else
throw new Error();
}
override protected function targetRemovedHandler(ctrl : EnterFrameController,
target : ISceneNode) : void
{
super.targetRemovedHandler(ctrl, target);
if (target is Scene)
(target as Scene).bindings.removeProvider(_data);
else if (target is Mesh)
(target as Mesh).bindings.removeProvider(_data);
}
override protected function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
target : BitmapData,
time : Number) : void
{
if (!_lastDraw || time - _lastDraw > 1000. / _framerate)
{
_lastDraw = time;
if (_source is DisplayObject)
updateFromDisplayObject();
else
updateFromBitmapData();
}
}
private function updateFromDisplayObject() : void
{
var sourceDisplayObject : DisplayObject = _source as DisplayObject;
refreshTempBitmapData();
_tmpBitmapData.draw(sourceDisplayObject, _matrix);
_texture.setContentFromBitmapData(_tmpBitmapData, _mipMapping);
}
private function updateFromBitmapData() : void
{
if (_matrix)
{
refreshTempBitmapData();
_tmpBitmapData.draw(_source as BitmapData, _matrix);
_texture.setContentFromBitmapData(_tmpBitmapData, _mipMapping);
}
_texture.setContentFromBitmapData(_source as BitmapData, _mipMapping);
}
private function refreshTempBitmapData() : void
{
if (!_tmpBitmapData)
_tmpBitmapData = new BitmapData(_source.width, _source.height);
else if (_forceBitmapDataClear)
_tmpBitmapData.fillRect(
new Rectangle(0, 0, _tmpBitmapData.width, _tmpBitmapData.height),
0
);
}
}
}
|
add support for BitmapData as a source for DynamicTextureController
|
add support for BitmapData as a source for DynamicTextureController
|
ActionScript
|
mit
|
aerys/minko-as3
|
e9814af2d20b61b2527b92b5bcde0055884d10d5
|
MQTTClient_AS3/src/MQTTClient_AS3.as
|
MQTTClient_AS3/src/MQTTClient_AS3.as
|
/**
* GODPAPER Confidential,Copyright 2012. All rights reserved.
*
* 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, sub-license,
* 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
{
//--------------------------------------------------------------------------
//
// Imports
//
//--------------------------------------------------------------------------
import com.godpaper.as3.configs.LoggerConfig;
import com.godpaper.as3.utils.LogUtil;
import com.godpaper.mqtt.as3.core.MQTTEvent;
import com.godpaper.mqtt.as3.impl.MQTTSocket;
import com.godpaper.mqtt.as3.utils.UIDUtil;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.system.Security;
import flash.utils.ByteArray;
import flash.utils.Endian;
import mx.logging.ILogger;
import mx.logging.LogEventLevel;
/**
* Pure Action Script 3 that implements the MQTT (Message Queue Telemetry Transport) protocol, a lightweight protocol for publish/subscribe messaging. </br>
* AS3 socket is a mechanism used to send data over a network (e.g. the Internet), it is the combination of an IP address and a port. </br>
* @see https://github.com/yangboz/as3MQTT
* @see https://github.com/yangboz/as3MQTT/wiki
* @see https://github.com/yangboz/as3Logger
*
* @author yangboz
* @langVersion 3.0
* @playerVersion 11.2+
* @airVersion 3.2+
* Created Nov 20, 2012 10:19:53 AM
*/
public class MQTTClient_AS3 extends Sprite
{
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
private var mqttSocket:MQTTSocket;
//----------------------------------
// CONSTANTS
//----------------------------------
//Notice: You need to define a cross domain policy file at your remote server root document, or have a policy file server on the target.
private static const MY_HOST:String="16.157.65.23"; //You'd better change it to your private ip address! //test.mosquitto.org//16.157.65.23(Ubuntu)//15.185.106.72(hp cs instance)
private static const MY_PORT:Number=1883; //Socket port.
//as3Logger
// LoggerConfig.filters = ["MQTTClient_AS3"];
LoggerConfig.filters = ["com.godpaper.mqtt.as3.impl.*"];
LoggerConfig.level = LogEventLevel.DEBUG;
private static const LOG:ILogger = LogUtil.getLogger(MQTTClient_AS3);
//--------------------------------------------------------------------------
//
// Public properties
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Protected properties
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
public function MQTTClient_AS3()
{
// Creating a Socket
this.mqttSocket=new MQTTSocket(MY_HOST, MY_PORT);
//Notice: You need to define a cross domain policy file at your remote server root document, or have a policy file server on the target.
Security.allowDomain("*");
// Security.loadPolicyFile("http://www.lookbackon.com/crossdomain.xml");
//event listeners
mqttSocket.addEventListener(MQTTEvent.CONNECT, onConnect); //dispatched when the connection is established
mqttSocket.addEventListener(MQTTEvent.CLOSE, onClose); //dispatched when the connection is closed
mqttSocket.addEventListener(MQTTEvent.ERROR, onError); //dispatched when an error occurs
mqttSocket.addEventListener(MQTTEvent.MESSGE, onMessage); //dispatched when socket can be read
//try to connect
mqttSocket.connect();
}
//--------------------------------------------------------------------------
//
// Public methods
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Protected methods
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Private methods
//
//--------------------------------------------------------------------------
//
private function onConnect(event:MQTTEvent):void
{
LOG.info("MQTT connect: {0}",event.message);
}
//
private function onClose(event:MQTTEvent):void
{
LOG.info("MQTT close: {0}",event.message);
}
//
private function onError(event:MQTTEvent):void
{
LOG.info("MQTT Error: {0}",event.message);
}
//
private function onMessage(event:MQTTEvent):void
{
LOG.info("MQTT message: {0}",event.message);
}
}
}
|
/**
* GODPAPER Confidential,Copyright 2012. All rights reserved.
*
* 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, sub-license,
* 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
{
//--------------------------------------------------------------------------
//
// Imports
//
//--------------------------------------------------------------------------
import com.godpaper.as3.configs.LoggerConfig;
import com.godpaper.as3.utils.LogUtil;
import com.godpaper.mqtt.as3.core.MQTTEvent;
import com.godpaper.mqtt.as3.impl.MQTTSocket;
import flash.display.Sprite;
import flash.system.Security;
import mx.logging.ILogger;
import mx.logging.LogEventLevel;
/**
* Pure Action Script 3 that implements the MQTT (Message Queue Telemetry Transport) protocol, a lightweight protocol for publish/subscribe messaging. </br>
* AS3 socket is a mechanism used to send data over a network (e.g. the Internet), it is the combination of an IP address and a port. </br>
* @see https://github.com/yangboz/as3MQTT
* @see https://github.com/yangboz/as3MQTT/wiki
* @see https://github.com/yangboz/as3Logger
*
* @author yangboz
* @langVersion 3.0
* @playerVersion 11.2+
* @airVersion 3.2+
* Created Nov 20, 2012 10:19:53 AM
*/
public class MQTTClient_AS3 extends Sprite
{
//--------------------------------------------------------------------------
//
// Variables
//
//--------------------------------------------------------------------------
private var mqttSocket:MQTTSocket;
//----------------------------------
// CONSTANTS
//----------------------------------
//Notice: You need to define a cross domain policy file at your remote server root document, or have a policy file server on the target.
private static const MY_HOST:String="test.mosquitto.org"; //You'd better change it to your private ip address! //test.mosquitto.org//16.157.65.23(Ubuntu)//15.185.106.72(hp cs instance)
private static const MY_PORT:Number=1883; //Socket port.
//as3Logger
// LoggerConfig.filters = ["MQTTClient_AS3"];
LoggerConfig.filters = ["com.godpaper.mqtt.as3.impl.*"];
LoggerConfig.level = LogEventLevel.DEBUG;
private static const LOG:ILogger = LogUtil.getLogger(MQTTClient_AS3);
//--------------------------------------------------------------------------
//
// Public properties
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Protected properties
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
public function MQTTClient_AS3()
{
// Creating a Socket
this.mqttSocket=new MQTTSocket(MY_HOST, MY_PORT);
//Notice: You need to define a cross domain policy file at your remote server root document, or have a policy file server on the target.
Security.allowDomain("*");
// Security.loadPolicyFile("http://www.lookbackon.com/crossdomain.xml");
//event listeners
mqttSocket.addEventListener(MQTTEvent.CONNECT, onConnect); //dispatched when the connection is established
mqttSocket.addEventListener(MQTTEvent.CLOSE, onClose); //dispatched when the connection is closed
mqttSocket.addEventListener(MQTTEvent.ERROR, onError); //dispatched when an error occurs
mqttSocket.addEventListener(MQTTEvent.MESSGE, onMessage); //dispatched when socket can be read
//try to connect
mqttSocket.connect();
}
//--------------------------------------------------------------------------
//
// Public methods
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Protected methods
//
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//
// Private methods
//
//--------------------------------------------------------------------------
//
private function onConnect(event:MQTTEvent):void
{
LOG.info("MQTT connect: {0}",event.message);
}
//
private function onClose(event:MQTTEvent):void
{
LOG.info("MQTT close: {0}",event.message);
}
//
private function onError(event:MQTTEvent):void
{
LOG.info("MQTT Error: {0}",event.message);
}
//
private function onMessage(event:MQTTEvent):void
{
LOG.info("MQTT message: {0}",event.message);
}
}
}
|
remove useless import
|
remove useless import
|
ActionScript
|
mit
|
yangboz/as3MQTT,yangboz/as3MQTT
|
ab2fe2bc842b48162a3dc5b6cf4e813f142e8573
|
src/aerys/minko/scene/controller/AnimationController.as
|
src/aerys/minko/scene/controller/AnimationController.as
|
package 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.TimeLabel;
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
{
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 _labels : Vector.<TimeLabel>;
private var _lastTime : Number;
private var _looped : Signal;
private var _started : Signal;
private var _stopped : Signal;
public function get timeFunction() : Function
{
return _timeFunction;
}
public function set timeFunction(value : Function) : void
{
_timeFunction = value;
}
public function get labels() : Vector.<TimeLabel>
{
return _labels;
}
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;
_labels = new <TimeLabel>[];
_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) : AnimationController
{
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() : AnimationController
{
_isPlaying = true;
_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
_started.execute(this);
return this;
}
public function stop() : AnimationController
{
_isPlaying = false;
_updateOneTime = true;
_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
_stopped.execute(this);
return this;
}
public function setPlaybackWindow(beginTime : Object = null,
endTime : Object = null) : AnimationController
{
_loopBeginTime = beginTime != null ? getAnimationTime(beginTime) : 0;
_loopEndTime = endTime != null ? getAnimationTime(endTime) : _totalTime;
if (_currentTime < _loopBeginTime || _currentTime > _loopEndTime)
_currentTime = _loopBeginTime;
return this;
}
public function resetPlaybackWindow() : AnimationController
{
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 = _labels.length;
for (var labelId : uint = 0; labelId < labelCount; ++labelId)
if (_labels[labelId].name == time)
timeValue = _labels[labelId].time;
}
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);
var numTimelines : int = _timelines.length;
var group : Group = target as Group;
if (ctrlTarget.root != scene)
continue ;
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;
}
}
}
|
package 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.TimeLabel;
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
{
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 _labels : Vector.<TimeLabel>;
private var _lastTime : Number;
private var _looped : Signal;
private var _started : Signal;
private var _stopped : Signal;
public function get timeFunction() : Function
{
return _timeFunction;
}
public function set timeFunction(value : Function) : void
{
_timeFunction = value;
}
public function get labels() : Vector.<TimeLabel>
{
return _labels;
}
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;
_labels = new <TimeLabel>[];
_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) : AnimationController
{
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() : AnimationController
{
_isPlaying = true;
_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
_started.execute(this);
return this;
}
public function stop() : AnimationController
{
_isPlaying = false;
_updateOneTime = true;
_lastTime = _timeFunction != null ? _timeFunction(getTimer()) : getTimer();
_stopped.execute(this);
return this;
}
public function setPlaybackWindow(beginTime : Object = null,
endTime : Object = null) : AnimationController
{
_loopBeginTime = beginTime != null ? getAnimationTime(beginTime) : 0;
_loopEndTime = endTime != null ? getAnimationTime(endTime) : _totalTime;
if (_currentTime < _loopBeginTime || _currentTime > _loopEndTime)
_currentTime = _loopBeginTime;
return this;
}
public function resetPlaybackWindow() : AnimationController
{
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 = _labels.length;
for (var labelId : uint = 0; labelId < labelCount; ++labelId)
if (_labels[labelId].name == time)
timeValue = _labels[labelId].time;
}
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);
var numTimelines : int = _timelines.length;
var group : Group = target as Group;
if (ctrlTarget.root != scene)
continue ;
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;
}
}
}
|
fix coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
dbedc8ad0b34d98a04b10be4c015599b78376724
|
software/sasFlex/src/gov/nih/nci/cbiit/casas/components/FormulaEditor.as
|
software/sasFlex/src/gov/nih/nci/cbiit/casas/components/FormulaEditor.as
|
package gov.nih.nci.cbiit.casas.components
{
import learnmath.mathml.components.MathMLEditor;
import mx.core.IUIComponent;
public class FormulaEditor extends MathMLEditor
{
public function FormulaEditor()
{
// this.setConfiguration("disableOpen", "false");
//decompile MathMLEditor
//decompile EditorApp to enable Save/Open functionalities
super();
// super.mainPannel.name= "<a href=\'http://ncicb.nci.nih.gov/\'>what NCI Center for Biomedical Informatics & Information Technology - Scientific Algorithm Service</a>";
}
}
}
|
package gov.nih.nci.cbiit.casas.components
{
import fl.core.UIComponent;
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.utils.Timer;
import learnmath.mathml.components.MathMLEditor;
import learnmath.mathml.formula.Constants;
import learnmath.windows.ConfigManager;
import mx.controls.Alert;
import mx.core.IUIComponent;
import flash.events.TimerEvent;
public class FormulaEditor extends MathMLEditor
{
public function FormulaEditor()
{
//duplicate MathMLEditor Constructor
ConfigManager.urlFonts="./";
Constants.setUrlFonts("./");
// ConfigManager.setConfig("disableSave","false");
// ConfigManager.setConfig("disableOpen","false");
ConfigManager.disableOpen=new Boolean(false);
ConfigManager.disableSave=new Boolean(false);
addEventListener(KeyboardEvent.KEY_DOWN, processKey);
// mainPannel.name= "<a href=\'http://ncicb.nci.nih.gov/\'>NCI Center for Biomedical Informatics & Information Technology - Scientific Algorithm Service</a>";
// mainPannel.draw();
return;
}
// override protected function createChildren():void
// {
// Alert.show("before created by super", mainPannel+"");
// super.createChildren();
// Alert.show("created by super", mainPannel+"");
// mainPannel=null;
// while (this.numChildren>0)
// {
// this.removeChildAt(0);
// }
// var _loc_1:*=new MovieClip();
// var editorW:Number=800;
// var editorH:Number=500;
//
// mainPannel = new FormulaPanel(_loc_1, 0,0,editorW, editorH, returnFocus);
// mainPannel.draw();
// mainPannel.setMathML("..xx");
// Alert.show(mainPannel+"", mainPannel.getMathML());
// var _loc_2:*=new UIComponent();
// addChild(_loc_2);
//
// var _loc_3:*=new Timer(100,1);
// _loc_3.addEventListenr(TimerEvent.TIMER, redrawEditor);
// _loc_3.start();
// return;
// }
//override private method
private function redrawEditor(event:TimerEvent):void
{
mainPannel.draw();
if (focusManager!=null)
{
focusManager.setFocus(this);
}
return;
}
}
}
|
clean version using FMathML FormulaEditor
|
clean version using FMathML FormulaEditor
SVN-Revision: 3125
|
ActionScript
|
bsd-3-clause
|
NCIP/caadapter,NCIP/caadapter,NCIP/caadapter
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.