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
|
---|---|---|---|---|---|---|---|---|---|
bbc2bc1551ed5b7f97ed91b623867c7f2048a479
|
src/main/actionscript/com/dotfold/dotvimstat/view/summary/LikesSummary.as
|
src/main/actionscript/com/dotfold/dotvimstat/view/summary/LikesSummary.as
|
package com.dotfold.dotvimstat.view.summary
{
import com.dotfold.dotvimstat.view.IView;
import flash.display.Graphics;
import flash.display.Shape;
import modena.core.Element;
import modena.core.ElementContent;
import modena.ui.Stack;
/**
*
* @author jamesmcnamee
*
*/
public class LikesSummary extends Stack implements IView
{
public static const ELEMENT_NAME:String = "likesSummary";
/**
* Constructor.
*/
public function LikesSummary(styleClass:String = null)
{
super(styleClass);
}
override protected function createElementContent():ElementContent
{
var content:ElementContent = super.createElementContent();
return content;
}
override public function validateRender():void
{
super.validateRender();
}
}
}
|
package com.dotfold.dotvimstat.view.summary
{
import com.dotfold.dotvimstat.view.IView;
import flash.display.Graphics;
import flash.display.Shape;
import modena.core.Element;
import modena.core.ElementContent;
import modena.ui.Label;
import modena.ui.Stack;
/**
*
* @author jamesmcnamee
*
*/
public class LikesSummary extends Stack implements IView
{
public static const ELEMENT_NAME:String = "likesSummary";
private var _label:Label;
/**
* Constructor.
*/
public function LikesSummary(styleClass:String = null)
{
super(styleClass);
}
override protected function createElementContent():ElementContent
{
var content:ElementContent = super.createElementContent();
_label = new Label("summaryCount");
content.addChild(_label)
return content;
}
/**
*
*/
public function set likesCount(value:int):void
{
_label.text = value.toString();
invalidateRender();
}
override public function validateRender():void
{
super.validateRender();
_label.x = (width - _label.width) / 2;
_label.y = (height - _label.height) / 2;
}
}
}
|
add label to likes summary
|
[feat] add label to likes summary
|
ActionScript
|
mit
|
dotfold/dotvimstat
|
2952d288fdb55f45a2455c95ef3c4698f648f6e0
|
src/as/com/threerings/flex/CommandMenu.as
|
src/as/com/threerings/flex/CommandMenu.as
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flex {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.geom.Point;
import flash.geom.Rectangle;
import mx.controls.Menu;
import mx.controls.listClasses.BaseListData;
import mx.controls.listClasses.IListItemRenderer;
import mx.controls.menuClasses.IMenuItemRenderer;
import mx.controls.menuClasses.MenuListData;
import mx.core.mx_internal;
import mx.core.Application;
import mx.core.ClassFactory;
import mx.core.IFlexDisplayObject;
import mx.core.ScrollPolicy;
import mx.events.MenuEvent;
import mx.managers.PopUpManager;
import com.threerings.util.CommandEvent;
import com.threerings.flex.PopUpUtil;
import com.threerings.flex.menuClasses.CommandMenuItemRenderer;
import com.threerings.flex.menuClasses.CommandListData;
use namespace mx_internal;
/**
* A pretty standard menu that can submit CommandEvents if menu items have "command" and possibly
* "arg" properties. Commands are submitted to controllers for processing. Alternatively, you may
* specify "callback" properties that specify a function closure to call, with the "arg" property
* containing either a single arg or an array of args.
*
* Another property now supported is "iconObject", which is an already-instantiated
* IFlexDisplayObject to use as the icon. This will only be applied if the "icon" property
* (which specifies a Class) is not used.
*
* Example dataProvider array:
* [ { label: "Go home", icon: homeIconClass,
* command: Controller.GO_HOME, arg: homeId },
* { type: "separator"},
{ label: "Crazytown", callback: setCrazy, arg: [ true, false ] },
* { label: "Other places", children: subMenuArray }
* ];
*
* See "Defining menu structure and data" in the Flex manual for the full list.
*
* CommandMenu is scrollable. This can be forced by setting verticalScrollPolicy to
* ScrollPolicy.AUTO or ScrollPolicy.ON and setting the maxHeight. Also, if the scrolling isn't
* forced on, but the menu does not fit within the vertical bounds given (either the stage size by
* default, or the height of the rectangle given in setBounds()), scrolling will be turned on
* so that none of the content is lost.
*
* Note: we don't extend flexlib's ScrollableMenu (or its sub-class ScrollableArrowMenu) because it
* does some weird stuff in measure() that forces some of our menus down to a very small height...
*/
public class CommandMenu extends Menu
{
/**
* Factory method to create a command menu.
*
* @param items an array of menu items.
* @param dispatcher an override event dispatcher to use for command events, rather than
* our parent.
*/
public static function createMenu (
items :Array, dispatcher :IEventDispatcher = null) :CommandMenu
{
var menu :CommandMenu = new CommandMenu();
menu.owner = DisplayObjectContainer(Application.application);
menu.tabEnabled = false;
menu.showRoot = true;
menu.setDispatcher(dispatcher);
Menu.popUpMenu(menu, null, items); // does not actually pop up, but needed.
return menu;
}
/**
* The mx.controls.Menu class overrides setting and getting the verticalScrollPolicy
* basically setting the verticalScrollPolicy did nothing, and getting it always returned
* ScrollPolicy.OFF. So that's not going to work if we want the menu to scroll. Here we
* reinstate the verticalScrollPolicy setter, and keep a local copy of the value in a
* protected variable _verticalScrollPolicy.
*
* This setter is basically a copy of what ScrollControlBase and ListBase do.
*/
override public function set verticalScrollPolicy (value :String) :void
{
var newPolicy :String = value.toLowerCase();
itemsSizeChanged = true;
if (_verticalScrollPolicy != newPolicy)
{
_verticalScrollPolicy = newPolicy;
dispatchEvent(new Event("verticalScrollPolicyChanged"));
}
invalidateDisplayList();
}
override public function get verticalScrollPolicy () :String
{
return _verticalScrollPolicy;
}
public function CommandMenu ()
{
super();
itemRenderer = new ClassFactory(CommandMenuItemRenderer);
verticalScrollPolicy = ScrollPolicy.OFF;
addEventListener(MenuEvent.ITEM_CLICK, itemClicked);
}
/**
* Configures the event dispatcher to be used when dispatching this menu's command events.
* Normally they will be dispatched on our parent (usually the SystemManager or something).
*/
public function setDispatcher (dispatcher :IEventDispatcher) :void
{
_dispatcher = dispatcher;
}
/**
* Sets a Rectangle (in stage coords) that the menu will attempt to keep submenus positioned
* within. If a submenu is too large to fit, it will position it in the lower right corner
* of this Rectangle (or top if popping upwards, or left if popping leftwards). This
* value defaults to the stage bounds.
*/
public function setBounds (fitting :Rectangle) :void
{
_fitting = fitting;
}
/**
* Actually pop up the menu. This can be used instead of show().
*/
public function popUp (
trigger :DisplayObject, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void
{
_upping = popUpwards;
_lefting = popLeftwards;
var r :Rectangle = trigger.getBounds(trigger.stage);
show(_lefting ? r.left : r.right, _upping ? r.top : r.bottom);
}
/**
* Shows the menu at the specified mouse coordinates.
*/
public function popUpAt (
mx :int, my :int, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void
{
_upping = popUpwards;
_lefting = popLeftwards;
show(mx, my);
}
/**
* Shows the menu at the current mouse location.
*/
public function popUpAtMouse (popUpwards :Boolean = false, popLeftwards :Boolean = false) :void
{
_upping = popUpwards;
_lefting = popLeftwards;
show(); // our show, with no args, pops at the mouse
}
/**
* Just like our superclass's show(), except that when invoked with no args, causes the menu to
* show at the current mouse location instead of the top-left corner of the application.
* Also, we ensure that the resulting menu is in-bounds.
*/
override public function show (xShow :Object = null, yShow :Object = null) :void
{
if (xShow == null) {
xShow = DisplayObject(Application.application).mouseX;
}
if (yShow == null) {
yShow = DisplayObject(Application.application).mouseY;
}
super.show(xShow, yShow);
// reposition now that we know our size
if (_lefting) {
y = x - getExplicitOrMeasuredWidth();
}
if (_upping) {
y = y - getExplicitOrMeasuredHeight();
}
var fitting :Rectangle = _fitting || screen;
PopUpUtil.fitInRect(this, fitting);
// if after fitting as best we can, the menu is outside of the declared bounds, we force
// scrolling and set the max height
if (y < fitting.y) {
verticalScrollPolicy = ScrollPolicy.AUTO;
maxHeight = fitting.height;
y = fitting.y;
}
}
/**
* The Menu class overrode configureScrollBars() and made the function do nothing. That means
* the scrollbars don't know how to draw themselves, so here we reinstate configureScrollBars.
* This is basically a copy of the same method from the mx.controls.List class.
*/
override protected function configureScrollBars () :void
{
var rowCount :int = listItems.length;
if (rowCount == 0) {
return;
}
// if there is more than one row and it is a partial row we don't count it
if (rowCount > 1 &&
rowInfo[rowCount - 1].y + rowInfo[rowCount - 1].height > listContent.height) {
rowCount--;
}
// offset, when added to rowCount, is hte index of the dataProvider item for that row.
// IOW, row 10 in listItems is showing dataProvider item 10 + verticalScrollPosition -
// lockedRowCount - 1
var offset :int = verticalScrollPosition - lockedRowCount - 1;
// don't count filler rows at the bottom either.
var fillerRows :int = 0;
while (rowCount > 0 && listItems[rowCount - 1].length == 0)
{
if (collection && rowCount + offset >= collection.length) {
rowCount--;
fillerRows++;
} else {
break;
}
}
var colCount :int = listItems[0].length;
var oldHorizontalScrollBar :Object = horizontalScrollBar;
var oldVerticalScrollBar :Object = verticalScrollBar;
var roundedWidth :int = Math.round(unscaledWidth);
var length :int = collection ? collection.length - lockedRowCount : 0;
var numRows :int = rowCount - lockedRowCount;
setScrollBarProperties(Math.round(listContent.width), roundedWidth, length, numRows);
maxVerticalScrollPosition = Math.max(length - numRows, 0);
}
/**
* Callback for MenuEvent.ITEM_CLICK.
*/
protected function itemClicked (event :MenuEvent) :void
{
var arg :Object = getItemProp(event.item, "arg");
var cmdOrFn :Object = getItemProp(event.item, "command");
if (cmdOrFn == null) {
cmdOrFn = getItemProp(event.item, "callback");
}
if (cmdOrFn != null) {
event.stopImmediatePropagation();
CommandEvent.dispatch(_dispatcher == null ? mx_internal::parentDisplayObject :
_dispatcher, cmdOrFn, arg);
}
// else: no warning. There may be non-command menu items mixed in.
}
// from ScrollableArrowMenu..
override mx_internal function openSubMenu (row :IListItemRenderer) :void
{
supposedToLoseFocus = true;
var r :Menu = getRootMenu();
var menu :CommandMenu;
// check to see if the menu exists, if not create it
if (!IMenuItemRenderer(row).menu) {
// the only differences between this method and the original method in mx.controls.Menu
// are these few lines.
menu = new CommandMenu();
menu.maxHeight = this.maxHeight;
menu.verticalScrollPolicy = this.verticalScrollPolicy;
menu.variableRowHeight = this.variableRowHeight;
menu.parentMenu = this;
menu.owner = this;
menu.showRoot = showRoot;
menu.dataDescriptor = r.dataDescriptor;
menu.styleName = r;
menu.labelField = r.labelField;
menu.labelFunction = r.labelFunction;
menu.iconField = r.iconField;
menu.iconFunction = r.iconFunction;
menu.itemRenderer = r.itemRenderer;
menu.rowHeight = r.rowHeight;
menu.scaleY = r.scaleY;
menu.scaleX = r.scaleX;
// if there's data and it has children then add the items
if (row.data && _dataDescriptor.isBranch(row.data) &&
_dataDescriptor.hasChildren(row.data)) {
menu.dataProvider = _dataDescriptor.getChildren(row.data);
}
menu.sourceMenuBar = sourceMenuBar;
menu.sourceMenuBarItem = sourceMenuBarItem;
IMenuItemRenderer(row).menu = menu;
PopUpManager.addPopUp(menu, r, false);
}
super.openSubMenu(row);
// if we're lefting, upping or fitting make sure our submenu does so as well
var submenu :Menu = IMenuItemRenderer(row).menu;
if (_lefting) {
submenu.x -= submenu.getExplicitOrMeasuredWidth();
}
if (_upping) {
var displayObj :DisplayObject = DisplayObject(row);
var rowLoc :Point = displayObj.localToGlobal(new Point(row.x, row.y));
submenu.y = rowLoc.y - submenu.getExplicitOrMeasuredHeight() + displayObj.height;
}
var fitting :Rectangle = _fitting || screen;
PopUpUtil.fitInRect(submenu, fitting);
// if after fitting as best we can, the menu is outside of the declared bounds, we force
// scrolling and set the max height
if (submenu.y < fitting.y) {
submenu.verticalScrollPolicy = ScrollPolicy.AUTO;
submenu.maxHeight = fitting.height;
submenu.y = fitting.y;
}
}
override protected function measure () :void
{
super.measure();
if (measuredHeight > this.maxHeight) {
measuredHeight = this.maxHeight;
}
if (verticalScrollPolicy == ScrollPolicy.ON || verticalScrollPolicy == ScrollPolicy.AUTO) {
if (verticalScrollBar) {
measuredMinWidth = measuredWidth = measuredWidth + verticalScrollBar.minWidth;
}
}
commitProperties();
}
// from List
override protected function makeListData (data :Object, uid :String, rowNum :int) :BaseListData
{
// Oh, FFS.
// We need to set up these "maxMeasuredIconWidth" fields on the MenuListData, but our
// superclass has made those variables private.
// We can get the values out of another MenuListData, so we just always call super()
// to create one of those, and if we need to make a CommandListData, we construct one
// from the fields in the MenuListData.
var menuListData :MenuListData = super.makeListData(data, uid, rowNum) as MenuListData;
var iconObject :IFlexDisplayObject = getItemProp(data, "iconObject") as IFlexDisplayObject;
if (iconObject != null) {
var cmdListData :CommandListData = new CommandListData(menuListData.label,
menuListData.icon, iconObject, labelField, uid, this, rowNum);
cmdListData.maxMeasuredIconWidth = menuListData.maxMeasuredIconWidth;
cmdListData.maxMeasuredTypeIconWidth = menuListData.maxMeasuredTypeIconWidth;
cmdListData.maxMeasuredBranchIconWidth = menuListData.maxMeasuredBranchIconWidth;
cmdListData.useTwoColumns = menuListData.useTwoColumns;
return cmdListData;
}
return menuListData;
}
/**
* Get the specified property for the specified item, if any. Somewhat similar to bits in the
* DefaultDataDescriptor.
*/
protected function getItemProp (item :Object, prop :String) :Object
{
try {
if (item is XML) {
return String((item as XML).attribute(prop));
} else if (prop in item) {
return item[prop];
}
} catch (e :Error) {
// alas; fall through
}
return null;
}
protected var _dispatcher :IEventDispatcher;
protected var _lefting :Boolean = false;
protected var _upping :Boolean = false;
protected var _fitting :Rectangle = null;
protected var _verticalScrollPolicy :String;
}
}
|
//
// $Id$
//
// Nenya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/nenya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.flex {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.events.Event;
import flash.events.IEventDispatcher;
import flash.geom.Point;
import flash.geom.Rectangle;
import mx.controls.Menu;
import mx.controls.listClasses.BaseListData;
import mx.controls.listClasses.IListItemRenderer;
import mx.controls.menuClasses.IMenuItemRenderer;
import mx.controls.menuClasses.MenuListData;
import mx.core.mx_internal;
import mx.core.Application;
import mx.core.ClassFactory;
import mx.core.IFlexDisplayObject;
import mx.core.ScrollPolicy;
import mx.events.MenuEvent;
import mx.managers.PopUpManager;
import com.threerings.util.CommandEvent;
import com.threerings.flex.PopUpUtil;
import com.threerings.flex.menuClasses.CommandMenuItemRenderer;
import com.threerings.flex.menuClasses.CommandListData;
use namespace mx_internal;
/**
* A pretty standard menu that can submit CommandEvents if menu items have "command" and possibly
* "arg" properties. Commands are submitted to controllers for processing. Alternatively, you may
* specify "callback" properties that specify a function closure to call, with the "arg" property
* containing either a single arg or an array of args.
*
* Another property now supported is "iconObject", which is an already-instantiated
* IFlexDisplayObject to use as the icon. This will only be applied if the "icon" property
* (which specifies a Class) is not used.
*
* Example dataProvider array:
* [ { label: "Go home", icon: homeIconClass,
* command: Controller.GO_HOME, arg: homeId },
* { type: "separator"},
{ label: "Crazytown", callback: setCrazy, arg: [ true, false ] },
* { label: "Other places", children: subMenuArray }
* ];
*
* See "Defining menu structure and data" in the Flex manual for the full list.
*
* CommandMenu is scrollable. This can be forced by setting verticalScrollPolicy to
* ScrollPolicy.AUTO or ScrollPolicy.ON and setting the maxHeight. Also, if the scrolling isn't
* forced on, but the menu does not fit within the vertical bounds given (either the stage size by
* default, or the height of the rectangle given in setBounds()), scrolling will be turned on
* so that none of the content is lost.
*
* Note: we don't extend flexlib's ScrollableMenu (or its sub-class ScrollableArrowMenu) because it
* does some weird stuff in measure() that forces some of our menus down to a very small height...
*/
public class CommandMenu extends Menu
{
/**
* Factory method to create a command menu.
*
* @param items an array of menu items.
* @param dispatcher an override event dispatcher to use for command events, rather than
* our parent.
*/
public static function createMenu (
items :Array, dispatcher :IEventDispatcher = null) :CommandMenu
{
var menu :CommandMenu = new CommandMenu();
menu.owner = DisplayObjectContainer(Application.application);
menu.tabEnabled = false;
menu.showRoot = true;
menu.setDispatcher(dispatcher);
Menu.popUpMenu(menu, null, items); // does not actually pop up, but needed.
return menu;
}
/**
* The mx.controls.Menu class overrides setting and getting the verticalScrollPolicy
* basically setting the verticalScrollPolicy did nothing, and getting it always returned
* ScrollPolicy.OFF. So that's not going to work if we want the menu to scroll. Here we
* reinstate the verticalScrollPolicy setter, and keep a local copy of the value in a
* protected variable _verticalScrollPolicy.
*
* This setter is basically a copy of what ScrollControlBase and ListBase do.
*/
override public function set verticalScrollPolicy (value :String) :void
{
var newPolicy :String = value.toLowerCase();
itemsSizeChanged = true;
if (_verticalScrollPolicy != newPolicy)
{
_verticalScrollPolicy = newPolicy;
dispatchEvent(new Event("verticalScrollPolicyChanged"));
}
invalidateDisplayList();
}
override public function get verticalScrollPolicy () :String
{
return _verticalScrollPolicy;
}
public function CommandMenu ()
{
super();
itemRenderer = new ClassFactory(getItemRenderer());
verticalScrollPolicy = ScrollPolicy.OFF;
addEventListener(MenuEvent.ITEM_CLICK, itemClicked);
}
/**
* Called in the CommandMenu constructor, this should return the item rendering class for this
* CommandMenu.
*/
protected function getItemRenderer () :Class
{
return CommandMenuItemRenderer;
}
/**
* Configures the event dispatcher to be used when dispatching this menu's command events.
* Normally they will be dispatched on our parent (usually the SystemManager or something).
*/
public function setDispatcher (dispatcher :IEventDispatcher) :void
{
_dispatcher = dispatcher;
}
/**
* Sets a Rectangle (in stage coords) that the menu will attempt to keep submenus positioned
* within. If a submenu is too large to fit, it will position it in the lower right corner
* of this Rectangle (or top if popping upwards, or left if popping leftwards). This
* value defaults to the stage bounds.
*/
public function setBounds (fitting :Rectangle) :void
{
_fitting = fitting;
}
/**
* Actually pop up the menu. This can be used instead of show().
*/
public function popUp (
trigger :DisplayObject, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void
{
_upping = popUpwards;
_lefting = popLeftwards;
var r :Rectangle = trigger.getBounds(trigger.stage);
show(_lefting ? r.left : r.right, _upping ? r.top : r.bottom);
}
/**
* Shows the menu at the specified mouse coordinates.
*/
public function popUpAt (
mx :int, my :int, popUpwards :Boolean = false, popLeftwards :Boolean = false) :void
{
_upping = popUpwards;
_lefting = popLeftwards;
show(mx, my);
}
/**
* Shows the menu at the current mouse location.
*/
public function popUpAtMouse (popUpwards :Boolean = false, popLeftwards :Boolean = false) :void
{
_upping = popUpwards;
_lefting = popLeftwards;
show(); // our show, with no args, pops at the mouse
}
/**
* Just like our superclass's show(), except that when invoked with no args, causes the menu to
* show at the current mouse location instead of the top-left corner of the application.
* Also, we ensure that the resulting menu is in-bounds.
*/
override public function show (xShow :Object = null, yShow :Object = null) :void
{
if (xShow == null) {
xShow = DisplayObject(Application.application).mouseX;
}
if (yShow == null) {
yShow = DisplayObject(Application.application).mouseY;
}
super.show(xShow, yShow);
// reposition now that we know our size
if (_lefting) {
y = x - getExplicitOrMeasuredWidth();
}
if (_upping) {
y = y - getExplicitOrMeasuredHeight();
}
var fitting :Rectangle = _fitting || screen;
PopUpUtil.fitInRect(this, fitting);
// if after fitting as best we can, the menu is outside of the declared bounds, we force
// scrolling and set the max height
if (y < fitting.y) {
verticalScrollPolicy = ScrollPolicy.AUTO;
maxHeight = fitting.height;
y = fitting.y;
}
}
/**
* The Menu class overrode configureScrollBars() and made the function do nothing. That means
* the scrollbars don't know how to draw themselves, so here we reinstate configureScrollBars.
* This is basically a copy of the same method from the mx.controls.List class.
*/
override protected function configureScrollBars () :void
{
var rowCount :int = listItems.length;
if (rowCount == 0) {
return;
}
// if there is more than one row and it is a partial row we don't count it
if (rowCount > 1 &&
rowInfo[rowCount - 1].y + rowInfo[rowCount - 1].height > listContent.height) {
rowCount--;
}
// offset, when added to rowCount, is hte index of the dataProvider item for that row.
// IOW, row 10 in listItems is showing dataProvider item 10 + verticalScrollPosition -
// lockedRowCount - 1
var offset :int = verticalScrollPosition - lockedRowCount - 1;
// don't count filler rows at the bottom either.
var fillerRows :int = 0;
while (rowCount > 0 && listItems[rowCount - 1].length == 0)
{
if (collection && rowCount + offset >= collection.length) {
rowCount--;
fillerRows++;
} else {
break;
}
}
var colCount :int = listItems[0].length;
var oldHorizontalScrollBar :Object = horizontalScrollBar;
var oldVerticalScrollBar :Object = verticalScrollBar;
var roundedWidth :int = Math.round(unscaledWidth);
var length :int = collection ? collection.length - lockedRowCount : 0;
var numRows :int = rowCount - lockedRowCount;
setScrollBarProperties(Math.round(listContent.width), roundedWidth, length, numRows);
maxVerticalScrollPosition = Math.max(length - numRows, 0);
}
/**
* Callback for MenuEvent.ITEM_CLICK.
*/
protected function itemClicked (event :MenuEvent) :void
{
var arg :Object = getItemProp(event.item, "arg");
var cmdOrFn :Object = getItemProp(event.item, "command");
if (cmdOrFn == null) {
cmdOrFn = getItemProp(event.item, "callback");
}
if (cmdOrFn != null) {
event.stopImmediatePropagation();
CommandEvent.dispatch(_dispatcher == null ? mx_internal::parentDisplayObject :
_dispatcher, cmdOrFn, arg);
}
// else: no warning. There may be non-command menu items mixed in.
}
// from ScrollableArrowMenu..
override mx_internal function openSubMenu (row :IListItemRenderer) :void
{
supposedToLoseFocus = true;
var r :Menu = getRootMenu();
var menu :CommandMenu;
// check to see if the menu exists, if not create it
if (!IMenuItemRenderer(row).menu) {
// the only differences between this method and the original method in mx.controls.Menu
// are these few lines.
menu = new CommandMenu();
menu.maxHeight = this.maxHeight;
menu.verticalScrollPolicy = this.verticalScrollPolicy;
menu.variableRowHeight = this.variableRowHeight;
menu.parentMenu = this;
menu.owner = this;
menu.showRoot = showRoot;
menu.dataDescriptor = r.dataDescriptor;
menu.styleName = r;
menu.labelField = r.labelField;
menu.labelFunction = r.labelFunction;
menu.iconField = r.iconField;
menu.iconFunction = r.iconFunction;
menu.itemRenderer = r.itemRenderer;
menu.rowHeight = r.rowHeight;
menu.scaleY = r.scaleY;
menu.scaleX = r.scaleX;
// if there's data and it has children then add the items
if (row.data && _dataDescriptor.isBranch(row.data) &&
_dataDescriptor.hasChildren(row.data)) {
menu.dataProvider = _dataDescriptor.getChildren(row.data);
}
menu.sourceMenuBar = sourceMenuBar;
menu.sourceMenuBarItem = sourceMenuBarItem;
IMenuItemRenderer(row).menu = menu;
PopUpManager.addPopUp(menu, r, false);
}
super.openSubMenu(row);
// if we're lefting, upping or fitting make sure our submenu does so as well
var submenu :Menu = IMenuItemRenderer(row).menu;
if (_lefting) {
submenu.x -= submenu.getExplicitOrMeasuredWidth();
}
if (_upping) {
var displayObj :DisplayObject = DisplayObject(row);
var rowLoc :Point = displayObj.localToGlobal(new Point(row.x, row.y));
submenu.y = rowLoc.y - submenu.getExplicitOrMeasuredHeight() + displayObj.height;
}
var fitting :Rectangle = _fitting || screen;
PopUpUtil.fitInRect(submenu, fitting);
// if after fitting as best we can, the menu is outside of the declared bounds, we force
// scrolling and set the max height
if (submenu.y < fitting.y) {
submenu.verticalScrollPolicy = ScrollPolicy.AUTO;
submenu.maxHeight = fitting.height;
submenu.y = fitting.y;
}
}
override protected function measure () :void
{
super.measure();
if (measuredHeight > this.maxHeight) {
measuredHeight = this.maxHeight;
}
if (verticalScrollPolicy == ScrollPolicy.ON || verticalScrollPolicy == ScrollPolicy.AUTO) {
if (verticalScrollBar) {
measuredMinWidth = measuredWidth = measuredWidth + verticalScrollBar.minWidth;
}
}
commitProperties();
}
// from List
override protected function makeListData (data :Object, uid :String, rowNum :int) :BaseListData
{
// Oh, FFS.
// We need to set up these "maxMeasuredIconWidth" fields on the MenuListData, but our
// superclass has made those variables private.
// We can get the values out of another MenuListData, so we just always call super()
// to create one of those, and if we need to make a CommandListData, we construct one
// from the fields in the MenuListData.
var menuListData :MenuListData = super.makeListData(data, uid, rowNum) as MenuListData;
var iconObject :IFlexDisplayObject = getItemProp(data, "iconObject") as IFlexDisplayObject;
if (iconObject != null) {
var cmdListData :CommandListData = new CommandListData(menuListData.label,
menuListData.icon, iconObject, labelField, uid, this, rowNum);
cmdListData.maxMeasuredIconWidth = menuListData.maxMeasuredIconWidth;
cmdListData.maxMeasuredTypeIconWidth = menuListData.maxMeasuredTypeIconWidth;
cmdListData.maxMeasuredBranchIconWidth = menuListData.maxMeasuredBranchIconWidth;
cmdListData.useTwoColumns = menuListData.useTwoColumns;
return cmdListData;
}
return menuListData;
}
/**
* Get the specified property for the specified item, if any. Somewhat similar to bits in the
* DefaultDataDescriptor.
*/
protected function getItemProp (item :Object, prop :String) :Object
{
try {
if (item is XML) {
return String((item as XML).attribute(prop));
} else if (prop in item) {
return item[prop];
}
} catch (e :Error) {
// alas; fall through
}
return null;
}
protected var _dispatcher :IEventDispatcher;
protected var _lefting :Boolean = false;
protected var _upping :Boolean = false;
protected var _fitting :Rectangle = null;
protected var _verticalScrollPolicy :String;
}
}
|
Allow CommandMenu subclasses to provide their own item renderer.
|
Allow CommandMenu subclasses to provide their own item renderer.
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@544 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
2e9282a3e58fe2e61cebb501795a55cdcae5f74f
|
src/as/com/threerings/flex/FlexWrapper.as
|
src/as/com/threerings/flex/FlexWrapper.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.core.UIComponent;
/**
* Wraps a non-Flex component for use in Flex.
*/
public class FlexWrapper extends UIComponent
{
public function FlexWrapper (object :DisplayObject)
{
// don't capture mouse events in this wrapper
mouseEnabled = false;
addChild(object);
}
}
}
|
//
// $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.core.UIComponent;
/**
* Wraps a non-Flex component for use in Flex.
*/
public class FlexWrapper extends UIComponent
{
public function FlexWrapper (object :DisplayObject)
{
// don't capture mouse events in this wrapper
mouseEnabled = false;
_obj = object;
addChild(object);
}
override protected function measure () :void
{
measuredWidth = _obj.width;
measuredHeight = _obj.height;
}
protected var _obj :DisplayObject;
}
}
|
Make our measured size the size of the thing we're wrapping. Half the places we use FlexWrapper we do something like this anyway. Note that you can still override this by setting the width and height (which sets the explicitWidth, explicitHeight).
|
Make our measured size the size of the thing we're wrapping.
Half the places we use FlexWrapper we do something like this anyway.
Note that you can still override this by setting the width and height
(which sets the explicitWidth, explicitHeight).
git-svn-id: b675b909355d5cf946977f44a8ec5a6ceb3782e4@614 ed5b42cb-e716-0410-a449-f6a68f950b19
|
ActionScript
|
lgpl-2.1
|
threerings/nenya,threerings/nenya
|
00aeccf785ef9bf42da033acb5cce65befcb163f
|
src/org/flintparticles/threeD/renderers/Camera.as
|
src/org/flintparticles/threeD/renderers/Camera.as
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2010
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.threeD.renderers
{
import org.flintparticles.threeD.geom.Matrix3DUtils;
import org.flintparticles.threeD.geom.Vector3DUtils;
import org.flintparticles.threeD.renderers.controllers.CameraController;
import flash.geom.Matrix3D;
import flash.geom.Vector3D;
/**
* The camera class is used by Flint's internal 3D renderers to manage the view on the 3D
* world that is displayed by the renderer. Each renderer has a camera property, which is
* its camera object.
*/
public class Camera
{
private var _projectionDistance:Number = 400;
private var _nearDistance:Number = 10;
private var _farDistance:Number = 2000;
private var _transform:Matrix3D;
private var _spaceTransform:Matrix3D;
private var _position:Vector3D;
private var _down:Vector3D;
private var _target:Vector3D;
private var _controller:CameraController;
/*
* These properties have private getters because they can be
* invalidated when other properties are set - the getter
* recalculates the value if it has been invalidated
*/
private var _pDirection:Vector3D;
private var _pTrack:Vector3D;
private var _pFront:Vector3D;
/**
* The constructor creates a Camera object. Usually, users don't need to create camera
* objects, but will use the camera objects that are properties of Flint's renderers.
*/
public function Camera()
{
_position = new Vector3D( 0, 0, 0, 1 );
_target = new Vector3D( 0, 0, 0, 1 );
_down = new Vector3D( 0, 1, 0 );
_pDirection = new Vector3D( 0, 0, 1 );
}
/**
* The point that the camera looks at. Setting this will
* invalidate any setting for the camera direction - the direction
* will be recalculated based on the position and the target.
*
* @see #direction
*/
public function get target():Vector3D
{
return _target.clone();
}
public function set target( value:Vector3D ):void
{
_target = Vector3DUtils.clonePoint( value );
_pDirection = null;
_pTrack = null;
_spaceTransform = null;
}
/**
* The location of the camera.
*/
public function get position():Vector3D
{
return _position.clone();
}
public function set position( value:Vector3D ):void
{
_position = Vector3DUtils.clonePoint( value );
_spaceTransform = null;
if( _target )
{
_pDirection = null;
_pTrack = null;
}
}
/**
* The direction the camera is pointing. Setting this will invalidate any
* setting for the target, since the camera now points in this direction
* rather than pointing towards the target.
*
* @see #target
*/
public function get direction():Vector3D
{
return _direction.clone();
}
public function set direction( value:Vector3D ):void
{
_pDirection = Vector3DUtils.cloneUnit( value );
_target = null;
_spaceTransform = null;
_pTrack = null;
}
/**
* The down direction for the camera. If this is not perpendicular to the direction the camera points,
* the camera is tilted down or up from this up direction to point in the direction or at the target.
*/
public function get down():Vector3D
{
return _down.clone();
}
public function set down( value:Vector3D ):void
{
_down = Vector3DUtils.cloneUnit( value );
_spaceTransform = null;
_pTrack = null;
}
/**
* The transform matrix that converts positions in world space to positions in camera space.
* The projection transform is part of this transform - so vectors need only to have their
* project method called to get their position in 2D camera space.
*/
public function get transform():Matrix3D
{
if( !_spaceTransform || !_transform )
{
_transform = spaceTransform.clone();
var projectionTransform:Matrix3D = new Matrix3D( Vector.<Number>( [
_projectionDistance, 0, 0, 0,
0, _projectionDistance, 0, 0,
0, 0, 1, 1,
0, 0, 0, 0
] ) );
_transform.append( projectionTransform );
}
return _transform;
}
/**
* The transform matrix that converts positions in world space to positions in camera space.
* The projection transform is not part of this transform.
*/
public function get spaceTransform():Matrix3D
{
if( !_spaceTransform )
{
var realDown:Vector3D = _direction.crossProduct( _track );
_spaceTransform = Matrix3DUtils.newBasisTransform(
Vector3DUtils.cloneUnit( _track ),
Vector3DUtils.cloneUnit( realDown ),
Vector3DUtils.cloneUnit( _direction ) );
_spaceTransform.prependTranslation( -_position.x, -_position.y, -_position.z );
}
return _spaceTransform;
}
/**
* Dolly or Track the camera in/out in the direction it's facing.
*
* @param distance The distance to move the camera. Positive values track in and
* negative values track out.
*/
public function dolly( distance:Number ):void
{
var dollyVector:Vector3D = _direction.clone();
dollyVector.scaleBy( distance );
_position.incrementBy( dollyVector );
_spaceTransform = null;
}
/**
* Raise or lower the camera.
*
* @param distance The distance to lift the camera. Positive values raise the camera
* and negative values lower the camera.
*/
public function lift( distance:Number ):void
{
var liftVector:Vector3D = _down.clone();
liftVector.scaleBy( -distance );
_position.incrementBy( liftVector );
_spaceTransform = null;
}
/**
* Dolly or Track the camera left/right.
*
* @param distance The distance to move the camera. Positive values move the camera to the
* right, negative values move it to the left.
*/
public function track( distance:Number ):void
{
var trackVector:Vector3D = _track.clone();
trackVector.scaleBy( distance );
_position.incrementBy( trackVector );
_spaceTransform = null;
}
/**
* Tilt the camera up or down.
*
* @param The angle (in radians) to tilt the camera. Positive values tilt up,
* negative values tilt down.
*/
public function tilt( angle:Number ):void
{
var m:Matrix3D = Matrix3DUtils.newRotate( angle, _track );
_pDirection = m.transformVector( _direction );
_spaceTransform = null;
_target = null;
}
/**
* Pan the camera left or right.
*
* @param The angle (in radians) to pan the camera. Positive values pan right,
* negative values pan left.
*/
public function pan( angle:Number ):void
{
var m:Matrix3D = Matrix3DUtils.newRotate( angle, _down );
_pDirection = m.transformVector( _direction );
_pTrack = null;
_spaceTransform = null;
_target = null;
}
/**
* Roll the camera clockwise or counter-clockwise.
*
* @param The angle (in radians) to roll the camera. Positive values roll clockwise,
* negative values roll counter-clockwise.
*/
public function roll( angle:Number ):void
{
var m:Matrix3D = Matrix3DUtils.newRotate( angle, _front );
_down = m.transformVector( _down );
_pTrack = null;
_spaceTransform = null;
}
/**
* Orbit the camera around the target.
*
* @param The angle (in radians) to orbit the camera. Positive values orbit to the right,
* negative values orbit to the left.
*/
public function orbit( angle:Number ):void
{
if( !_target )
{
throw new Error( "Attempting to orbit camera when no target is set" );
}
var m:Matrix3D = Matrix3DUtils.newRotate( -angle, down );
_position = m.transformVector( _position );
_pDirection = null;
_pTrack = null;
_spaceTransform = null;
}
/**
* The distance to the camera's near plane
* - particles closer than this are not rendered.
*
* The default value is 10.
*/
public function get nearPlaneDistance():Number
{
return _nearDistance;
}
public function set nearPlaneDistance( value:Number ):void
{
_nearDistance = value;
}
/**
* The distance to the camera's far plane
* - particles farther away than this are not rendered.
*
* The default value is 2000.
*/
public function get farPlaneDistance():Number
{
return _farDistance;
}
public function set farPlaneDistance( value:Number ):void
{
_farDistance = value;
}
/**
* The distance to the camera's projection distance. Particles this
* distance from the camera are rendered at their normal size. Perspective
* will cause closer particles to appear larger than normal and more
* distant particles to appear smaller than normal.
*
* The default value is 400.
*/
public function get projectionDistance():Number
{
return _projectionDistance;
}
public function set projectionDistance( value:Number ):void
{
_projectionDistance = value;
_transform = null;
}
/*
* private getters for properties that can be invaliadated.
*/
private function get _track():Vector3D
{
if( _pTrack == null )
{
_pTrack = _down.crossProduct( _direction );
}
_pFront == null;
return _pTrack;
}
private function get _front():Vector3D
{
if( _pFront == null )
{
_pFront = _track.crossProduct( _down );
}
return _pFront;
}
private function get _direction():Vector3D
{
if( _pDirection == null && _target )
{
_pDirection = _target.subtract( _position );
_pDirection.normalize();
}
return _pDirection;
}
public function get controller():CameraController
{
return _controller;
}
public function set controller( value:CameraController ):void
{
if( _controller )
{
_controller.camera = null;
}
_controller = value;
_controller.camera = this;
}
}
}
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2010
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.threeD.renderers
{
import org.flintparticles.threeD.geom.Matrix3DUtils;
import org.flintparticles.threeD.geom.Vector3DUtils;
import org.flintparticles.threeD.renderers.controllers.CameraController;
import flash.geom.Matrix3D;
import flash.geom.Vector3D;
/**
* The camera class is used by Flint's internal 3D renderers to manage the view on the 3D
* world that is displayed by the renderer. Each renderer has a camera property, which is
* its camera object.
*/
public class Camera
{
private var _projectionDistance:Number = 400;
private var _nearDistance:Number = 10;
private var _farDistance:Number = 2000;
private var _transform:Matrix3D;
private var _spaceTransform:Matrix3D;
private var _position:Vector3D;
private var _down:Vector3D;
private var _target:Vector3D;
private var _controller:CameraController;
/*
* These properties have private getters because they can be
* invalidated when other properties are set - the getter
* recalculates the value if it has been invalidated
*/
private var _pDirection:Vector3D;
private var _pTrack:Vector3D;
private var _pFront:Vector3D;
private var _realDown:Vector3D;
private var _projectionTransform:Matrix3D;
/**
* The constructor creates a Camera object. Usually, users don't need to create camera
* objects, but will use the camera objects that are properties of Flint's renderers.
*/
public function Camera()
{
_position = new Vector3D( 0, 0, 0, 1 );
_target = new Vector3D( 0, 0, 0, 1 );
_down = new Vector3D( 0, 1, 0 );
_pDirection = new Vector3D( 0, 0, 1 );
_realDown = new Vector3D();
_projectionTransform = new Matrix3D;
}
/**
* The point that the camera looks at. Setting this will
* invalidate any setting for the camera direction - the direction
* will be recalculated based on the position and the target.
*
* @see #direction
*/
public function get target():Vector3D
{
return _target.clone();
}
public function set target( value:Vector3D ):void
{
_target = Vector3DUtils.clonePoint( value );
_pDirection = null;
_pTrack = null;
_spaceTransform = null;
}
/**
* The location of the camera.
*/
public function get position():Vector3D
{
return _position.clone();
}
public function set position( value:Vector3D ):void
{
_position = Vector3DUtils.clonePoint( value );
_spaceTransform = null;
if( _target )
{
_pDirection = null;
_pTrack = null;
}
}
/**
* The direction the camera is pointing. Setting this will invalidate any
* setting for the target, since the camera now points in this direction
* rather than pointing towards the target.
*
* @see #target
*/
public function get direction():Vector3D
{
return _direction.clone();
}
public function set direction( value:Vector3D ):void
{
_pDirection = Vector3DUtils.cloneUnit( value );
_target = null;
_spaceTransform = null;
_pTrack = null;
}
/**
* The down direction for the camera. If this is not perpendicular to the direction the camera points,
* the camera is tilted down or up from this up direction to point in the direction or at the target.
*/
public function get down():Vector3D
{
return _down.clone();
}
public function set down( value:Vector3D ):void
{
_down = Vector3DUtils.cloneUnit( value );
_spaceTransform = null;
_pTrack = null;
}
/**
* The transform matrix that converts positions in world space to positions in camera space.
* The projection transform is part of this transform - so vectors need only to have their
* project method called to get their position in 2D camera space.
*/
public function get transform():Matrix3D
{
if( !_spaceTransform || !_transform )
{
_transform = spaceTransform.clone();
_projectionTransform.rawData = Vector.<Number>( [
_projectionDistance, 0, 0, 0,
0, _projectionDistance, 0, 0,
0, 0, 1, 1,
0, 0, 0, 0
] );
_transform.append( _projectionTransform );
}
return _transform;
}
/**
* The transform matrix that converts positions in world space to positions in camera space.
* The projection transform is not part of this transform.
*/
public function get spaceTransform():Matrix3D
{
if( !_spaceTransform )
{
// This is more efficient than
//_realDown = _direction.crossProduct( _track );
_realDown.x = _direction.y * _track.z - _direction.z * _track.y;
_realDown.y = _direction.z * _track.x - _direction.x * _track.z;
_realDown.z = _direction.x * _track.y - _direction.y * _track.x;
_spaceTransform = Matrix3DUtils.newBasisTransform(
Vector3DUtils.cloneUnit( _track ),
Vector3DUtils.cloneUnit( _realDown ),
Vector3DUtils.cloneUnit( _direction ) );
_spaceTransform.prependTranslation( -_position.x, -_position.y, -_position.z );
}
return _spaceTransform;
}
/**
* Dolly or Track the camera in/out in the direction it's facing.
*
* @param distance The distance to move the camera. Positive values track in and
* negative values track out.
*/
public function dolly( distance:Number ):void
{
var dollyVector:Vector3D = _direction.clone();
dollyVector.scaleBy( distance );
_position.incrementBy( dollyVector );
_spaceTransform = null;
}
/**
* Raise or lower the camera.
*
* @param distance The distance to lift the camera. Positive values raise the camera
* and negative values lower the camera.
*/
public function lift( distance:Number ):void
{
var liftVector:Vector3D = _down.clone();
liftVector.scaleBy( -distance );
_position.incrementBy( liftVector );
_spaceTransform = null;
}
/**
* Dolly or Track the camera left/right.
*
* @param distance The distance to move the camera. Positive values move the camera to the
* right, negative values move it to the left.
*/
public function track( distance:Number ):void
{
var trackVector:Vector3D = _track.clone();
trackVector.scaleBy( distance );
_position.incrementBy( trackVector );
_spaceTransform = null;
}
/**
* Tilt the camera up or down.
*
* @param The angle (in radians) to tilt the camera. Positive values tilt up,
* negative values tilt down.
*/
public function tilt( angle:Number ):void
{
var m:Matrix3D = Matrix3DUtils.newRotate( angle, _track );
_pDirection = m.transformVector( _direction );
_spaceTransform = null;
_target = null;
}
/**
* Pan the camera left or right.
*
* @param The angle (in radians) to pan the camera. Positive values pan right,
* negative values pan left.
*/
public function pan( angle:Number ):void
{
var m:Matrix3D = Matrix3DUtils.newRotate( angle, _down );
_pDirection = m.transformVector( _direction );
_pTrack = null;
_spaceTransform = null;
_target = null;
}
/**
* Roll the camera clockwise or counter-clockwise.
*
* @param The angle (in radians) to roll the camera. Positive values roll clockwise,
* negative values roll counter-clockwise.
*/
public function roll( angle:Number ):void
{
var m:Matrix3D = Matrix3DUtils.newRotate( angle, _front );
_down = m.transformVector( _down );
_pTrack = null;
_spaceTransform = null;
}
/**
* Orbit the camera around the target.
*
* @param The angle (in radians) to orbit the camera. Positive values orbit to the right,
* negative values orbit to the left.
*/
public function orbit( angle:Number ):void
{
if( !_target )
{
throw new Error( "Attempting to orbit camera when no target is set" );
}
var m:Matrix3D = Matrix3DUtils.newRotate( -angle, down );
_position = m.transformVector( _position );
_pDirection = null;
_pTrack = null;
_spaceTransform = null;
}
/**
* The distance to the camera's near plane
* - particles closer than this are not rendered.
*
* The default value is 10.
*/
public function get nearPlaneDistance():Number
{
return _nearDistance;
}
public function set nearPlaneDistance( value:Number ):void
{
_nearDistance = value;
}
/**
* The distance to the camera's far plane
* - particles farther away than this are not rendered.
*
* The default value is 2000.
*/
public function get farPlaneDistance():Number
{
return _farDistance;
}
public function set farPlaneDistance( value:Number ):void
{
_farDistance = value;
}
/**
* The distance to the camera's projection distance. Particles this
* distance from the camera are rendered at their normal size. Perspective
* will cause closer particles to appear larger than normal and more
* distant particles to appear smaller than normal.
*
* The default value is 400.
*/
public function get projectionDistance():Number
{
return _projectionDistance;
}
public function set projectionDistance( value:Number ):void
{
_projectionDistance = value;
_transform = null;
}
/*
* private getters for properties that can be invaliadated.
*/
private function get _track():Vector3D
{
if( _pTrack == null )
{
_pTrack = _down.crossProduct( _direction );
}
_pFront == null;
return _pTrack;
}
private function get _front():Vector3D
{
if( _pFront == null )
{
_pFront = _track.crossProduct( _down );
}
return _pFront;
}
private function get _direction():Vector3D
{
if( _pDirection == null && _target )
{
_pDirection = _target.subtract( _position );
_pDirection.normalize();
}
return _pDirection;
}
public function get controller():CameraController
{
return _controller;
}
public function set controller( value:CameraController ):void
{
if( _controller )
{
_controller.camera = null;
}
_controller = value;
_controller.camera = this;
}
}
}
|
Add speed improvements to Camera class
|
Add speed improvements to Camera class
|
ActionScript
|
mit
|
richardlord/Flint
|
53fcd931929eba516e39aea4b17cc524b0fa8c78
|
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.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;
// Bytes per second. Set to undefined to disable limit.
private const RATE_LIMIT:Number = undefined; //10000;
// Seconds.
private const RATE_LIMIT_HISrelayY:Number = 5.0;
private var rate_limit:RateLimit;
// 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();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISrelayY, RATE_LIMIT_HISrelayY);
else
rate_limit = new RateUnlimit();
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 */
}
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, function (e:Event):void {
log("Relay: closed connection.");
close();
});
relay_socket.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Relay: I/O error: " + e.text + ".");
close();
});
relay_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Relay: security error: " + e.text + ".");
close();
});
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 (!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);
rate_limit.update(num_bytes);
}
if (r2c_schedule.length > 0) {
num_bytes = r2c_schedule.shift();
transfer_bytes(relay_socket, null, num_bytes);
rate_limit.update(num_bytes);
}
}
/* Call again when safe, if necessary. */
if (c2r_schedule.length > 0 || r2c_schedule.length > 0)
flush_id = setTimeout(flush, 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);
}
}
}
import flash.utils.getTimer;
class RateLimit
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
|
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.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;
// Bytes per second. Set to undefined to disable limit.
private const RATE_LIMIT:Number = undefined; //10000;
// Seconds.
private const RATE_LIMIT_HISTORY:Number = 5.0;
private var rate_limit:RateLimit;
// 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();
if (RATE_LIMIT)
rate_limit = new BucketRateLimit(RATE_LIMIT * RATE_LIMIT_HISTORY, RATE_LIMIT_HISTORY);
else
rate_limit = new RateUnlimit();
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 */
}
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, function (e:Event):void {
log("Relay: closed connection.");
close();
});
relay_socket.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Relay: I/O error: " + e.text + ".");
close();
});
relay_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Relay: security error: " + e.text + ".");
close();
});
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 (!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);
rate_limit.update(num_bytes);
}
if (r2c_schedule.length > 0) {
num_bytes = r2c_schedule.shift();
transfer_bytes(relay_socket, null, num_bytes);
rate_limit.update(num_bytes);
}
}
/* Call again when safe, if necessary. */
if (c2r_schedule.length > 0 || r2c_schedule.length > 0)
flush_id = setTimeout(flush, 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);
}
}
}
import flash.utils.getTimer;
class RateLimit
{
public function RateLimit()
{
}
public function update(n:Number):Boolean
{
return true;
}
public function when():Number
{
return 0.0;
}
public function is_limited():Boolean
{
return false;
}
}
class RateUnlimit extends RateLimit
{
public function RateUnlimit()
{
}
public override function update(n:Number):Boolean
{
return true;
}
public override function when():Number
{
return 0.0;
}
public override function is_limited():Boolean
{
return false;
}
}
class BucketRateLimit extends RateLimit
{
private var amount:Number;
private var capacity:Number;
private var time:Number;
private var last_update:uint;
public function BucketRateLimit(capacity:Number, time:Number)
{
this.amount = 0.0;
/* capacity / time is the rate we are aiming for. */
this.capacity = capacity;
this.time = time;
this.last_update = getTimer();
}
private function age():void
{
var now:uint;
var delta:Number;
now = getTimer();
delta = (now - last_update) / 1000.0;
last_update = now;
amount -= delta * capacity / time;
if (amount < 0.0)
amount = 0.0;
}
public override function update(n:Number):Boolean
{
age();
amount += n;
return amount <= capacity;
}
public override function when():Number
{
age();
return (amount - capacity) / (capacity / time);
}
public override function is_limited():Boolean
{
age();
return amount > capacity;
}
}
|
Fix a global search-and-replace error.
|
Fix a global search-and-replace error.
RATE_LIMIT_HISrelayY -> RATE_LIMIT_HISTORY
|
ActionScript
|
mit
|
infinity0/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,arlolra/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,glamrock/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy
|
f15e5a56662f8f5d7af341ea514fb5e93a2704b5
|
src/flash/display3D/Context3D.as
|
src/flash/display3D/Context3D.as
|
package flash.display3D
{
import flash.events.EventDispatcher;
import flash.geom.Matrix3D;
import flash.utils.ByteArray;
import flash.display3D.textures.*;
import flash.geom.Rectangle;
import flash.display.BitmapData;
/**
* ...
* @author lizhi http://matrix3d.github.io/
*/
public final class Context3D extends EventDispatcher
{
public var canvas:HTMLCanvasElement;
public var gl:WebGLRenderingContext;
private var currentProgram:Program3D;
private var currentTextures:Object = { };
private var currentVBufs:Object = { };
public function Context3D()
{
super();
}
public static function get supportsVideoTexture():Boolean { return false }
public function get driverInfo():String { return null }
public function dispose(recreate:Boolean = true):void
{
}
public function get enableErrorChecking():Boolean { return false }
public function set enableErrorChecking(toggle:Boolean):void
{
}
public function configureBackBuffer(width:int, height:int, antiAlias:int, enableDepthAndStencil:Boolean = true, wantsBestResolution:Boolean = false):void
{
canvas.width = width;
canvas.height = height;
canvas.style.width = width + "px";
canvas.style.height = height + "px";
gl.viewport(0, 0, width, height);
if (enableDepthAndStencil)
{
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.STENCIL_TEST);
}
else
{
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.STENCIL_TEST);
}
}
public function clear(red:Number = 0, green:Number = 0, blue:Number = 0, alpha:Number = 1, depth:Number = 1, stencil:uint = 0, mask:uint = 4294967295):void
{
SpriteFlexjs.dirtyGraphics = true;
gl.clearColor(red, green, blue, alpha);
gl.clearDepth(depth);
gl.clearStencil(stencil);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}
public function drawTriangles(indexBuffer:IndexBuffer3D, firstIndex:int = 0, numTriangles:int = -1):void
{
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer.buff);
gl.drawElements(gl.TRIANGLES, numTriangles < 0 ? indexBuffer.count : numTriangles * 3, gl.UNSIGNED_SHORT, firstIndex * 2);
}
public function present():void
{
SpriteFlexjs.dirtyGraphics = true;
}
public function setProgram(program:Program3D):void
{
if(currentProgram!=program){
currentProgram = program;
gl.useProgram(program.program);
}
}
public function setProgramConstantsFromVector(programType:String, firstRegister:int, data:Vector.<Number>, numRegisters:int = -1):void
{
//var num:int =gl.getProgramParameter(currentProgram.program, gl.ACTIVE_UNIFORMS);
//var count:int = 0;
//for (var i:int = 0; i < num;i++ ) {
// var au:WebGLActiveInfo = gl(currentProgram.program, i);
//}
setProgramConstantsFromVectorGL(getUniformLocationName(programType, firstRegister), data, numRegisters);
}
public function setProgramConstantsFromMatrix(programType:String, firstRegister:int, matrix:Matrix3D, transposedMatrix:Boolean = false):void
{
setProgramConstantsFromMatrixGL(getUniformLocationName(programType, firstRegister), matrix, transposedMatrix);
}
public function setProgramConstantsFromByteArray(programType:String, firstRegister:int, numRegisters:int, data:ByteArray, byteArrayOffset:uint):void
{
}
public function setProgramConstantsFromVectorGL(name:String, data:Vector.<Number>, numRegisters:int = -1):void
{
gl.uniform4fv(getUniformLocation(name), data as Object);
}
/**
* @flexjsignorecoercion Object
*/
public function setProgramConstantsFromMatrixGL(name:String, matrix:Matrix3D, transposedMatrix:Boolean = false):void
{
if (transposedMatrix) {
matrix.transpose();
}
gl.uniformMatrix4fv(getUniformLocation(name), false, matrix.rawData as Object);
if (transposedMatrix) {
matrix.transpose();
}
}
public function setProgramConstantsFromByteArrayGL(name:String , numRegisters:int, data:ByteArray, byteArrayOffset:uint):void
{
}
private function getUniformLocationName(programType:String, register:int):String
{
return (Context3DProgramType.VERTEX === programType) ? ("vc" + register) : ("fc" + register);
}
private function getUniformLocation(name:String):WebGLUniformLocation
{
return currentProgram.getUniformLocation(name);
}
public function setVertexBufferAt(index:int, buffer:VertexBuffer3D, bufferOffset:int = 0, format:String = "float4"):void
{
setVertexBufferAtGL("va" + index, buffer, bufferOffset, format);
}
public function setVertexBufferAtGL(name:String, buffer:VertexBuffer3D, bufferOffset:int = 0, format:String = "float4"):void {
if (currentVBufs[name] != buffer) {
currentVBufs[name] = buffer;
var loc:Number= currentProgram.getAttribLocation(name);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer.buff);
var type:int = gl.FLOAT;
var size:int = 0;
var normalized:Boolean = false;
switch (format)
{
case Context3DVertexBufferFormat.FLOAT_1:
size = 1;
break;
case Context3DVertexBufferFormat.FLOAT_2:
size = 2;
break;
case Context3DVertexBufferFormat.FLOAT_3:
size = 3;
break;
case Context3DVertexBufferFormat.FLOAT_4:
size = 4;
break;
case Context3DVertexBufferFormat.BYTES_4:
size = 4;
type = gl.UNSIGNED_BYTE;
normalized = true;
break;
}
gl.vertexAttribPointer(loc, size, type, normalized, buffer.data32PerVertex * 4, bufferOffset*4);
}
}
public function setBlendFactors(sourceFactor:String, destinationFactor:String):void
{
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(Context3DBlendFactor.getGLVal(gl,sourceFactor), Context3DBlendFactor.getGLVal(gl,destinationFactor));
}
public function setColorMask(red:Boolean, green:Boolean, blue:Boolean, alpha:Boolean):void
{
gl.colorMask(red, green, blue, alpha);
}
public function setDepthTest(depthMask:Boolean, passCompareMode:String):void
{
gl.depthFunc(Context3DCompareMode.getGLVal(gl,passCompareMode));
gl.depthMask(depthMask);
}
public function setTextureAt(sampler:int, texture:TextureBase):void
{
if (texture == null)
{
this.setTextureInternal(sampler, null);
}
else if (texture is Texture)
{
this.setTextureInternal(sampler, texture as Texture);
}
else if (texture is CubeTexture)
{
this.setCubeTextureInternal(sampler, texture as CubeTexture);
}
else if (texture is RectangleTexture)
{
this.setRectangleTextureInternal(sampler, texture as RectangleTexture);
}
else if (texture is VideoTexture)
{
this.setVideoTextureInternal(sampler, texture as VideoTexture);
}
}
public function setRenderToTexture(texture:TextureBase, enableDepthAndStencil:Boolean = false, antiAlias:int = 0, surfaceSelector:int = 0, colorOutputIndex:int = 0):void
{
var targetType:uint = 0;
if (texture is Texture)
{
targetType = 1;
}
else if (texture is CubeTexture)
{
targetType = 2;
}
else if (texture is RectangleTexture)
{
targetType = 3;
}
else if (texture != null)
{
throw "texture argument not derived from TextureBase (can be Texture, CubeTexture, or if supported, RectangleTexture)";
}
this.setRenderToTextureInternal(texture, targetType, enableDepthAndStencil, antiAlias, surfaceSelector, colorOutputIndex);
}
public function setRenderToBackBuffer():void
{
}
private function setRenderToTextureInternal(param1:TextureBase, param2:int, param3:Boolean, param4:int, param5:int, param6:int):void
{
}
public function setCulling(triangleFaceToCull:String):void
{
if (triangleFaceToCull === Context3DTriangleFace.NONE)
{
gl.disable(gl.CULL_FACE);
}
else
{
gl.enable(gl.CULL_FACE);
gl.cullFace(Context3DTriangleFace.getGLVal(gl,triangleFaceToCull));
}
}
public function setStencilActions(triangleFace:String = "frontAndBack", compareMode:String = "always", actionOnBothPass:String = "keep", actionOnDepthFail:String = "keep", actionOnDepthPassStencilFail:String = "keep"):void
{
}
public function setStencilReferenceValue(referenceValue:uint, readMask:uint = 255, writeMask:uint = 255):void
{
}
public function setScissorRectangle(rectangle:Rectangle):void
{
if (rectangle == null)
{
gl.disable(gl.SCISSOR_TEST);
}
else
{
gl.enable(gl.SCISSOR_TEST);
gl.scissor(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}
}
public function createVertexBuffer(numVertices:int, data32PerVertex:int, bufferUsage:String = "staticDraw"):VertexBuffer3D
{
var buffer:VertexBuffer3D = new VertexBuffer3D;
buffer.buff = gl.createBuffer();
buffer.data32PerVertex = data32PerVertex;
buffer.gl = gl;
return buffer;
}
public function createIndexBuffer(numIndices:int, bufferUsage:String = "staticDraw"):IndexBuffer3D
{
var buffer:IndexBuffer3D = new IndexBuffer3D;
buffer.buff = gl.createBuffer();
buffer.gl = gl;
buffer.count = numIndices;
return buffer;
}
public function createTexture(width:int, height:int, format:String, optimizeForRenderToTexture:Boolean, streamingLevels:int = 0):Texture
{
var t:Texture = new Texture;
t.gl = gl;
t.texture = gl.createTexture();
return t;
}
public function createCubeTexture(size:int, format:String, optimizeForRenderToTexture:Boolean, streamingLevels:int = 0):CubeTexture { return null }
public function createRectangleTexture(width:int, height:int, format:String, optimizeForRenderToTexture:Boolean):RectangleTexture { return null }
public function createProgram():Program3D
{
var p:Program3D = new Program3D;
p.gl = gl;
p.program = gl.createProgram();
return p;
}
public function drawToBitmapData(destination:BitmapData):void
{
}
public function setSamplerStateAt(sampler:int, wrap:String, filter:String, mipfilter:String):void
{
}
public function get profile():String { return null }
private function setTextureInternal(sampler:int, texture:Texture):void
{
setTextureAtGL("fs" + sampler, sampler, texture);
}
public function setTextureAtGL(name:String, sampler:int, texture:Texture):void {
if (currentTextures[name] != texture) {
currentTextures[name] = texture;
if (texture)
{
gl.activeTexture(WebGLRenderingContext["TEXTURE"+sampler]);
gl.bindTexture(gl.TEXTURE_2D, texture.texture);
gl.uniform1i(currentProgram.getUniformLocation(name), sampler);
}
}
}
private function setCubeTextureInternal(param1:int, param2:CubeTexture):void
{
}
private function setRectangleTextureInternal(param1:int, param2:RectangleTexture):void
{
}
private function setVideoTextureInternal(param1:int, param2:VideoTexture):void
{
}
public function get backBufferWidth():int { return 0 }
public function get backBufferHeight():int { return 0 }
public function get maxBackBufferWidth():int { return 0 }
public function set maxBackBufferWidth(width:int):void
{
}
public function get maxBackBufferHeight():int { return 0 }
public function set maxBackBufferHeight(height:int):void
{
}
public function createVideoTexture():VideoTexture { return null }
}
}
|
package flash.display3D
{
import flash.events.EventDispatcher;
import flash.geom.Matrix3D;
import flash.utils.ByteArray;
import flash.display3D.textures.*;
import flash.geom.Rectangle;
import flash.display.BitmapData;
/**
* ...
* @author lizhi http://matrix3d.github.io/
*/
public final class Context3D extends EventDispatcher
{
public var canvas:HTMLCanvasElement;
public var gl:WebGLRenderingContext;
private var currentProgram:Program3D;
private var currentTextures:Object = { };
private var currentVBufs:Object = { };
public function Context3D()
{
super();
}
public static function get supportsVideoTexture():Boolean { return false }
public function get driverInfo():String { return null }
public function dispose(recreate:Boolean = true):void
{
}
public function get enableErrorChecking():Boolean { return false }
public function set enableErrorChecking(toggle:Boolean):void
{
}
public function configureBackBuffer(width:int, height:int, antiAlias:int, enableDepthAndStencil:Boolean = true, wantsBestResolution:Boolean = false):void
{
canvas.width = width;
canvas.height = height;
canvas.style.width = width + "px";
canvas.style.height = height + "px";
gl.viewport(0, 0, width, height);
if (enableDepthAndStencil)
{
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.STENCIL_TEST);
}
else
{
gl.disable(gl.DEPTH_TEST);
gl.disable(gl.STENCIL_TEST);
}
}
public function clear(red:Number = 0, green:Number = 0, blue:Number = 0, alpha:Number = 1, depth:Number = 1, stencil:uint = 0, mask:uint = 4294967295):void
{
SpriteFlexjs.dirtyGraphics = true;
gl.clearColor(red, green, blue, alpha);
gl.clearDepth(depth);
gl.clearStencil(stencil);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
}
public function drawTriangles(indexBuffer:IndexBuffer3D, firstIndex:int = 0, numTriangles:int = -1):void
{
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer.buff);
gl.drawElements(gl.TRIANGLES, numTriangles < 0 ? indexBuffer.count : numTriangles * 3, gl.UNSIGNED_SHORT, firstIndex * 2);
}
public function present():void
{
SpriteFlexjs.dirtyGraphics = true;
}
public function setProgram(program:Program3D):void
{
if(currentProgram!=program){
currentProgram = program;
gl.useProgram(program.program);
}
}
public function setProgramConstantsFromVector(programType:String, firstRegister:int, data:Vector.<Number>, numRegisters:int = -1):void
{
//var num:int =gl.getProgramParameter(currentProgram.program, gl.ACTIVE_UNIFORMS);
//var count:int = 0;
//for (var i:int = 0; i < num;i++ ) {
// var au:WebGLActiveInfo = gl(currentProgram.program, i);
//}
setProgramConstantsFromVectorGL(getUniformLocationName(programType, firstRegister), data, numRegisters);
}
public function setProgramConstantsFromMatrix(programType:String, firstRegister:int, matrix:Matrix3D, transposedMatrix:Boolean = false):void
{
setProgramConstantsFromMatrixGL(getUniformLocationName(programType, firstRegister), matrix, transposedMatrix);
}
public function setProgramConstantsFromByteArray(programType:String, firstRegister:int, numRegisters:int, data:ByteArray, byteArrayOffset:uint):void
{
}
public function setProgramConstantsFromVectorGL(name:String, data:Vector.<Number>, numRegisters:int = -1):void
{
gl.uniform4fv(getUniformLocation(name), data as Object);
}
/**
* @flexjsignorecoercion Object
*/
public function setProgramConstantsFromMatrixGL(name:String, matrix:Matrix3D, transposedMatrix:Boolean = false):void
{
if (transposedMatrix) {
matrix.transpose();
}
gl.uniformMatrix4fv(getUniformLocation(name), false, matrix.rawData as Object);
if (transposedMatrix) {
matrix.transpose();
}
}
public function setProgramConstantsFromByteArrayGL(name:String , numRegisters:int, data:ByteArray, byteArrayOffset:uint):void
{
}
private function getUniformLocationName(programType:String, register:int):String
{
return (Context3DProgramType.VERTEX === programType) ? ("vc" + register) : ("fc" + register);
}
private function getUniformLocation(name:String):WebGLUniformLocation
{
return currentProgram.getUniformLocation(name);
}
public function setVertexBufferAt(index:int, buffer:VertexBuffer3D, bufferOffset:int = 0, format:String = "float4"):void
{
setVertexBufferAtGL("va" + index, buffer, bufferOffset, format);
}
public function setVertexBufferAtGL(name:String, buffer:VertexBuffer3D, bufferOffset:int = 0, format:String = "float4"):void {
if (currentVBufs[name] != buffer) {
currentVBufs[name] = buffer;
var loc:Number= currentProgram.getAttribLocation(name);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer.buff);
var type:int = gl.FLOAT;
var size:int = 0;
var mul:int=4;
var normalized:Boolean = false;
switch (format)
{
case Context3DVertexBufferFormat.FLOAT_1:
size = 1;
break;
case Context3DVertexBufferFormat.FLOAT_2:
size = 2;
break;
case Context3DVertexBufferFormat.FLOAT_3:
size = 3;
break;
case Context3DVertexBufferFormat.FLOAT_4:
size = 4;
break;
case Context3DVertexBufferFormat.BYTES_4:
size = 4;
type = gl.UNSIGNED_BYTE;
normalized = true;
mul = 1;
break;
}
gl.vertexAttribPointer(loc, size, type, normalized, buffer.data32PerVertex * mul, bufferOffset*mul);
}
}
public function setBlendFactors(sourceFactor:String, destinationFactor:String):void
{
gl.enable(gl.BLEND);
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(Context3DBlendFactor.getGLVal(gl,sourceFactor), Context3DBlendFactor.getGLVal(gl,destinationFactor));
}
public function setColorMask(red:Boolean, green:Boolean, blue:Boolean, alpha:Boolean):void
{
gl.colorMask(red, green, blue, alpha);
}
public function setDepthTest(depthMask:Boolean, passCompareMode:String):void
{
gl.depthFunc(Context3DCompareMode.getGLVal(gl,passCompareMode));
gl.depthMask(depthMask);
}
public function setTextureAt(sampler:int, texture:TextureBase):void
{
if (texture == null)
{
this.setTextureInternal(sampler, null);
}
else if (texture is Texture)
{
this.setTextureInternal(sampler, texture as Texture);
}
else if (texture is CubeTexture)
{
this.setCubeTextureInternal(sampler, texture as CubeTexture);
}
else if (texture is RectangleTexture)
{
this.setRectangleTextureInternal(sampler, texture as RectangleTexture);
}
else if (texture is VideoTexture)
{
this.setVideoTextureInternal(sampler, texture as VideoTexture);
}
}
public function setRenderToTexture(texture:TextureBase, enableDepthAndStencil:Boolean = false, antiAlias:int = 0, surfaceSelector:int = 0, colorOutputIndex:int = 0):void
{
var targetType:uint = 0;
if (texture is Texture)
{
targetType = 1;
}
else if (texture is CubeTexture)
{
targetType = 2;
}
else if (texture is RectangleTexture)
{
targetType = 3;
}
else if (texture != null)
{
throw "texture argument not derived from TextureBase (can be Texture, CubeTexture, or if supported, RectangleTexture)";
}
this.setRenderToTextureInternal(texture, targetType, enableDepthAndStencil, antiAlias, surfaceSelector, colorOutputIndex);
}
public function setRenderToBackBuffer():void
{
}
private function setRenderToTextureInternal(param1:TextureBase, param2:int, param3:Boolean, param4:int, param5:int, param6:int):void
{
}
public function setCulling(triangleFaceToCull:String):void
{
if (triangleFaceToCull === Context3DTriangleFace.NONE)
{
gl.disable(gl.CULL_FACE);
}
else
{
gl.enable(gl.CULL_FACE);
gl.cullFace(Context3DTriangleFace.getGLVal(gl,triangleFaceToCull));
}
}
public function setStencilActions(triangleFace:String = "frontAndBack", compareMode:String = "always", actionOnBothPass:String = "keep", actionOnDepthFail:String = "keep", actionOnDepthPassStencilFail:String = "keep"):void
{
}
public function setStencilReferenceValue(referenceValue:uint, readMask:uint = 255, writeMask:uint = 255):void
{
}
public function setScissorRectangle(rectangle:Rectangle):void
{
if (rectangle == null)
{
gl.disable(gl.SCISSOR_TEST);
}
else
{
gl.enable(gl.SCISSOR_TEST);
gl.scissor(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}
}
public function createVertexBuffer(numVertices:int, data32PerVertex:int, bufferUsage:String = "staticDraw"):VertexBuffer3D
{
var buffer:VertexBuffer3D = new VertexBuffer3D;
buffer.buff = gl.createBuffer();
buffer.data32PerVertex = data32PerVertex;
buffer.gl = gl;
return buffer;
}
public function createIndexBuffer(numIndices:int, bufferUsage:String = "staticDraw"):IndexBuffer3D
{
var buffer:IndexBuffer3D = new IndexBuffer3D;
buffer.buff = gl.createBuffer();
buffer.gl = gl;
buffer.count = numIndices;
return buffer;
}
public function createTexture(width:int, height:int, format:String, optimizeForRenderToTexture:Boolean, streamingLevels:int = 0):Texture
{
var t:Texture = new Texture;
t.gl = gl;
t.texture = gl.createTexture();
return t;
}
public function createCubeTexture(size:int, format:String, optimizeForRenderToTexture:Boolean, streamingLevels:int = 0):CubeTexture { return null }
public function createRectangleTexture(width:int, height:int, format:String, optimizeForRenderToTexture:Boolean):RectangleTexture { return null }
public function createProgram():Program3D
{
var p:Program3D = new Program3D;
p.gl = gl;
p.program = gl.createProgram();
return p;
}
public function drawToBitmapData(destination:BitmapData):void
{
}
public function setSamplerStateAt(sampler:int, wrap:String, filter:String, mipfilter:String):void
{
}
public function get profile():String { return null }
private function setTextureInternal(sampler:int, texture:Texture):void
{
setTextureAtGL("fs" + sampler, sampler, texture);
}
public function setTextureAtGL(name:String, sampler:int, texture:Texture):void {
if (currentTextures[name] != texture) {
currentTextures[name] = texture;
if (texture)
{
gl.activeTexture(WebGLRenderingContext["TEXTURE"+sampler]);
gl.bindTexture(gl.TEXTURE_2D, texture.texture);
gl.uniform1i(currentProgram.getUniformLocation(name), sampler);
}
}
}
private function setCubeTextureInternal(param1:int, param2:CubeTexture):void
{
}
private function setRectangleTextureInternal(param1:int, param2:RectangleTexture):void
{
}
private function setVideoTextureInternal(param1:int, param2:VideoTexture):void
{
}
public function get backBufferWidth():int { return 0 }
public function get backBufferHeight():int { return 0 }
public function get maxBackBufferWidth():int { return 0 }
public function set maxBackBufferWidth(width:int):void
{
}
public function get maxBackBufferHeight():int { return 0 }
public function set maxBackBufferHeight(height:int):void
{
}
public function createVideoTexture():VideoTexture { return null }
}
}
|
Update Context3D.as
|
Update Context3D.as
|
ActionScript
|
mit
|
matrix3d/spriteflexjs,matrix3d/spriteflexjs
|
b65bdd47e1cabb7771b1f32aa9e41a290dd6cdc6
|
src/as/com/threerings/util/MethodQueue.as
|
src/as/com/threerings/util/MethodQueue.as
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util {
import flash.display.Sprite;
import flash.events.Event;
/**
* A simple mechanism for queueing functions to be called on the next frame.
* Similar to UIComponent's callLater, only flex-free.
*/
public class MethodQueue
{
/**
* Call the specified method at the entry to the next frame.
*/
public static function callLater (fn :Function, args :Array = null) :void
{
_methodQueue.push([fn, args]);
if (!_d.hasEventListener(Event.ENTER_FRAME)) {
_d.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
}
}
/**
* Handle a frame event: call any queued functions.
*/
protected static function handleEnterFrame (event :Event) :void
{
// swap out the working set
var methods :Array = _methodQueue;
_methodQueue = [];
// safely call each function
for each (var arr :Array in methods) {
var fn :Function = (arr[0] as Function);
var args :Array = (arr[1] as Array);
try {
fn.apply(null, args);
} catch (e :Error) {
Log.getLog(MethodQueue).warning("Error calling deferred method " +
"[e=" + e + ", fn=" + fn + ", args=" + args + "].");
}
}
// If no new functions were added while we were calling the current set,
// then remove the listener.
if (_methodQueue.length == 0) {
_d.removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
}
}
/** A display object on which we listen for ENTER_FRAME. */
protected static var _d :Sprite = new Sprite();
/** The currently queued functions. */
protected static var _methodQueue :Array = [];
}
}
|
//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.util {
import flash.events.TimerEvent;
import flash.utils.Timer;
/**
* A simple mechanism for queueing functions to be called on the next frame.
* Similar to UIComponent's callLater, only flex-free.
*/
public class MethodQueue
{
/**
* Call the specified method at the entry to the next frame.
*/
public static function callLater (fn :Function, args :Array = null) :void
{
_methodQueue.push([fn, args]);
_t.start(); // starts the timer if it's not already running
}
/**
* Handle a timer event: call any queued functions.
*/
protected static function handleTimer (event :TimerEvent) :void
{
// swap out the working set
var methods :Array = _methodQueue;
_methodQueue = [];
// safely call each function
for each (var arr :Array in methods) {
var fn :Function = (arr[0] as Function);
var args :Array = (arr[1] as Array);
try {
fn.apply(null, args);
} catch (e :Error) {
Log.getLog(MethodQueue).warning("Error calling deferred method " +
"[e=" + e + ", fn=" + fn + ", args=" + args + "].");
}
}
// If no new functions were added while we were calling the current set,
// then stop firing
if (_methodQueue.length == 0) {
_t.stop();
}
}
/** A timer that will fire as quickly as possible. */
protected static var _t :Timer = new Timer(1);
/** The currently queued functions. */
protected static var _methodQueue :Array = [];
// a bit of static initialization
_t.addEventListener(TimerEvent.TIMER, handleTimer);
}
}
|
Use a Timer instead of ENTER_FRAME. This is a potentially more dangerous change, but nothing seems awry. Eyes peeled!
|
Use a Timer instead of ENTER_FRAME.
This is a potentially more dangerous change, but nothing
seems awry. Eyes peeled!
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@5017 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
8a40760b22ce3ea49585dd1f35bf7107a6a15282
|
src/com/esri/builder/model/PortalModel.as
|
src/com/esri/builder/model/PortalModel.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.model
{
import com.esri.ags.portal.Portal;
import com.esri.builder.supportClasses.URLUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import mx.utils.StringUtil;
public class PortalModel extends EventDispatcher
{
//--------------------------------------------------------------------------
//
// Constants
//
//--------------------------------------------------------------------------
public static const DEFAULT_PORTAL_URL:String = "https://www.arcgis.com/";
private static var instance:PortalModel;
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
public static function getInstance():PortalModel
{
if (!instance)
{
instance = new PortalModel(new SingletonEnforcer());
}
return instance;
}
public function cleanUpPortalURL(url:String):String
{
var cleanURL:String = url;
cleanURL = StringUtil.trim(cleanURL);
cleanURL = replacePreviousDefaultPortalURL(cleanURL);
cleanURL = cleanURL.replace(/\/sharing\/content\/items\/?$/i, '');
cleanURL = URLUtil.ensureTrailingForwardSlash(cleanURL);
cleanURL = URLUtil.encode(cleanURL);
return cleanURL;
}
private function replacePreviousDefaultPortalURL(url:String):String
{
const previousDefaultPortalURL:String = "http://www.arcgis.com/";
return url.replace(previousDefaultPortalURL, DEFAULT_PORTAL_URL);
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
public function PortalModel(singletonEnforcer:SingletonEnforcer)
{
if (!singletonEnforcer)
{
throw new Error("Class should not be instantiated - use getInstance()");
}
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// portal
//----------------------------------
[Bindable]
public var portal:Portal = new Portal();
//----------------------------------
// portalURL
//----------------------------------
/**
* The ArcGIS Portal URL
*/
private var _portalURL:String;
[Bindable("userDefinedPortalURLChanged")]
public function get portalURL():String
{
return _portalURL;
}
public function set portalURL(value:String):void
{
if (_portalURL != value)
{
_portalURL = cleanUpPortalURL(value);
dispatchEvent(new Event("userDefinedPortalURLChanged"));
}
}
}
}
class SingletonEnforcer
{
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2013 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.model
{
import com.esri.ags.components.IdentityManager;
import com.esri.ags.components.supportClasses.Credential;
import com.esri.ags.portal.Portal;
import com.esri.builder.supportClasses.PortalUtil;
import com.esri.builder.supportClasses.URLUtil;
import flash.events.Event;
import flash.events.EventDispatcher;
import mx.utils.StringUtil;
public class PortalModel extends EventDispatcher
{
//--------------------------------------------------------------------------
//
// Constants
//
//--------------------------------------------------------------------------
public static const DEFAULT_PORTAL_URL:String = "https://www.arcgis.com/";
private static var instance:PortalModel;
//--------------------------------------------------------------------------
//
// Class methods
//
//--------------------------------------------------------------------------
public static function getInstance():PortalModel
{
if (!instance)
{
instance = new PortalModel(new SingletonEnforcer());
}
return instance;
}
public function cleanUpPortalURL(url:String):String
{
var cleanURL:String = url;
cleanURL = StringUtil.trim(cleanURL);
cleanURL = replacePreviousDefaultPortalURL(cleanURL);
cleanURL = cleanURL.replace(/\/sharing\/content\/items\/?$/i, '');
cleanURL = URLUtil.ensureTrailingForwardSlash(cleanURL);
cleanURL = URLUtil.encode(cleanURL);
return cleanURL;
}
private function replacePreviousDefaultPortalURL(url:String):String
{
const previousDefaultPortalURL:String = "http://www.arcgis.com/";
return url.replace(previousDefaultPortalURL, DEFAULT_PORTAL_URL);
}
public function canSignOut():Boolean
{
var credential:Credential = IdentityManager.instance.findCredential(PortalUtil.toPortalSharingURL(portal.url));
return portal.signedIn && (credential != null);
}
//--------------------------------------------------------------------------
//
// Constructor
//
//--------------------------------------------------------------------------
public function PortalModel(singletonEnforcer:SingletonEnforcer)
{
if (!singletonEnforcer)
{
throw new Error("Class should not be instantiated - use getInstance()");
}
}
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
//----------------------------------
// portal
//----------------------------------
[Bindable]
public var portal:Portal = new Portal();
//----------------------------------
// portalURL
//----------------------------------
/**
* The ArcGIS Portal URL
*/
private var _portalURL:String;
[Bindable("userDefinedPortalURLChanged")]
public function get portalURL():String
{
return _portalURL;
}
public function set portalURL(value:String):void
{
if (_portalURL != value)
{
_portalURL = cleanUpPortalURL(value);
dispatchEvent(new Event("userDefinedPortalURLChanged"));
}
}
}
}
class SingletonEnforcer
{
}
|
Add logic to PortalModel to determine if the user can sign out.
|
Add logic to PortalModel to determine if the user can sign out.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
0682a002573f027f4897e716f06086ef6de445b8
|
src/flash/plupload/src/com/plupload/File.as
|
src/flash/plupload/src/com/plupload/File.as
|
/**
* File.as
*
* Copyright 2009, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
package com.plupload {
import com.formatlos.BitmapDataUnlimited;
import com.formatlos.events.BitmapDataUnlimitedEvent;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.IBitmapDrawable;
import flash.events.EventDispatcher;
import flash.geom.Matrix;
import flash.net.FileReference;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.HTTPStatusEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.events.DataEvent;
import flash.net.FileReferenceList;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLStream;
import flash.net.URLVariables;
import flash.utils.ByteArray;
import flash.external.ExternalInterface;
import com.mxi.image.Image;
import com.mxi.image.events.ImageEvent;
/**
* Container class for file references, this handles upload logic for individual files.
*/
public class File extends EventDispatcher {
// Private fields
private var _fileRef:FileReference, _cancelled:Boolean;
private var _uploadUrl:String, _uploadPath:String, _mimeType:String;
private var _id:String, _fileName:String, _size:Number, _imageData:ByteArray;
private var _multipart:Boolean, _fileDataName:String, _chunking:Boolean, _chunk:int, _chunks:int, _chunkSize:int, _postvars:Object;
private var _headers:Object, _settings:Object;
/**
* Id property of file.
*/
public function get id():String {
return this._id;
}
/**
* File name for the file.
*/
public function get fileName():String {
return this._fileName;
}
/**
* File name for the file.
*/
public function set fileName(value:String):void {
this._fileName = value;
}
/**
* File size property.
*/
public function get size():Number {
return this._size;
}
/**
* Constructs a new file object.
*
* @param id Unique indentifier for the file.
* @param file_ref File reference for the selected file.
*/
public function File(id:String, file_ref:FileReference) {
this._id = id;
this._fileRef = file_ref;
this._size = file_ref.size;
this._fileName = file_ref.name;
}
/**
* Uploads a the file to the specified url. This method will upload it as a normal
* multipart file upload if the file size is smaller than the chunk size. But if the file is to
* large it will be chunked into multiple requests.
*
* @param url Url to upload the file to.
* @param settings Settings object.
*/
public function upload(url:String, settings:Object):void {
this._settings = settings;
if (this.canUseSimpleUpload(settings)) {
this.simpleUpload(url, settings);
} else {
this.advancedUpload(url, settings);
}
}
// Private methods
public function canUseSimpleUpload(settings:Object):Boolean {
var multipart:Boolean = new Boolean(settings["multipart"]);
var resize:Boolean = (settings["width"] || settings["height"] || settings["quality"]);
var chunking:Boolean = (settings["chunk_size"] > 0);
// Check if it's not an image, chunking is disabled, multipart enabled and the ref_upload setting isn't forced
return (!(/\.(jpeg|jpg|png)$/i.test(this._fileName)) || !resize) && multipart && !chunking && !settings.urlstream_upload;
}
public function simpleUpload(url:String, settings:Object):void {
var file:File = this, request:URLRequest, postData:URLVariables, fileDataName:String,
onProgress:Function, onUploadComplete:Function, onIOError:Function, onSecurityErrorEvent:Function,
removeAllListeners:Function = function () : void {
file._fileRef.removeEventListener(ProgressEvent.PROGRESS, onProgress);
file._fileRef.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
file._fileRef.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
file._fileRef.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErrorEvent);
};
file._postvars = settings["multipart_params"];
file._chunk = 0;
file._chunks = 1;
postData = new URLVariables();
file._postvars["name"] = settings["name"];
for (var key:String in file._postvars) {
if (key != 'Filename') { // Flash will add it by itself, so we need to omit potential duplicate
postData[key] = file._postvars[key];
}
}
request = new URLRequest();
request.method = URLRequestMethod.POST;
request.url = url;
request.data = postData;
fileDataName = new String(settings["file_data_name"]);
onUploadComplete = function(e:DataEvent):void {
removeAllListeners();
var pe:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS, false, false, file._size, file._size);
dispatchEvent(pe);
// Fake UPLOAD_COMPLETE_DATA event
var uploadChunkEvt:UploadChunkEvent = new UploadChunkEvent(
UploadChunkEvent.UPLOAD_CHUNK_COMPLETE_DATA,
false,
false,
e.data,
file._chunk,
file._chunks
);
file._chunk++;
file._fileRef.data.clear();
dispatchEvent(uploadChunkEvt);
dispatchEvent(e);
};
file._fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
// Delegate upload IO errors
onIOError = function(e:IOErrorEvent):void {
removeAllListeners();
dispatchEvent(e);
};
file._fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
// Delegate secuirty errors
onSecurityErrorEvent = function(e:SecurityErrorEvent):void {
removeAllListeners();
dispatchEvent(e);
};
file._fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErrorEvent);
// Delegate progress
onProgress = function(e:ProgressEvent):void {
dispatchEvent(e);
};
file._fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress);
file._fileRef.upload(request, fileDataName, false);
}
public function advancedUpload(url:String, settings:Object):void {
var file:File = this, width:int, height:int, quality:int, multipart:Boolean, chunking:Boolean, fileDataName:String;
var chunk:int, chunks:int, chunkSize:int, postvars:Object;
var onComplete:Function, onIOError:Function,
removeAllListeneres:Function = function() : void {
file._fileRef.removeEventListener(Event.COMPLETE, onComplete);
file._fileRef.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
};
// Setup internal vars
this._uploadUrl = url;
this._cancelled = false;
this._headers = settings.headers;
this._mimeType = settings.mime;
multipart = new Boolean(settings["multipart"]);
fileDataName = new String(settings["file_data_name"]);
chunkSize = settings["chunk_size"];
chunking = chunkSize > 0;
postvars = settings["multipart_params"];
chunk = 0;
// When file is loaded start uploading
onComplete = function(e:Event):void {
removeAllListeneres();
var startUpload:Function = function() : void
{
if (chunking) {
chunks = Math.ceil(file._size / chunkSize);
// Force at least 4 chunks to fake progress. We need to fake this since the URLLoader
// doesn't have a upload progress event and we can't use FileReference.upload since it
// doesn't support cookies, breaks on HTTPS and doesn't support custom data so client
// side image resizing will not be possible.
if (chunks < 4 && file._size > 1024 * 32) {
chunkSize = Math.ceil(file._size / 4);
chunks = 4;
}
} else {
// If chunking is disabled then upload file in one huge chunk
chunkSize = file._size;
chunks = 1;
}
// Start uploading the scaled down image
file._multipart = multipart;
file._fileDataName = fileDataName;
file._chunking = chunking;
file._chunk = chunk;
file._chunks = chunks;
file._chunkSize = chunkSize;
file._postvars = postvars;
file.uploadNextChunk();
}
if (/\.(jpeg|jpg|png)$/i.test(file._fileName) && (settings["width"] || settings["height"] || settings["quality"])) {
var image:Image = new Image(file._fileRef.data);
image.addEventListener(ImageEvent.COMPLETE, function(e:ImageEvent) : void
{
image.removeAllEventListeners();
if (image.imageData) {
file._imageData = image.imageData;
file._imageData.position = 0;
file._size = image.imageData.length;
}
startUpload();
});
image.addEventListener(ImageEvent.ERROR, function(e:ImageEvent) : void
{
image.removeAllEventListeners();
file.dispatchEvent(e);
});
image.scale(settings["width"], settings["height"], settings["quality"]);
} else {
startUpload();
}
};
this._fileRef.addEventListener(Event.COMPLETE, onComplete);
// File load IO error
onIOError = function(e:Event):void {
removeAllListeneres();
this.dispatchEvent(e);
};
this._fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
// Start loading local file
this._fileRef.load();
}
/**
* Uploads the next chunk or terminates the upload loop if all chunks are done.
*/
public function uploadNextChunk():Boolean {
var req:URLRequest, fileData:ByteArray, chunkData:ByteArray;
var urlStream:URLStream, url:String, file:File = this;
// All chunks uploaded?
if (this._chunk >= this._chunks) {
// Clean up memory
if(this._fileRef.data) {
this._fileRef.data.clear();
}
this._imageData = null;
return false;
}
// Slice out a chunk
chunkData = new ByteArray();
// Use image data if it exists, will exist if the image was resized
if (this._imageData != null)
fileData = this._imageData;
else
fileData = this._fileRef.data;
fileData.readBytes(chunkData, 0, fileData.position + this._chunkSize > fileData.length ? fileData.length - fileData.position : this._chunkSize);
// Setup URL stream
urlStream = new URLStream();
// Wait for response and dispatch it
urlStream.addEventListener(Event.COMPLETE, function(e:Event):void {
var response:String;
response = urlStream.readUTFBytes(urlStream.bytesAvailable);
// Fake UPLOAD_COMPLETE_DATA event
var uploadChunkEvt:UploadChunkEvent = new UploadChunkEvent(
UploadChunkEvent.UPLOAD_CHUNK_COMPLETE_DATA,
false,
false,
response,
file._chunk,
file._chunks
);
file._chunk++;
dispatchEvent(uploadChunkEvt);
// Fake progress event since Flash doesn't have a progress event for streaming data up to the server
var pe:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS, false, false, fileData.position, file._size);
dispatchEvent(pe);
// Clean up memory
urlStream.close();
chunkData.clear();
});
// Delegate upload IO errors
urlStream.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void {
dispatchEvent(e);
});
// Delegate secuirty errors
urlStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(e:SecurityErrorEvent):void {
dispatchEvent(e);
});
// Setup URL
url = this._uploadUrl;
// Add name and chunk/chunks to URL if we use direct streaming method
if (!this._multipart) {
if (url.indexOf('?') == -1)
url += '?';
else
url += '&';
url += "name=" + encodeURIComponent(this._settings["name"]);
if (this._chunking) {
url += "&chunk=" + this._chunk + "&chunks=" + this._chunks;
}
}
// Setup request
req = new URLRequest(url);
req.method = URLRequestMethod.POST;
// Add custom headers
if (this._headers) {
for (var headerName:String in this._headers) {
req.requestHeaders.push(new URLRequestHeader(headerName, this._headers[headerName]));
}
}
// Build multipart request
if (this._multipart) {
var boundary:String = '----pluploadboundary' + new Date().getTime(),
dashdash:String = '--', crlf:String = '\r\n', multipartBlob: ByteArray = new ByteArray();
req.requestHeaders.push(new URLRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary));
this._postvars["name"] = this._settings["name"];
// Add chunking parameters if needed
if (this._chunking) {
this._postvars["chunk"] = this._chunk;
this._postvars["chunks"] = this._chunks;
}
// Append mutlipart parameters
for (var name:String in this._postvars) {
multipartBlob.writeUTFBytes(
dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf +
this._postvars[name] + crlf
);
}
// Add file header
multipartBlob.writeUTFBytes(
dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + this._fileDataName + '"; filename="' + this._fileName + '"' + crlf +
'Content-Type: ' + this._mimeType + crlf + crlf
);
// Add file data
multipartBlob.writeBytes(chunkData, 0, chunkData.length);
// Add file footer
multipartBlob.writeUTFBytes(crlf + dashdash + boundary + dashdash + crlf);
req.data = multipartBlob;
} else {
req.requestHeaders.push(new URLRequestHeader("Content-Type", "application/octet-stream"));
req.data = chunkData;
}
// Make request
urlStream.load(req);
return true;
}
}
}
|
/**
* File.as
*
* Copyright 2009, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
package com.plupload {
import com.formatlos.BitmapDataUnlimited;
import com.formatlos.events.BitmapDataUnlimitedEvent;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.IBitmapDrawable;
import flash.events.EventDispatcher;
import flash.geom.Matrix;
import flash.net.FileReference;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.HTTPStatusEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.events.DataEvent;
import flash.net.FileReferenceList;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLStream;
import flash.net.URLVariables;
import flash.utils.ByteArray;
import flash.external.ExternalInterface;
import com.mxi.image.Image;
import com.mxi.image.events.ImageEvent;
/**
* Container class for file references, this handles upload logic for individual files.
*/
public class File extends EventDispatcher {
// Private fields
private var _fileRef:FileReference, _cancelled:Boolean;
private var _uploadUrl:String, _uploadPath:String, _mimeType:String;
private var _id:String, _fileName:String, _size:Number, _imageData:ByteArray;
private var _multipart:Boolean, _fileDataName:String, _chunking:Boolean, _chunk:int, _chunks:int, _chunkSize:int, _postvars:Object;
private var _headers:Object, _settings:Object;
/**
* Id property of file.
*/
public function get id():String {
return this._id;
}
/**
* File name for the file.
*/
public function get fileName():String {
return this._fileName;
}
/**
* File name for the file.
*/
public function set fileName(value:String):void {
this._fileName = value;
}
/**
* File size property.
*/
public function get size():Number {
return this._size;
}
/**
* Constructs a new file object.
*
* @param id Unique indentifier for the file.
* @param file_ref File reference for the selected file.
*/
public function File(id:String, file_ref:FileReference) {
this._id = id;
this._fileRef = file_ref;
this._size = file_ref.size;
this._fileName = file_ref.name;
}
/**
* Uploads a the file to the specified url. This method will upload it as a normal
* multipart file upload if the file size is smaller than the chunk size. But if the file is to
* large it will be chunked into multiple requests.
*
* @param url Url to upload the file to.
* @param settings Settings object.
*/
public function upload(url:String, settings:Object):void {
this._settings = settings;
if (this.canUseSimpleUpload(settings)) {
this.simpleUpload(url, settings);
} else {
this.advancedUpload(url, settings);
}
}
// Private methods
public function canUseSimpleUpload(settings:Object):Boolean {
var multipart:Boolean = new Boolean(settings["multipart"]);
var resize:Boolean = (settings["width"] || settings["height"] || settings["quality"]);
var chunking:Boolean = (settings["chunk_size"] > 0);
// Check if it's not an image, chunking is disabled, multipart enabled and the ref_upload setting isn't forced
return (!(/\.(jpeg|jpg|png)$/i.test(this._fileName)) || !resize) && multipart && !chunking && !settings.urlstream_upload;
}
public function simpleUpload(url:String, settings:Object):void {
var file:File = this, request:URLRequest, postData:URLVariables, fileDataName:String,
onProgress:Function, onUploadComplete:Function, onIOError:Function, onSecurityErrorEvent:Function,
removeAllListeners:Function = function () : void {
file._fileRef.removeEventListener(ProgressEvent.PROGRESS, onProgress);
file._fileRef.removeEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
file._fileRef.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
file._fileRef.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErrorEvent);
};
file._postvars = settings["multipart_params"];
file._chunk = 0;
file._chunks = 1;
postData = new URLVariables();
file._postvars["name"] = settings["name"];
for (var key:String in file._postvars) {
if (key != 'Filename') { // Flash will add it by itself, so we need to omit potential duplicate
postData[key] = file._postvars[key];
}
}
request = new URLRequest();
request.method = URLRequestMethod.POST;
request.url = url;
request.data = postData;
fileDataName = new String(settings["file_data_name"]);
onUploadComplete = function(e:DataEvent):void {
removeAllListeners();
var pe:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS, false, false, file._size, file._size);
dispatchEvent(pe);
// Fake UPLOAD_COMPLETE_DATA event
var uploadChunkEvt:UploadChunkEvent = new UploadChunkEvent(
UploadChunkEvent.UPLOAD_CHUNK_COMPLETE_DATA,
false,
false,
e.data,
file._chunk,
file._chunks
);
file._chunk++;
dispatchEvent(uploadChunkEvt);
dispatchEvent(e);
};
file._fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);
// Delegate upload IO errors
onIOError = function(e:IOErrorEvent):void {
removeAllListeners();
dispatchEvent(e);
};
file._fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
// Delegate secuirty errors
onSecurityErrorEvent = function(e:SecurityErrorEvent):void {
removeAllListeners();
dispatchEvent(e);
};
file._fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErrorEvent);
// Delegate progress
onProgress = function(e:ProgressEvent):void {
dispatchEvent(e);
};
file._fileRef.addEventListener(ProgressEvent.PROGRESS, onProgress);
file._fileRef.upload(request, fileDataName, false);
}
public function advancedUpload(url:String, settings:Object):void {
var file:File = this, width:int, height:int, quality:int, multipart:Boolean, chunking:Boolean, fileDataName:String;
var chunk:int, chunks:int, chunkSize:int, postvars:Object;
var onComplete:Function, onIOError:Function,
removeAllListeneres:Function = function() : void {
file._fileRef.removeEventListener(Event.COMPLETE, onComplete);
file._fileRef.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
};
// Setup internal vars
this._uploadUrl = url;
this._cancelled = false;
this._headers = settings.headers;
this._mimeType = settings.mime;
multipart = new Boolean(settings["multipart"]);
fileDataName = new String(settings["file_data_name"]);
chunkSize = settings["chunk_size"];
chunking = chunkSize > 0;
postvars = settings["multipart_params"];
chunk = 0;
// When file is loaded start uploading
onComplete = function(e:Event):void {
removeAllListeneres();
var startUpload:Function = function() : void
{
if (chunking) {
chunks = Math.ceil(file._size / chunkSize);
// Force at least 4 chunks to fake progress. We need to fake this since the URLLoader
// doesn't have a upload progress event and we can't use FileReference.upload since it
// doesn't support cookies, breaks on HTTPS and doesn't support custom data so client
// side image resizing will not be possible.
if (chunks < 4 && file._size > 1024 * 32) {
chunkSize = Math.ceil(file._size / 4);
chunks = 4;
}
} else {
// If chunking is disabled then upload file in one huge chunk
chunkSize = file._size;
chunks = 1;
}
// Start uploading the scaled down image
file._multipart = multipart;
file._fileDataName = fileDataName;
file._chunking = chunking;
file._chunk = chunk;
file._chunks = chunks;
file._chunkSize = chunkSize;
file._postvars = postvars;
file.uploadNextChunk();
}
if (/\.(jpeg|jpg|png)$/i.test(file._fileName) && (settings["width"] || settings["height"] || settings["quality"])) {
var image:Image = new Image(file._fileRef.data);
image.addEventListener(ImageEvent.COMPLETE, function(e:ImageEvent) : void
{
image.removeAllEventListeners();
if (image.imageData) {
file._imageData = image.imageData;
file._imageData.position = 0;
file._size = image.imageData.length;
}
startUpload();
});
image.addEventListener(ImageEvent.ERROR, function(e:ImageEvent) : void
{
image.removeAllEventListeners();
file.dispatchEvent(e);
});
image.scale(settings["width"], settings["height"], settings["quality"]);
} else {
startUpload();
}
};
this._fileRef.addEventListener(Event.COMPLETE, onComplete);
// File load IO error
onIOError = function(e:Event):void {
removeAllListeneres();
this.dispatchEvent(e);
};
this._fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
// Start loading local file
this._fileRef.load();
}
/**
* Uploads the next chunk or terminates the upload loop if all chunks are done.
*/
public function uploadNextChunk():Boolean {
var req:URLRequest, fileData:ByteArray, chunkData:ByteArray;
var urlStream:URLStream, url:String, file:File = this;
// All chunks uploaded?
if (this._chunk >= this._chunks) {
// Clean up memory
if(this._fileRef.data) {
this._fileRef.data.clear();
}
this._imageData = null;
return false;
}
// Slice out a chunk
chunkData = new ByteArray();
// Use image data if it exists, will exist if the image was resized
if (this._imageData != null)
fileData = this._imageData;
else
fileData = this._fileRef.data;
fileData.readBytes(chunkData, 0, fileData.position + this._chunkSize > fileData.length ? fileData.length - fileData.position : this._chunkSize);
// Setup URL stream
urlStream = new URLStream();
// Wait for response and dispatch it
urlStream.addEventListener(Event.COMPLETE, function(e:Event):void {
var response:String;
response = urlStream.readUTFBytes(urlStream.bytesAvailable);
// Fake UPLOAD_COMPLETE_DATA event
var uploadChunkEvt:UploadChunkEvent = new UploadChunkEvent(
UploadChunkEvent.UPLOAD_CHUNK_COMPLETE_DATA,
false,
false,
response,
file._chunk,
file._chunks
);
file._chunk++;
dispatchEvent(uploadChunkEvt);
// Fake progress event since Flash doesn't have a progress event for streaming data up to the server
var pe:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS, false, false, fileData.position, file._size);
dispatchEvent(pe);
// Clean up memory
urlStream.close();
chunkData.clear();
});
// Delegate upload IO errors
urlStream.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void {
dispatchEvent(e);
});
// Delegate secuirty errors
urlStream.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(e:SecurityErrorEvent):void {
dispatchEvent(e);
});
// Setup URL
url = this._uploadUrl;
// Add name and chunk/chunks to URL if we use direct streaming method
if (!this._multipart) {
if (url.indexOf('?') == -1)
url += '?';
else
url += '&';
url += "name=" + encodeURIComponent(this._settings["name"]);
if (this._chunking) {
url += "&chunk=" + this._chunk + "&chunks=" + this._chunks;
}
}
// Setup request
req = new URLRequest(url);
req.method = URLRequestMethod.POST;
// Add custom headers
if (this._headers) {
for (var headerName:String in this._headers) {
req.requestHeaders.push(new URLRequestHeader(headerName, this._headers[headerName]));
}
}
// Build multipart request
if (this._multipart) {
var boundary:String = '----pluploadboundary' + new Date().getTime(),
dashdash:String = '--', crlf:String = '\r\n', multipartBlob: ByteArray = new ByteArray();
req.requestHeaders.push(new URLRequestHeader("Content-Type", 'multipart/form-data; boundary=' + boundary));
this._postvars["name"] = this._settings["name"];
// Add chunking parameters if needed
if (this._chunking) {
this._postvars["chunk"] = this._chunk;
this._postvars["chunks"] = this._chunks;
}
// Append mutlipart parameters
for (var name:String in this._postvars) {
multipartBlob.writeUTFBytes(
dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf +
this._postvars[name] + crlf
);
}
// Add file header
multipartBlob.writeUTFBytes(
dashdash + boundary + crlf +
'Content-Disposition: form-data; name="' + this._fileDataName + '"; filename="' + this._fileName + '"' + crlf +
'Content-Type: ' + this._mimeType + crlf + crlf
);
// Add file data
multipartBlob.writeBytes(chunkData, 0, chunkData.length);
// Add file footer
multipartBlob.writeUTFBytes(crlf + dashdash + boundary + dashdash + crlf);
req.data = multipartBlob;
} else {
req.requestHeaders.push(new URLRequestHeader("Content-Type", "application/octet-stream"));
req.data = chunkData;
}
// Make request
urlStream.load(req);
return true;
}
}
}
|
Remove extra clear() operation on SimpleUpload FileReference, causing Plupload to hang in some cases.
|
Flash: Remove extra clear() operation on SimpleUpload FileReference, causing Plupload to hang in some cases.
|
ActionScript
|
agpl-3.0
|
moxiecode/plupload,moxiecode/plupload,envato/plupload,envato/plupload,vitr/fend005-plupload,vitr/fend005-plupload
|
2828276c6aaa0ce85e788fd912bcc831aa7a0487
|
src/justpinegames/Logi/Console.as
|
src/justpinegames/Logi/Console.as
|
package justpinegames.Logi
{
import flash.events.Event;
import flash.desktop.Clipboard;
import flash.desktop.ClipboardFormats;
import flash.utils.getQualifiedClassName;
import feathers.display.Sprite;
import feathers.controls.Button;
import feathers.controls.List;
import feathers.controls.Scroller;
import feathers.controls.renderers.IListItemRenderer;
import feathers.controls.ScrollContainer;
import feathers.controls.text.BitmapFontTextRenderer;
import feathers.core.FeathersControl;
import feathers.data.ListCollection;
import feathers.layout.VerticalLayout;
import feathers.text.BitmapFontTextFormat;
import starling.animation.Tween;
import starling.core.Starling;
import starling.display.Quad;
import starling.events.Event;
import starling.text.BitmapFont;
import starling.textures.TextureSmoothing;
/**
* Main class, used to display console and handle its events.
*/
public class Console extends Sprite
{
private static var _console:Console;
private static var _archiveOfUndisplayedLogs:Array = [];
private var _consoleSettings:ConsoleSettings;
private var _defaultFont:BitmapFont;
private var _format:BitmapFontTextFormat;
private var _formatBackground:BitmapFontTextFormat;
private var _consoleContainer:Sprite;
private var _hudContainer:ScrollContainer;
private var _consoleHeight:Number;
private var _isShown:Boolean;
private var _copyButton:Button;
private var _data:Array;
private var _quad:Quad;
private var _list:List;
private const VERTICAL_PADDING: Number = 5;
private const HORIZONTAL_PADDING: Number = 5;
/**
* You need to create the instance of this class and add it to the stage in order to use this library.
*
* @param consoleSettings Optional parameter which can specify the look and behaviour of the console.
*/
public function Console(consoleSettings:ConsoleSettings = null)
{
_consoleSettings = consoleSettings ? consoleSettings : new ConsoleSettings();
_console = _console ? _console : this;
_data = [];
_defaultFont = new BitmapFont();
_format = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textColor);
_format.letterSpacing = 2;
_formatBackground = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textBackgroundColor);
_formatBackground.letterSpacing = 2;
this.addEventListener(starling.events.Event.ADDED_TO_STAGE, addedToStageHandler);
}
public function get isShown():Boolean
{
return _isShown;
}
public function set isShown(value:Boolean):void
{
if (_isShown == value)
{
return;
}
_isShown = value;
if (_isShown)
{
show();
}
else
{
hide();
}
}
private function addedToStageHandler(e:starling.events.Event):void
{
_consoleHeight = this.stage.stageHeight * _consoleSettings.consoleSize;
_isShown = false;
_consoleContainer = new FeathersControl();
_consoleContainer.alpha = 0;
_consoleContainer.y = -_consoleHeight;
this.addChild(_consoleContainer);
_quad = new Quad(this.stage.stageWidth, _consoleHeight, _consoleSettings.consoleBackground);
_quad.alpha = _consoleSettings.consoleTransparency;
_consoleContainer.addChild(_quad);
// TODO Make the list selection work correctly.
_list = new List();
_list.x = HORIZONTAL_PADDING;
_list.y = VERTICAL_PADDING;
_list.dataProvider = new ListCollection(_data);
_list.itemRendererFactory = function():IListItemRenderer
{
var consoleItemRenderer:ConsoleItemRenderer = new ConsoleItemRenderer(_consoleSettings.textColor, _consoleSettings.highlightColor);
consoleItemRenderer.width = _list.width;
consoleItemRenderer.height = 20;
return consoleItemRenderer;
};
_list.addEventListener(starling.events.Event.CHANGE, copyLine);
_consoleContainer.addChild(_list);
_copyButton = new Button();
_copyButton.label = "Copy All";
_copyButton.addEventListener(starling.events.Event.ADDED, function(e:starling.events.Event):void
{
_copyButton.defaultLabelProperties.smoothing = TextureSmoothing.NONE;
_copyButton.downLabelProperties.smoothing = TextureSmoothing.NONE;
_copyButton.defaultLabelProperties.textFormat = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textColor);
_copyButton.downLabelProperties.textFormat = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.highlightColor);
_copyButton.stateToSkinFunction = function(target:Object, state:Object, oldValue:Object = null):Object
{
return null;
};
_copyButton.width = 150;
_copyButton.height = 40;
});
_copyButton.addEventListener(starling.events.Event.SELECT, copy);
_consoleContainer.addChild(_copyButton);
_hudContainer = new ScrollContainer();
// TODO This should be changed to prevent the hud from even creating, not just making it invisible.
if (!_consoleSettings.hudEnabled)
{
_hudContainer.visible = false;
}
_hudContainer.x = HORIZONTAL_PADDING;
_hudContainer.y = VERTICAL_PADDING;
_hudContainer.touchable = false;
_hudContainer.layout = new VerticalLayout();
_hudContainer.scrollerProperties.verticalScrollPolicy = Scroller.SCROLL_POLICY_OFF;
this.addChild(_hudContainer);
this.setScreenSize(Starling.current.nativeStage.stageWidth, Starling.current.nativeStage.stageHeight);
for each (var undisplayedMessage:* in _archiveOfUndisplayedLogs)
{
this.logMessage(undisplayedMessage);
}
_archiveOfUndisplayedLogs = [];
Starling.current.nativeStage.addEventListener(flash.events.Event.RESIZE, function(e:flash.events.Event):void
{
setScreenSize(Starling.current.nativeStage.stageWidth, Starling.current.nativeStage.stageHeight);
});
}
private function setScreenSize(width:Number, height:Number):void
{
_consoleContainer.width = width;
_consoleContainer.height = height;
_consoleHeight = height * _consoleSettings.consoleSize;
_quad.width = width;
_quad.height = _consoleHeight;
_copyButton.x = width - 110 - HORIZONTAL_PADDING;
_copyButton.y = _consoleHeight - 33 - VERTICAL_PADDING;
_list.width = this.stage.stageWidth - HORIZONTAL_PADDING * 2;
_list.height = _consoleHeight - VERTICAL_PADDING * 2;
if (!_isShown)
{
_consoleContainer.y = -_consoleHeight;
}
}
private function show():void
{
_consoleContainer.visible = true;
var __tween1:Tween = new Tween(_consoleContainer, _consoleSettings.animationTime);
__tween1.animate("y", 0);
__tween1.fadeTo(1);
Starling.juggler.add(__tween1);
var __tween2:Tween = new Tween(_hudContainer, _consoleSettings.animationTime);
__tween2.fadeTo(0);
Starling.juggler.add(__tween2);
_isShown = true;
}
private function hide():void
{
var __tween1:Tween = new Tween(_consoleContainer, _consoleSettings.animationTime);
__tween1.animate("y", -_consoleHeight);
__tween1.fadeTo(0);
__tween1.onComplete = function():void
{
_consoleContainer.visible = false;
};
Starling.juggler.add(__tween1);
var __tween2:Tween = new Tween(_hudContainer, _consoleSettings.animationTime);
__tween2.fadeTo(1);
Starling.juggler.add(__tween2);
_isShown = false;
}
private function copyLine(list:List):void
{
//log(list.selectedItem.data);
}
/**
* You can use this data to save a log to the file.
*
* @return Log messages joined into a String with new lines.
*/
public function getLogData():String
{
var text:String = "";
for each (var object:Object in _data)
{
text += object.data + "\n";
}
return text;
}
private function copy(button:Button):void
{
var text:String = this.getLogData();
Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, text);
}
/**
* Displays the message string in the console, or on the HUD if the console is hidden.
*
* @param message String to display
*/
public function logMessage(message:String):void
{
if (_consoleSettings.traceEnabled)
{
trace(message);
}
var labelDisplay: String = (new Date()).toLocaleTimeString() + ": " + message;
_list.dataProvider.push({label: labelDisplay, data: message});
var createLabel:Function = function(text:String, format:BitmapFontTextFormat):BitmapFontTextRenderer
{
var label:BitmapFontTextRenderer = new BitmapFontTextRenderer();
label.addEventListener(starling.events.Event.ADDED, function(e:starling.events.Event):void
{
label.textFormat = format;
});
label.smoothing = TextureSmoothing.NONE;
label.text = text;
label.validate();
return label;
};
var hudLabelContainer:FeathersControl = new FeathersControl();
hudLabelContainer.width = 640;
hudLabelContainer.height = 20;
var addBackground:Function = function(offsetX:int, offsetY: int):void
{
var hudLabelBackground:BitmapFontTextRenderer = createLabel(message, _formatBackground);
hudLabelBackground.x = offsetX;
hudLabelBackground.y = offsetY;
hudLabelContainer.addChild(hudLabelBackground);
};
addBackground(0, 0);
addBackground(2, 0);
addBackground(0, 2);
addBackground(2, 2);
var hudLabel:BitmapFontTextRenderer = createLabel(message, _format);
hudLabel.x += 1;
hudLabel.y += 1;
hudLabelContainer.addChild(hudLabel);
_hudContainer.addChildAt(hudLabelContainer, 0);
var __tween1:Tween = new Tween(hudLabelContainer, _consoleSettings.hudMessageFadeOutTime);
__tween1.delay = _consoleSettings.hudMessageDisplayTime
__tween1.fadeTo(0);
__tween1.onComplete = function():void
{
_hudContainer.removeChild(hudLabelContainer);
};
Starling.juggler.add(__tween1);
// TODO use the correct API, currently there is a problem with List max vertical position. A bug in foxhole?
_list.verticalScrollPosition = Math.max(_list.dataProvider.length * 20 - _list.height, 0);
}
/**
* Returns the fist created Console instance.
*
* @return Console instance
*/
public static function getMainConsoleInstance():Console
{
return _console;
}
/**
* Main log function. Usage is the same as for the trace statement.
*
* For data sent to the log function to be displayed, you need to first create a LogConsole instance, and add it to the Starling stage.
*
* @param ... arguments Variable number of arguments, which will be displayed in the log
*/
public static function staticLogMessage(... arguments):void
{
var message:String = "";
var firstTime:Boolean = true;
for each (var argument:* in arguments)
{
var description:String;
if (argument == null)
{
description = "[null]"
}
else if (!("toString" in argument))
{
description = "[object " + getQualifiedClassName(argument) + "]";
}
else
{
description = argument;
}
if (firstTime)
{
message = description;
firstTime = false;
}
else
{
message += ", " + description;
}
}
if (Console.getMainConsoleInstance() == null)
{
_archiveOfUndisplayedLogs.push(message);
}
else
{
Console.getMainConsoleInstance().logMessage(message);
}
}
}
}
|
package justpinegames.Logi
{
import flash.desktop.Clipboard;
import flash.desktop.ClipboardFormats;
import flash.utils.getQualifiedClassName;
import feathers.display.Sprite;
import feathers.controls.Button;
import feathers.controls.List;
import feathers.controls.Scroller;
import feathers.controls.renderers.IListItemRenderer;
import feathers.controls.ScrollContainer;
import feathers.controls.text.BitmapFontTextRenderer;
import feathers.core.FeathersControl;
import feathers.data.ListCollection;
import feathers.layout.VerticalLayout;
import feathers.text.BitmapFontTextFormat;
import starling.animation.Tween;
import starling.core.Starling;
import starling.display.Quad;
import starling.events.Event;
import starling.events.ResizeEvent;
import starling.text.BitmapFont;
import starling.textures.TextureSmoothing;
/**
* Main class, used to display console and handle its events.
*/
public class Console extends Sprite
{
private static var _console:Console;
private static var _archiveOfUndisplayedLogs:Array = [];
private var _consoleSettings:ConsoleSettings;
private var _defaultFont:BitmapFont;
private var _format:BitmapFontTextFormat;
private var _formatBackground:BitmapFontTextFormat;
private var _consoleContainer:Sprite;
private var _hudContainer:ScrollContainer;
private var _consoleHeight:Number;
private var _isShown:Boolean;
private var _copyButton:Button;
private var _data:Array;
private var _quad:Quad;
private var _list:List;
private const VERTICAL_PADDING: Number = 5;
private const HORIZONTAL_PADDING: Number = 5;
/**
* You need to create the instance of this class and add it to the stage in order to use this library.
*
* @param consoleSettings Optional parameter which can specify the look and behaviour of the console.
*/
public function Console(consoleSettings:ConsoleSettings = null)
{
_consoleSettings = consoleSettings ? consoleSettings : new ConsoleSettings();
_console = _console ? _console : this;
_data = [];
_defaultFont = new BitmapFont();
_format = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textColor);
_format.letterSpacing = 2;
_formatBackground = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textBackgroundColor);
_formatBackground.letterSpacing = 2;
this.addEventListener(starling.events.Event.ADDED_TO_STAGE, addedToStageHandler);
}
public function get isShown():Boolean
{
return _isShown;
}
public function set isShown(value:Boolean):void
{
if (_isShown == value)
{
return;
}
_isShown = value;
if (_isShown)
{
show();
}
else
{
hide();
}
}
private function addedToStageHandler(e:Event):void
{
_consoleHeight = this.stage.stageHeight * _consoleSettings.consoleSize;
_isShown = false;
_consoleContainer = new FeathersControl();
_consoleContainer.alpha = 0;
_consoleContainer.y = -_consoleHeight;
this.addChild(_consoleContainer);
_quad = new Quad(this.stage.stageWidth, _consoleHeight, _consoleSettings.consoleBackground);
_quad.alpha = _consoleSettings.consoleTransparency;
_consoleContainer.addChild(_quad);
// TODO Make the list selection work correctly.
_list = new List();
_list.x = HORIZONTAL_PADDING;
_list.y = VERTICAL_PADDING;
_list.dataProvider = new ListCollection(_data);
_list.itemRendererFactory = function():IListItemRenderer
{
var consoleItemRenderer:ConsoleItemRenderer = new ConsoleItemRenderer(_consoleSettings.textColor, _consoleSettings.highlightColor);
consoleItemRenderer.width = _list.width;
consoleItemRenderer.height = 20;
return consoleItemRenderer;
};
_list.addEventListener(Event.CHANGE, copyLine);
_consoleContainer.addChild(_list);
_copyButton = new Button();
_copyButton.label = "Copy All";
_copyButton.addEventListener(Event.ADDED, function(e:Event):void
{
_copyButton.defaultLabelProperties.smoothing = TextureSmoothing.NONE;
_copyButton.downLabelProperties.smoothing = TextureSmoothing.NONE;
_copyButton.defaultLabelProperties.textFormat = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.textColor);
_copyButton.downLabelProperties.textFormat = new BitmapFontTextFormat(_defaultFont, 16, _consoleSettings.highlightColor);
_copyButton.stateToSkinFunction = function(target:Object, state:Object, oldValue:Object = null):Object
{
return null;
};
_copyButton.width = 150;
_copyButton.height = 40;
});
_copyButton.addEventListener(Event.SELECT, copy);
_consoleContainer.addChild(_copyButton);
_hudContainer = new ScrollContainer();
// TODO This should be changed to prevent the hud from even creating, not just making it invisible.
if (!_consoleSettings.hudEnabled)
{
_hudContainer.visible = false;
}
_hudContainer.x = HORIZONTAL_PADDING;
_hudContainer.y = VERTICAL_PADDING;
_hudContainer.touchable = false;
_hudContainer.layout = new VerticalLayout();
_hudContainer.scrollerProperties.verticalScrollPolicy = Scroller.SCROLL_POLICY_OFF;
this.addChild(_hudContainer);
this.setScreenSize(Starling.current.nativeStage.stageWidth, Starling.current.nativeStage.stageHeight);
for each (var undisplayedMessage:* in _archiveOfUndisplayedLogs)
{
this.logMessage(undisplayedMessage);
}
_archiveOfUndisplayedLogs = [];
stage.addEventListener(ResizeEvent.RESIZE, function(e:ResizeEvent):void
{
setScreenSize(stage.stageWidth, stage.stageHeight);
});
}
private function setScreenSize(width:Number, height:Number):void
{
_consoleContainer.width = width;
_consoleContainer.height = height;
_consoleHeight = height * _consoleSettings.consoleSize;
_quad.width = width;
_quad.height = _consoleHeight;
_copyButton.x = width - 110 - HORIZONTAL_PADDING;
_copyButton.y = _consoleHeight - 33 - VERTICAL_PADDING;
_list.width = this.stage.stageWidth - HORIZONTAL_PADDING * 2;
_list.height = _consoleHeight - VERTICAL_PADDING * 2;
if (!_isShown)
{
_consoleContainer.y = -_consoleHeight;
}
}
private function show():void
{
_consoleContainer.visible = true;
var __tween1:Tween = new Tween(_consoleContainer, _consoleSettings.animationTime);
__tween1.animate("y", 0);
__tween1.fadeTo(1);
Starling.juggler.add(__tween1);
var __tween2:Tween = new Tween(_hudContainer, _consoleSettings.animationTime);
__tween2.fadeTo(0);
Starling.juggler.add(__tween2);
_isShown = true;
}
private function hide():void
{
var __tween1:Tween = new Tween(_consoleContainer, _consoleSettings.animationTime);
__tween1.animate("y", -_consoleHeight);
__tween1.fadeTo(0);
__tween1.onComplete = function():void
{
_consoleContainer.visible = false;
};
Starling.juggler.add(__tween1);
var __tween2:Tween = new Tween(_hudContainer, _consoleSettings.animationTime);
__tween2.fadeTo(1);
Starling.juggler.add(__tween2);
_isShown = false;
}
private function copyLine(list:List):void
{
//log(list.selectedItem.data);
}
/**
* You can use this data to save a log to the file.
*
* @return Log messages joined into a String with new lines.
*/
public function getLogData():String
{
var text:String = "";
for each (var object:Object in _data)
{
text += object.data + "\n";
}
return text;
}
private function copy(button:Button):void
{
var text:String = this.getLogData();
Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, text);
}
/**
* Displays the message string in the console, or on the HUD if the console is hidden.
*
* @param message String to display
*/
public function logMessage(message:String):void
{
if (_consoleSettings.traceEnabled)
{
trace(message);
}
var labelDisplay: String = (new Date()).toLocaleTimeString() + ": " + message;
_list.dataProvider.push({label: labelDisplay, data: message});
var createLabel:Function = function(text:String, format:BitmapFontTextFormat):BitmapFontTextRenderer
{
var label:BitmapFontTextRenderer = new BitmapFontTextRenderer();
label.addEventListener(Event.ADDED, function(e:Event):void
{
label.textFormat = format;
});
label.smoothing = TextureSmoothing.NONE;
label.text = text;
label.validate();
return label;
};
var hudLabelContainer:FeathersControl = new FeathersControl();
hudLabelContainer.width = 640;
hudLabelContainer.height = 20;
var addBackground:Function = function(offsetX:int, offsetY: int):void
{
var hudLabelBackground:BitmapFontTextRenderer = createLabel(message, _formatBackground);
hudLabelBackground.x = offsetX;
hudLabelBackground.y = offsetY;
hudLabelContainer.addChild(hudLabelBackground);
};
addBackground(0, 0);
addBackground(2, 0);
addBackground(0, 2);
addBackground(2, 2);
var hudLabel:BitmapFontTextRenderer = createLabel(message, _format);
hudLabel.x += 1;
hudLabel.y += 1;
hudLabelContainer.addChild(hudLabel);
_hudContainer.addChildAt(hudLabelContainer, 0);
var __tween1:Tween = new Tween(hudLabelContainer, _consoleSettings.hudMessageFadeOutTime);
__tween1.delay = _consoleSettings.hudMessageDisplayTime
__tween1.fadeTo(0);
__tween1.onComplete = function():void
{
_hudContainer.removeChild(hudLabelContainer);
};
Starling.juggler.add(__tween1);
// TODO use the correct API, currently there is a problem with List max vertical position. A bug in foxhole?
_list.verticalScrollPosition = Math.max(_list.dataProvider.length * 20 - _list.height, 0);
}
/**
* Returns the fist created Console instance.
*
* @return Console instance
*/
public static function getMainConsoleInstance():Console
{
return _console;
}
/**
* Main log function. Usage is the same as for the trace statement.
*
* For data sent to the log function to be displayed, you need to first create a LogConsole instance, and add it to the Starling stage.
*
* @param ... arguments Variable number of arguments, which will be displayed in the log
*/
public static function staticLogMessage(... arguments):void
{
var message:String = "";
var firstTime:Boolean = true;
for each (var argument:* in arguments)
{
var description:String;
if (argument == null)
{
description = "[null]"
}
else if (!("toString" in argument))
{
description = "[object " + getQualifiedClassName(argument) + "]";
}
else
{
description = argument;
}
if (firstTime)
{
message = description;
firstTime = false;
}
else
{
message += ", " + description;
}
}
if (Console.getMainConsoleInstance() == null)
{
_archiveOfUndisplayedLogs.push(message);
}
else
{
Console.getMainConsoleInstance().logMessage(message);
}
}
}
}
|
Update src/justpinegames/Logi/Console.as
|
Update src/justpinegames/Logi/Console.as
Removed flash.display.Events and used starling.events.Event instead
|
ActionScript
|
mit
|
justpinegames/Logi,justpinegames/Logi
|
7231d7ad7b9679f88a809afa3677fa8486e418a1
|
src/net/manaca/tracking/Tracking.as
|
src/net/manaca/tracking/Tracking.as
|
package net.manaca.tracking
{
import net.manaca.data.Set;
import net.manaca.tracking.sender.ITrackingSender;
/**
*
* @author Sean
*
*/
public class Tracking
{
//==========================================================================
// Class variables
//==========================================================================
static private const senderList:Set = new Set();
//==========================================================================
// Class methods
//==========================================================================
/**
* Do the tracking.
*
* @param action The value to track.
* @param rest Additional parameters.
*/
static public function action(action:String, ... rest):void
{
var list:Array = senderList.toArray();
for each (var sender:ITrackingSender in list)
{
sender.externalTrack(action, rest);
}
}
/**
* Add a sender.
*
* @param sender The sender to add.
*/
static public function addSender(sender:ITrackingSender):void
{
senderList.add(sender);
}
/**
* Remove a sender.
*
* @param sender The sender to remove.
*/
static public function removeSender(sender:ITrackingSender):void
{
senderList.remove(sender);
}
}
}
|
package net.manaca.tracking
{
import net.manaca.tracking.sender.ITrackingSender;
import net.manaca.utils.ArrayUtil;
/**
*
* @author Sean
*
*/
public class Tracking
{
//==========================================================================
// Class variables
//==========================================================================
static private const senderList:Array = [];
//==========================================================================
// Class methods
//==========================================================================
/**
* Do the tracking.
*
* @param action The value to track.
* @param rest Additional parameters.
*/
static public function action(action:String, ... rest):void
{
for each (var sender:ITrackingSender in senderList)
{
sender.externalTrack(action, rest);
}
}
/**
* Add a sender.
*
* @param sender The sender to add.
*/
static public function addSender(sender:ITrackingSender):void
{
senderList.push(sender);
}
/**
* Remove a sender.
*
* @param sender The sender to remove.
*/
static public function removeSender(sender:ITrackingSender):void
{
ArrayUtil.removeValueFromArray(senderList, sender);
}
}
}
|
change senderList type to Array
|
change senderList type to Array
|
ActionScript
|
mit
|
wersling/manaca,wersling/manaca
|
c0790dddb141ef9e05355c59904e4b0f9859286e
|
actionscript-cafe/src/main/flex/org/servebox/cafe/core/layout/impl/DelegateLayoutArea.as
|
actionscript-cafe/src/main/flex/org/servebox/cafe/core/layout/impl/DelegateLayoutArea.as
|
package org.servebox.cafe.core.layout.impl
{
import flash.events.Event;
import flash.events.IEventDispatcher;
import mx.collections.ArrayCollection;
import mx.core.IVisualElementContainer;
import mx.events.ChildExistenceChangedEvent;
import mx.events.FlexEvent;
import org.flexunit.internals.namespaces.classInternal;
import org.servebox.cafe.core.Container;
import org.servebox.cafe.core.layout.ILayoutArea;
import org.servebox.cafe.core.layout.ILayoutAreaManager;
import org.servebox.cafe.core.signal.SignalAggregator;
import org.servebox.cafe.core.view.IView;
import spark.events.ElementExistenceEvent;
public class DelegateLayoutArea implements ILayoutArea
{
private var _container : IVisualElementContainer;
private var _views : Vector.<IView> = new Vector.<IView>();
private var _name : String;
public function DelegateLayoutArea( container : IVisualElementContainer = null )
{
this.container = container;
}
public function add(view:IView):void
{
cleanAllViews();
IEventDispatcher( container ).addEventListener( ElementExistenceEvent.ELEMENT_ADD, viewCreationCompleteHandler );
_views.push( view );
container.addElement( view );
}
protected function cleanAllViews() : void
{
container.removeAllElements();
_views = new Vector.<IView>();
}
protected function viewCreationCompleteHandler( event : ElementExistenceEvent ) : void
{
trace("SIGNAL : " + Object(event.element).className + "_LOADED");
Container.getInstance().signalAggregator.signal( Object(event.element).className + "_LOADED" );
IEventDispatcher( container ).removeEventListener( ElementExistenceEvent.ELEMENT_ADD, viewCreationCompleteHandler );
}
public function remove(view:IView):void
{
container.removeElement( view );
for(var i : int = 0; i < _views.length; i++ )
{
if( _views[i] == view )
{
_views.splice( i, 1 );
break;
}
}
}
public function getViews() : ArrayCollection
{
var viewList : ArrayCollection = new ArrayCollection();
for each ( var view : IView in _views )
{
viewList.addItem(view);
}
return viewList;
}
[Bindable]
public function set container( value : IVisualElementContainer ) : void
{
_container = value;
if( value && name )
{
register();
}
}
public function get container() : IVisualElementContainer
{
return _container;
}
[Bindable]
public function get name() : String
{
return _name;
}
public function set name( value : String ): void
{
_name = value;
if( value && name )
{
register();
}
}
private function register() : void
{
var manager : ILayoutAreaManager = Container.getInstance().getLayoutAreaManager();
manager.addArea( name, this );
}
}
}
|
package org.servebox.cafe.core.layout.impl
{
import flash.events.IEventDispatcher;
import mx.collections.ArrayCollection;
import mx.core.IVisualElementContainer;
import org.servebox.cafe.core.Container;
import org.servebox.cafe.core.layout.ILayoutArea;
import org.servebox.cafe.core.layout.ILayoutAreaManager;
import org.servebox.cafe.core.view.IView;
import spark.events.ElementExistenceEvent;
public class DelegateLayoutArea implements ILayoutArea
{
private var _container : IVisualElementContainer;
private var _views : Vector.<IView> = new Vector.<IView>();
private var _name : String;
public function DelegateLayoutArea( container : IVisualElementContainer = null )
{
this.container = container;
}
public function add(view:IView):void
{
cleanAllViews();
IEventDispatcher( container ).addEventListener( ElementExistenceEvent.ELEMENT_ADD, viewCreationCompleteHandler );
_views.push( view );
container.addElement( view );
}
protected function cleanAllViews() : void
{
container.removeAllElements();
_views = new Vector.<IView>();
}
protected function viewCreationCompleteHandler( event : ElementExistenceEvent ) : void
{
trace("SIGNAL : " + Object(event.element).className + "_LOADED");
Container.getInstance().signalAggregator.signal( Object(event.element).className + "_LOADED" );
IEventDispatcher( container ).removeEventListener( ElementExistenceEvent.ELEMENT_ADD, viewCreationCompleteHandler );
}
public function remove(view:IView):void
{
container.removeElement( view );
for(var i : int = 0; i < _views.length; i++ )
{
if( _views[i] == view )
{
_views.splice( i, 1 );
break;
}
}
}
public function getViews() : ArrayCollection
{
var viewList : ArrayCollection = new ArrayCollection();
for each ( var view : IView in _views )
{
viewList.addItem(view);
}
return viewList;
}
[Bindable]
public function set container( value : IVisualElementContainer ) : void
{
_container = value;
if( value && name )
{
register();
}
}
public function get container() : IVisualElementContainer
{
return _container;
}
[Bindable]
public function get name() : String
{
return _name;
}
public function set name( value : String ): void
{
_name = value;
if( value && name )
{
register();
}
}
private function register() : void
{
var manager : ILayoutAreaManager = Container.getInstance().getLayoutAreaManager();
manager.addArea( name, this );
}
}
}
|
Fix import.
|
Fix import.
|
ActionScript
|
mit
|
servebox/as-cafe
|
6080c4994a4ddaa5c03414059b5a1b73188b22b0
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.display.MiracleImage;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler():void {
if(_model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler)
_model.viewerInput.browseForOpen("Open file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
var name:String = asset.name;
Miracle.createScene(new <Asset>[asset], 1);
Miracle.currentScene.createImage(name)
.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
Miracle.resume();
}
private function imageAddedToStage(event:Event):void {
var target:MiracleImage = event.target as MiracleImage;
target.moveTO(
this.stage.stageWidth - target.width >> 1,
this.stage.stageHeight - target.height >> 1
);
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.display.MiracleImage;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TEXTURE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose mesh");
var list:List = new List(_window, 0, 0, this.getTexture(asset.output));
_window.x = this.stage.stageWidth - _window.width >> 1;
_window.y = this.stage.stageHeight - _window.height >> 1;
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
}
private function getTexture(bytes:ByteArray):Array {
var result:Array = [1, 2, 3];
return result;
}
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [1, 2, 3];
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
_assets.push(new Asset(_model.viewerInput.name, byteArray));
// var name:String = asset.name;
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets, 1);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
list.removeEventListener(event.type, this.selectAnimationHandler);
log(this, "selectAnimationHandler", list.selectedItem);
this.removeChild(_window);
_window = null;
//add animation to miracle
var name:String = list.selectedItem.toString();
Miracle.currentScene.createImage(name)
.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
}
private function imageAddedToStage(event:Event):void {
var target:MiracleImage = event.target as MiracleImage;
target.moveTO(
this.stage.stageWidth - target.width >> 1,
this.stage.stageHeight - target.height >> 1
);
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
change viewer
|
change viewer
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
7f53793e6ec36cf47a4f771c73c37de34c1d73b8
|
HLSPlugin/src/com/kaltura/hls/m2ts/FLVTranscoder.as
|
HLSPlugin/src/com/kaltura/hls/m2ts/FLVTranscoder.as
|
package com.kaltura.hls.m2ts
{
import flash.utils.ByteArray;
import flash.net.ObjectEncoding;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
/**
* Responsible for emitting FLV data. Also handles AAC conversion
* config and buffering.
*/
public class FLVTranscoder
{
public const MIN_FILE_HEADER_BYTE_COUNT:int = 9;
public var callback:Function;
private var lastTagSize:uint = 0;
private var _aacConfig:ByteArray;
private var _aacRemainder:ByteArray;
private var _aacTimestamp:Number = 0;
public function clear(clearAACConfig:Boolean = false):void
{
if(clearAACConfig)
_aacConfig = null;
_aacRemainder = null;
_aacTimestamp = 0;
}
private static var tag:ByteArray = new ByteArray();
private function sendFLVTag(flvts:uint, type:uint, codec:int, mode:int, bytes:ByteArray, offset:uint, length:uint):void
{
tag.position = 0;
var msgLength:uint = length + ((codec >= 0) ? 1 : 0) + ((mode >= 0) ? 1 : 0);
var cursor:uint = 0;
if(msgLength > 0xffffff)
return; // too big for the length field
tag.length = FLVTags.HEADER_LENGTH + msgLength;
tag[cursor++] = type;
tag[cursor++] = (msgLength >> 16) & 0xff;
tag[cursor++] = (msgLength >> 8) & 0xff;
tag[cursor++] = (msgLength ) & 0xff;
tag[cursor++] = (flvts >> 16) & 0xff;
tag[cursor++] = (flvts >> 8) & 0xff;
tag[cursor++] = (flvts ) & 0xff;
tag[cursor++] = (flvts >> 24) & 0xff;
tag[cursor++] = 0x00; // stream ID
tag[cursor++] = 0x00;
tag[cursor++] = 0x00;
if(codec >= 0)
tag[cursor++] = codec;
if(mode >= 0)
tag[cursor++] = mode;
tag.position = cursor;
tag.writeBytes(bytes, offset, length);
cursor += length;
msgLength += 11; // account for message header in back pointer
tag.writeUnsignedInt(lastTagSize);
// Dispatch tag.
if(callback != null)
callback(flvts, tag);
lastTagSize = tag.length;
}
public function convertFLVTimestamp(pts:Number):Number
{
return pts / 90.0;
}
private static var flvGenerationBuffer:ByteArray = new ByteArray();
/**
* Convert and amit AVC NALU data.
*/
public function convert(unit:NALU):void
{
// Emit an AVCC.
var avcc:ByteArray = NALUProcessor.extractAVCC(unit);
if(avcc)
sendFLVTag(convertFLVTimestamp(unit.pts), FLVTags.TYPE_VIDEO, FLVTags.VIDEO_CODEC_AVC_KEYFRAME, FLVTags.AVC_MODE_AVCC, avcc, 0, avcc.length);
// Accumulate NALUs into buffer.
flvGenerationBuffer.length = 3;
flvGenerationBuffer[0] = (tsu >> 16) & 0xff;
flvGenerationBuffer[1] = (tsu >> 8) & 0xff;
flvGenerationBuffer[2] = (tsu ) & 0xff;
flvGenerationBuffer.position = 3;
// Check keyframe status.
var keyFrame:Boolean = false;
var totalAppended:int = 0;
NALUProcessor.walkNALUs(unit.buffer, 0, function(bytes:ByteArray, cursor:uint, length:uint):void
{
// Check for a NALU that is keyframe type.
var naluType:uint = bytes[cursor] & 0x1f;
//trace(naluType + " length=" + length);
switch(naluType)
{
case 0x09: // "access unit delimiter"
switch((bytes[cursor + 1] >> 5) & 0x07) // access unit type
{
case 0:
case 3:
case 5:
keyFrame = true;
break;
default:
keyFrame = false;
break;
}
break;
default:
// Infer keyframe state.
if(naluType == 5)
keyFrame = true;
else if(naluType == 1)
keyFrame = false;
}
// Append.
flvGenerationBuffer.writeUnsignedInt(length);
flvGenerationBuffer.writeBytes(bytes, cursor, length);
totalAppended += length;
}, true );
var flvts:uint = convertFLVTimestamp(unit.pts);
var tsu:uint = convertFLVTimestamp(unit.pts - unit.dts);
var codec:uint;
if(keyFrame)
codec = FLVTags.VIDEO_CODEC_AVC_KEYFRAME;
else
codec = FLVTags.VIDEO_CODEC_AVC_PREDICTIVEFRAME;
//trace("ts=" + flvts + " tsu=" + tsu + " keyframe = " + keyFrame);
sendFLVTag(flvts, FLVTags.TYPE_VIDEO, codec, FLVTags.AVC_MODE_PICTURE, flvGenerationBuffer, 0, flvGenerationBuffer.length);
}
private function compareBytesHelper(b1:ByteArray, b2:ByteArray):Boolean
{
var curPos:uint;
if(b1.length != b2.length)
return false;
for(curPos = 0; curPos < b1.length; curPos++)
{
if(b1[curPos] != b2[curPos])
return false;
}
return true;
}
private function sendAACConfigFLVTag(flvts:uint, profile:uint, sampleRateIndex:uint, channelConfig:uint):void
{
var isNewConfig:Boolean = true;
var audioSpecificConfig:ByteArray = new ByteArray();
var audioObjectType:uint;
audioSpecificConfig.length = 2;
switch(profile)
{
case 0x00:
audioObjectType = 0x01;
break;
case 0x01:
audioObjectType = 0x02;
break;
case 0x02:
audioObjectType = 0x03;
break;
default:
return;
}
audioSpecificConfig[0] = ((audioObjectType << 3) & 0xf8) + ((sampleRateIndex >> 1) & 0x07);
audioSpecificConfig[1] = ((sampleRateIndex << 7) & 0x80) + ((channelConfig << 3) & 0x78);
if(_aacConfig && compareBytesHelper(_aacConfig, audioSpecificConfig))
isNewConfig = false;
if(!isNewConfig)
return;
_aacConfig = audioSpecificConfig;
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_CONFIG, _aacConfig, 0, _aacConfig.length);
}
/**
* Convert and amit AAC data.
*/
public function convertAAC(pes:PESPacket):void
{
var timeAccumulation:Number = 0.0;
var limit:uint;
var stream:ByteArray;
var hadRemainder:Boolean = false;
var cursor:int = 0;
var length:int = pes.buffer.length;
var bytes:ByteArray = pes.buffer;
var timestamp:Number = pes.pts;
if(_aacRemainder)
{
stream = _aacRemainder;
stream.writeBytes(bytes, cursor, length);
cursor = 0;
length = stream.length;
_aacRemainder = null;
hadRemainder = true;
timeAccumulation = _aacTimestamp - timestamp;
}
else
stream = bytes;
limit = cursor + length;
// an AAC PES packet can contain multiple ADTS frames
while(cursor < limit)
{
var remaining:uint = limit - cursor;
var sampleRateIndex:uint;
var sampleRate:Number = undefined;
var profile:uint;
var channelConfig:uint;
var frameLength:uint;
if(remaining < FLVTags.ADTS_FRAME_HEADER_LENGTH)
break;
// search for syncword
if(stream[cursor] != 0xff || (stream[cursor + 1] & 0xf0) != 0xf0)
{
cursor++;
continue;
}
frameLength = (stream[cursor + 3] & 0x03) << 11;
frameLength += (stream[cursor + 4]) << 3;
frameLength += (stream[cursor + 5] >> 5) & 0x07;
// Check for an invalid ADTS header; if so look for next syncword.
if(frameLength < FLVTags.ADTS_FRAME_HEADER_LENGTH)
{
cursor++;
continue;
}
// Skip it till next PES packet.
if(frameLength > remaining)
break;
profile = (stream[cursor + 2] >> 6) & 0x03;
sampleRateIndex = (stream[cursor + 2] >> 2) & 0x0f;
switch(sampleRateIndex)
{
case 0x00:
sampleRate = 96000.0;
break;
case 0x01:
sampleRate = 88200.0;
break;
case 0x02:
sampleRate = 64000.0;
break;
case 0x03:
sampleRate = 48000.0;
break;
case 0x04:
sampleRate = 44100.0;
break;
case 0x05:
sampleRate = 32000.0;
break;
case 0x06:
sampleRate = 24000.0;
break;
case 0x07:
sampleRate = 22050.0;
break;
case 0x08:
sampleRate = 16000.0;
break;
case 0x09:
sampleRate = 12000.0;
break;
case 0x0a:
sampleRate = 11025.0;
break;
case 0x0b:
sampleRate = 8000.0;
break;
case 0x0c:
sampleRate = 7350.0;
break;
}
channelConfig = ((stream[cursor + 2] & 0x01) << 2) + ((stream[cursor + 3] >> 6) & 0x03);
if(sampleRate)
{
var flvts:uint = convertFLVTimestamp(timestamp + timeAccumulation);
sendAACConfigFLVTag(flvts, profile, sampleRateIndex, channelConfig);
//trace("Sending AAC");
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_FRAME, stream, cursor + FLVTags.ADTS_FRAME_HEADER_LENGTH, frameLength - FLVTags.ADTS_FRAME_HEADER_LENGTH);
timeAccumulation += (1024.0 / sampleRate) * 90000.0; // account for the duration of this frame
if(hadRemainder)
{
timeAccumulation = 0.0;
hadRemainder = false;
}
}
cursor += frameLength;
}
if(cursor < limit)
{
//trace("AAC timestamp was " + _aacTimestamp);
_aacRemainder = new ByteArray();
_aacRemainder.writeBytes(stream, cursor, limit - cursor);
_aacTimestamp = timestamp + timeAccumulation;
//trace("AAC timestamp now " + _aacTimestamp);
}
}
/**
* Convert and amit MP3 data.
*/
public function convertMP3(pes:PESPacket):void
{
sendFLVTag(convertFLVTimestamp(pes.pts), FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_MP3, -1, pes.buffer, 0, pes.buffer.length);
}
private function generateScriptData(values:Array):ByteArray
{
var bytes:ByteArray = new ByteArray();
bytes.objectEncoding = ObjectEncoding.AMF0;
for each (var object:Object in values)
bytes.writeObject(object);
return bytes;
}
private function sendScriptDataFLVTag(flvts:uint, values:Array):void
{
var bytes:ByteArray = generateScriptData(values);
sendFLVTag(flvts, FLVTags.TYPE_SCRIPTDATA, -1, -1, bytes, 0, bytes.length);
}
/**
* Fire off a subtitle caption.
*/
public function createAndSendCaptionMessage( timeStamp:Number, captionBuffer:String, lang:String="", textid:Number=99):void
{
var captionObject:Array = ["onCaptionInfo", { type:"WebVTT", data:captionBuffer }];
//sendScriptDataFLVTag( timeStamp * 1000, captionObject);
// We need to strip the timestamp off of the text data
captionBuffer = captionBuffer.slice(captionBuffer.indexOf('\n') + 1);
var subtitleObject:Array = ["onTextData", { text:captionBuffer, language:lang, trackid:textid }];
sendScriptDataFLVTag( timeStamp * 1000, subtitleObject);
}
}
}
|
package com.kaltura.hls.m2ts
{
import flash.utils.ByteArray;
import flash.net.ObjectEncoding;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
/**
* Responsible for emitting FLV data. Also handles AAC conversion
* config and buffering.
*/
public class FLVTranscoder
{
public const MIN_FILE_HEADER_BYTE_COUNT:int = 9;
public var callback:Function;
private var lastTagSize:uint = 0;
private var _aacConfig:ByteArray;
private var _aacRemainder:ByteArray;
private var _aacTimestamp:Number = 0;
public function clear(clearAACConfig:Boolean = false):void
{
if(clearAACConfig)
_aacConfig = null;
_aacRemainder = null;
_aacTimestamp = 0;
}
private function sendFLVTag(flvts:uint, type:uint, codec:int, mode:int, bytes:ByteArray, offset:uint, length:uint):void
{
var tag:ByteArray = new ByteArray();
tag.position = 0;
var msgLength:uint = length + ((codec >= 0) ? 1 : 0) + ((mode >= 0) ? 1 : 0);
var cursor:uint = 0;
if(msgLength > 0xffffff)
return; // too big for the length field
tag.length = FLVTags.HEADER_LENGTH + msgLength;
tag[cursor++] = type;
tag[cursor++] = (msgLength >> 16) & 0xff;
tag[cursor++] = (msgLength >> 8) & 0xff;
tag[cursor++] = (msgLength ) & 0xff;
tag[cursor++] = (flvts >> 16) & 0xff;
tag[cursor++] = (flvts >> 8) & 0xff;
tag[cursor++] = (flvts ) & 0xff;
tag[cursor++] = (flvts >> 24) & 0xff;
tag[cursor++] = 0x00; // stream ID
tag[cursor++] = 0x00;
tag[cursor++] = 0x00;
if(codec >= 0)
tag[cursor++] = codec;
if(mode >= 0)
tag[cursor++] = mode;
tag.position = cursor;
tag.writeBytes(bytes, offset, length);
cursor += length;
msgLength += 11; // account for message header in back pointer
tag.writeUnsignedInt(lastTagSize);
lastTagSize = tag.length;
// Dispatch tag.
if(callback != null)
callback(flvts, tag);
}
public function convertFLVTimestamp(pts:Number):Number
{
return pts / 90.0;
}
private static var flvGenerationBuffer:ByteArray = new ByteArray();
/**
* Convert and amit AVC NALU data.
*/
public function convert(unit:NALU):void
{
// Emit an AVCC.
var avcc:ByteArray = NALUProcessor.extractAVCC(unit);
if(avcc)
sendFLVTag(convertFLVTimestamp(unit.pts), FLVTags.TYPE_VIDEO, FLVTags.VIDEO_CODEC_AVC_KEYFRAME, FLVTags.AVC_MODE_AVCC, avcc, 0, avcc.length);
// Accumulate NALUs into buffer.
flvGenerationBuffer.length = 3;
flvGenerationBuffer[0] = (tsu >> 16) & 0xff;
flvGenerationBuffer[1] = (tsu >> 8) & 0xff;
flvGenerationBuffer[2] = (tsu ) & 0xff;
flvGenerationBuffer.position = 3;
// Check keyframe status.
var keyFrame:Boolean = false;
var totalAppended:int = 0;
NALUProcessor.walkNALUs(unit.buffer, 0, function(bytes:ByteArray, cursor:uint, length:uint):void
{
// Check for a NALU that is keyframe type.
var naluType:uint = bytes[cursor] & 0x1f;
//trace(naluType + " length=" + length);
switch(naluType)
{
case 0x09: // "access unit delimiter"
switch((bytes[cursor + 1] >> 5) & 0x07) // access unit type
{
case 0:
case 3:
case 5:
keyFrame = true;
break;
default:
keyFrame = false;
break;
}
break;
default:
// Infer keyframe state.
if(naluType == 5)
keyFrame = true;
else if(naluType == 1)
keyFrame = false;
}
// Append.
flvGenerationBuffer.writeUnsignedInt(length);
flvGenerationBuffer.writeBytes(bytes, cursor, length);
totalAppended += length;
}, true );
var flvts:uint = convertFLVTimestamp(unit.pts);
var tsu:uint = convertFLVTimestamp(unit.pts - unit.dts);
var codec:uint;
if(keyFrame)
codec = FLVTags.VIDEO_CODEC_AVC_KEYFRAME;
else
codec = FLVTags.VIDEO_CODEC_AVC_PREDICTIVEFRAME;
//trace("ts=" + flvts + " tsu=" + tsu + " keyframe = " + keyFrame);
sendFLVTag(flvts, FLVTags.TYPE_VIDEO, codec, FLVTags.AVC_MODE_PICTURE, flvGenerationBuffer, 0, flvGenerationBuffer.length);
}
private function compareBytesHelper(b1:ByteArray, b2:ByteArray):Boolean
{
var curPos:uint;
if(b1.length != b2.length)
return false;
for(curPos = 0; curPos < b1.length; curPos++)
{
if(b1[curPos] != b2[curPos])
return false;
}
return true;
}
private function sendAACConfigFLVTag(flvts:uint, profile:uint, sampleRateIndex:uint, channelConfig:uint):void
{
var isNewConfig:Boolean = true;
var audioSpecificConfig:ByteArray = new ByteArray();
var audioObjectType:uint;
audioSpecificConfig.length = 2;
switch(profile)
{
case 0x00:
audioObjectType = 0x01;
break;
case 0x01:
audioObjectType = 0x02;
break;
case 0x02:
audioObjectType = 0x03;
break;
default:
return;
}
audioSpecificConfig[0] = ((audioObjectType << 3) & 0xf8) + ((sampleRateIndex >> 1) & 0x07);
audioSpecificConfig[1] = ((sampleRateIndex << 7) & 0x80) + ((channelConfig << 3) & 0x78);
if(_aacConfig && compareBytesHelper(_aacConfig, audioSpecificConfig))
isNewConfig = false;
if(!isNewConfig)
return;
_aacConfig = audioSpecificConfig;
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_CONFIG, _aacConfig, 0, _aacConfig.length);
}
/**
* Convert and amit AAC data.
*/
public function convertAAC(pes:PESPacket):void
{
var timeAccumulation:Number = 0.0;
var limit:uint;
var stream:ByteArray;
var hadRemainder:Boolean = false;
var cursor:int = 0;
var length:int = pes.buffer.length;
var bytes:ByteArray = pes.buffer;
var timestamp:Number = pes.pts;
if(_aacRemainder)
{
stream = _aacRemainder;
stream.writeBytes(bytes, cursor, length);
cursor = 0;
length = stream.length;
_aacRemainder = null;
hadRemainder = true;
timeAccumulation = _aacTimestamp - timestamp;
}
else
stream = bytes;
limit = cursor + length;
// an AAC PES packet can contain multiple ADTS frames
while(cursor < limit)
{
var remaining:uint = limit - cursor;
var sampleRateIndex:uint;
var sampleRate:Number = undefined;
var profile:uint;
var channelConfig:uint;
var frameLength:uint;
if(remaining < FLVTags.ADTS_FRAME_HEADER_LENGTH)
break;
// search for syncword
if(stream[cursor] != 0xff || (stream[cursor + 1] & 0xf0) != 0xf0)
{
cursor++;
continue;
}
frameLength = (stream[cursor + 3] & 0x03) << 11;
frameLength += (stream[cursor + 4]) << 3;
frameLength += (stream[cursor + 5] >> 5) & 0x07;
// Check for an invalid ADTS header; if so look for next syncword.
if(frameLength < FLVTags.ADTS_FRAME_HEADER_LENGTH)
{
cursor++;
continue;
}
// Skip it till next PES packet.
if(frameLength > remaining)
break;
profile = (stream[cursor + 2] >> 6) & 0x03;
sampleRateIndex = (stream[cursor + 2] >> 2) & 0x0f;
switch(sampleRateIndex)
{
case 0x00:
sampleRate = 96000.0;
break;
case 0x01:
sampleRate = 88200.0;
break;
case 0x02:
sampleRate = 64000.0;
break;
case 0x03:
sampleRate = 48000.0;
break;
case 0x04:
sampleRate = 44100.0;
break;
case 0x05:
sampleRate = 32000.0;
break;
case 0x06:
sampleRate = 24000.0;
break;
case 0x07:
sampleRate = 22050.0;
break;
case 0x08:
sampleRate = 16000.0;
break;
case 0x09:
sampleRate = 12000.0;
break;
case 0x0a:
sampleRate = 11025.0;
break;
case 0x0b:
sampleRate = 8000.0;
break;
case 0x0c:
sampleRate = 7350.0;
break;
}
channelConfig = ((stream[cursor + 2] & 0x01) << 2) + ((stream[cursor + 3] >> 6) & 0x03);
if(sampleRate)
{
var flvts:uint = convertFLVTimestamp(timestamp + timeAccumulation);
sendAACConfigFLVTag(flvts, profile, sampleRateIndex, channelConfig);
//trace("Sending AAC");
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_FRAME, stream, cursor + FLVTags.ADTS_FRAME_HEADER_LENGTH, frameLength - FLVTags.ADTS_FRAME_HEADER_LENGTH);
timeAccumulation += (1024.0 / sampleRate) * 90000.0; // account for the duration of this frame
if(hadRemainder)
{
timeAccumulation = 0.0;
hadRemainder = false;
}
}
cursor += frameLength;
}
if(cursor < limit)
{
//trace("AAC timestamp was " + _aacTimestamp);
_aacRemainder = new ByteArray();
_aacRemainder.writeBytes(stream, cursor, limit - cursor);
_aacTimestamp = timestamp + timeAccumulation;
//trace("AAC timestamp now " + _aacTimestamp);
}
}
/**
* Convert and amit MP3 data.
*/
public function convertMP3(pes:PESPacket):void
{
sendFLVTag(convertFLVTimestamp(pes.pts), FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_MP3, -1, pes.buffer, 0, pes.buffer.length);
}
private function generateScriptData(values:Array):ByteArray
{
var bytes:ByteArray = new ByteArray();
bytes.objectEncoding = ObjectEncoding.AMF0;
for each (var object:Object in values)
bytes.writeObject(object);
return bytes;
}
private function sendScriptDataFLVTag(flvts:uint, values:Array):void
{
var bytes:ByteArray = generateScriptData(values);
sendFLVTag(flvts, FLVTags.TYPE_SCRIPTDATA, -1, -1, bytes, 0, bytes.length);
}
/**
* Fire off a subtitle caption.
*/
public function createAndSendCaptionMessage( timeStamp:Number, captionBuffer:String, lang:String="", textid:Number=99):void
{
//var captionObject:Array = ["onCaptionInfo", { type:"WebVTT", data:captionBuffer }];
//sendScriptDataFLVTag( timeStamp * 1000, captionObject);
// We need to strip the timestamp off of the text data
captionBuffer = captionBuffer.slice(captionBuffer.indexOf('\n') + 1);
var subtitleObject:Array = ["onTextData", { text:captionBuffer, language:lang, trackid:textid }];
sendScriptDataFLVTag( timeStamp * 1000, subtitleObject);
}
}
}
|
Fix CC generation breaking video/dupe'ing tags.
|
Fix CC generation breaking video/dupe'ing tags.
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
f077777afd6ae1f73b338d1a2c4b669e36b9780d
|
WEB-INF/lps/lfc/kernel/swf9/DojoExternalInterface.as
|
WEB-INF/lps/lfc/kernel/swf9/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]
*/
class DojoExternalInterfaceClass {
#passthrough (toplevel:true) {
import flash.external.ExternalInterface;
}#
var available = null;
var flashMethods = [];
var numArgs = null;
var argData = null;
var resultData = null;
// var installing = false;
var _id;
function DojoExternalInterfaceClass(id){
// extract the dojo base path
//Debug.write('initialize', ExternalInterface.addCallback);
// see if we need to do an express install
/* var install = new ExpressInstall();
if(install.needsUpdate){
install.init();
this.installing = true;
}
*/
// not loaded from the wrapper JS...
if (id == null) return;
this._id = id;
// register our callback functions
ExternalInterface.addCallback("startExec", this.startExec);
ExternalInterface.addCallback("setNumberArguments", this.setNumberArguments);
ExternalInterface.addCallback("chunkArgumentData", this.chunkArgumentData);
ExternalInterface.addCallback("exec", this.exec);
ExternalInterface.addCallback("getReturnLength", this.getReturnLength);
ExternalInterface.addCallback("chunkReturnData", this.chunkReturnData);
ExternalInterface.addCallback("endExec", this.endExec);
// set whether communication is available
this.available = ExternalInterface.available;
this.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);
ExternalInterface.call("lz.embed.dojo.comm." + this._id + "._addExternalInterfaceCallback", methodName, this._id);
return true;
}
function call(methodName, resultsCallback = null, ...parameters) {
/*
// 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 = ExternalInterface.call(methodName, 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(){
Debug.write('loaded');
//if (this.installing) return;
this.call("lz.embed.dojo.loaded", null, this._id);
//LzBrowserKernel.__jsready();
}
function startExec(){
//Debug.write('startExec');
this.numArgs = null;
this.argData = null;
this.resultData = null;
}
function setNumberArguments(numArgs){
//Debug.write('setNumberArguments', numArgs);
this.numArgs = numArgs;
this.argData = [];
}
function chunkArgumentData(value, argIndex){
//Debug.write('chunkArgumentData', value, argIndex);
//getURL("javascript:dojo.debug('FLASH: chunkArgumentData, value="+value+", argIndex="+argIndex+"')");
var currentValue = this.argData[argIndex];
if(currentValue == null || typeof currentValue == "undefined"){
this.argData[argIndex] = value;
}else{
this.argData[argIndex] += value;
}
}
function exec(methodName){
//Debug.write('exec', methodName);
// decode all of the arguments that were passed in
for(var i = 0; i < this.argData.length; i++){
this.argData[i] =
this.decodeData(this.argData[i]);
}
var instance = this.flashMethods[methodName];
//Debug.write('instance', instance, instance[methodName]);
this.resultData = instance[methodName].apply(
instance, this.argData) + '';
//Debug.write('result', this.resultData);
// encode the result data
this.resultData =
this.encodeData(this.resultData);
//Debug.write('resultData', this.resultData);
//getURL("javascript:dojo.debug('FLASH: encoded result data="+this.resultData+"')");
}
function getReturnLength(){
if(this.resultData == null ||
typeof this.resultData == "undefined"){
return 0;
}
var segments = Math.ceil(this.resultData.length / 1024);
//Debug.write('getReturnLength', typeof this.resultData, this.resultData.length, segments);
return segments;
}
function chunkReturnData(segment){
var numSegments = this.getReturnLength();
var startCut = segment * 1024;
var endCut = segment * 1024 + 1024;
if(segment == (numSegments - 1)){
endCut = segment * 1024 + this.resultData.length;
}
var piece = this.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 = this.replaceStr(data, "&custom_backslash;", "\\");
data = this.replaceStr(data, "\\\'", "\'");
data = this.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 = this.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 = this.replaceStr(data, '<', '&custom_lt;');
data = this.replaceStr(data, '>', '&custom_gt;');
// encode control characters and JavaScript delimiters
data = this.replaceStr(data, "\n", "\\n");
data = this.replaceStr(data, "\r", "\\r");
data = this.replaceStr(data, "\f", "\\f");
data = this.replaceStr(data, "'", "\\'");
data = this.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]
*/
class DojoExternalInterfaceClass {
#passthrough (toplevel:true) {
import flash.external.ExternalInterface;
}#
var available = null;
var flashMethods = [];
var numArgs = null;
var argData = null;
var resultData = null;
// var installing = false;
var _id;
function DojoExternalInterfaceClass(id){
// extract the dojo base path
//Debug.write('initialize', ExternalInterface.addCallback);
// see if we need to do an express install
/* var install = new ExpressInstall();
if(install.needsUpdate){
install.init();
this.installing = true;
}
*/
// not loaded from the wrapper JS...
if (id == null) return;
this._id = id;
// register our callback functions
ExternalInterface.addCallback("startExec", this.startExec);
ExternalInterface.addCallback("setNumberArguments", this.setNumberArguments);
ExternalInterface.addCallback("chunkArgumentData", this.chunkArgumentData);
ExternalInterface.addCallback("exec", this.exec);
ExternalInterface.addCallback("getReturnLength", this.getReturnLength);
ExternalInterface.addCallback("chunkReturnData", this.chunkReturnData);
ExternalInterface.addCallback("endExec", this.endExec);
// set whether communication is available
this.available = ExternalInterface.available;
this.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);
ExternalInterface.call("lz.embed.dojo.comm." + this._id + "._addExternalInterfaceCallback", methodName, this._id);
return true;
}
function call(methodName, resultsCallback = null, ...parameters) {
/*
// 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 = ExternalInterface.call(methodName, 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(){
//Debug.write('loaded');
//if (this.installing) return;
this.call("lz.embed.dojo.loaded", null, this._id);
//LzBrowserKernel.__jsready();
}
function startExec(){
//Debug.write('startExec');
this.numArgs = null;
this.argData = null;
this.resultData = null;
}
function setNumberArguments(numArgs){
//Debug.write('setNumberArguments', numArgs);
this.numArgs = numArgs;
this.argData = [];
}
function chunkArgumentData(value, argIndex){
//Debug.write('chunkArgumentData', value, argIndex);
//getURL("javascript:dojo.debug('FLASH: chunkArgumentData, value="+value+", argIndex="+argIndex+"')");
var currentValue = this.argData[argIndex];
if(currentValue == null || typeof currentValue == "undefined"){
this.argData[argIndex] = value;
}else{
this.argData[argIndex] += value;
}
}
function exec(methodName){
//Debug.write('exec', methodName);
// decode all of the arguments that were passed in
for(var i = 0; i < this.argData.length; i++){
this.argData[i] =
this.decodeData(this.argData[i]);
}
var instance = this.flashMethods[methodName];
//Debug.write('instance', instance, instance[methodName]);
this.resultData = instance[methodName].apply(
instance, this.argData) + '';
//Debug.write('result', this.resultData);
// encode the result data
this.resultData =
this.encodeData(this.resultData);
//Debug.write('resultData', this.resultData);
//getURL("javascript:dojo.debug('FLASH: encoded result data="+this.resultData+"')");
}
function getReturnLength(){
if(this.resultData == null ||
typeof this.resultData == "undefined"){
return 0;
}
var segments = Math.ceil(this.resultData.length / 1024);
//Debug.write('getReturnLength', typeof this.resultData, this.resultData.length, segments);
return segments;
}
function chunkReturnData(segment){
var numSegments = this.getReturnLength();
var startCut = segment * 1024;
var endCut = segment * 1024 + 1024;
if(segment == (numSegments - 1)){
endCut = segment * 1024 + this.resultData.length;
}
var piece = this.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 = this.replaceStr(data, "&custom_backslash;", "\\");
data = this.replaceStr(data, "\\\'", "\'");
data = this.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 = this.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 = this.replaceStr(data, '<', '&custom_lt;');
data = this.replaceStr(data, '>', '&custom_gt;');
// encode control characters and JavaScript delimiters
data = this.replaceStr(data, "\n", "\\n");
data = this.replaceStr(data, "\r", "\\r");
data = this.replaceStr(data, "\f", "\\f");
data = this.replaceStr(data, "'", "\\'");
data = this.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 20080820-hqm-d by [email protected] on 2008-08-20 15:18:10 EDT in /Users/hqm/openlaszlo/trunk/WEB-INF/lps/lfc for http://svn.openlaszlo.org/openlaszlo/trunk/WEB-INF/lps/lfc
|
Change 20080820-hqm-d by [email protected] on 2008-08-20 15:18:10 EDT
in /Users/hqm/openlaszlo/trunk/WEB-INF/lps/lfc
for http://svn.openlaszlo.org/openlaszlo/trunk/WEB-INF/lps/lfc
Summary:
New Features: remove debug.write statement
Bugs Fixed:
Technical Reviewer: hqm
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
Tests:
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@10725 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
d10b94df85e5926ee86deaac6448b67f970f79ec
|
src/as/com/threerings/util/MediaContainer.as
|
src/as/com/threerings/util/MediaContainer.as
|
package com.threerings.util {
//import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Shape;
import flash.errors.IOError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.events.NetStatusEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.events.StatusEvent;
import flash.events.TextEvent;
import flash.geom.Point;
import flash.media.Video;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
import flash.system.SecurityDomain;
import flash.net.URLRequest;
import mx.core.ScrollPolicy;
import mx.core.UIComponent;
import mx.containers.Box;
import mx.controls.VideoDisplay;
import mx.events.VideoEvent;
import com.threerings.util.StringUtil;
import com.threerings.media.image.ImageUtil;
/**
* A wrapper class for all media that will be placed on the screen.
* Subject to change.
*/
public class MediaContainer extends Box
{
/** An event we dispatch when our size is known. */
public static const SIZE_KNOWN :String = "mediaSizeKnown";
/** A log instance that can be shared by sprites. */
protected static const log :Log = Log.getLog(MediaContainer);
/**
* Constructor.
*/
public function MediaContainer (url :String = null)
{
if (url != null) {
setMedia(url);
}
mouseEnabled = false;
mouseChildren = true;
verticalScrollPolicy = ScrollPolicy.OFF;
horizontalScrollPolicy = ScrollPolicy.OFF;
}
/**
* Get the media. If the media was loaded using a URL, this will
* likely be the Loader object holding the real media.
*/
public function getMedia () :DisplayObject
{
return _media;
}
/**
* Configure the media to display.
*/
public function setMedia (url :String) :void
{
if (Util.equals(_url, url)) {
return; // no change
}
_url = url;
// shutdown any previous media
if (_media != null) {
shutdown(false);
}
// set up the new media
if (StringUtil.endsWith(url.toLowerCase(), ".flv")) {
setupVideo(url);
} else {
setupSwfOrImage(url);
}
}
/**
* Configure our media as an instance of the specified class.
*/
public function setMediaClass (clazz :Class) :void
{
setMediaObject(new clazz() as DisplayObject);
}
/**
* Configure an already-instantiated DisplayObject as our media.
*/
public function setMediaObject (disp :DisplayObject) :void
{
_url = null;
if (_media != null) {
shutdown(false);
}
if (disp is UIComponent) {
addChild(disp);
} else {
rawChildren.addChild(disp);
}
_media = disp;
updateContentDimensions(disp.width, disp.height);
}
/**
* Configure this sprite to show a video.
*/
protected function setupVideo (url :String) :void
{
var vid :VideoDisplay = new VideoDisplay();
vid.autoPlay = false;
_media = vid;
addChild(vid);
vid.addEventListener(ProgressEvent.PROGRESS, loadVideoProgress);
vid.addEventListener(VideoEvent.READY, loadVideoReady);
vid.addEventListener(VideoEvent.REWIND, videoDidRewind);
// start it loading
vid.source = url;
vid.load();
}
/**
* Configure this sprite to show an image or flash movie.
*/
protected function setupSwfOrImage (url :String) :void
{
// create our loader and set up some event listeners
var loader :Loader = new Loader();
_media = loader;
var info :LoaderInfo = loader.contentLoaderInfo;
info.addEventListener(Event.COMPLETE, loadingComplete);
info.addEventListener(IOErrorEvent.IO_ERROR, loadError);
info.addEventListener(ProgressEvent.PROGRESS, loadProgress);
// create a mask to prevent the media from drawing out of bounds
if (getMaxContentWidth() < int.MAX_VALUE &&
getMaxContentHeight() < int.MAX_VALUE) {
configureMask(getMaxContentWidth(), getMaxContentHeight());
}
// start it loading, add it as a child
loader.load(new URLRequest(url), getContext(url));
rawChildren.addChild(loader);
try {
updateContentDimensions(info.width, info.height);
} catch (err :Error) {
// an error is thrown trying to access these props before they're
// ready
}
}
/**
* Display a 'broken image' to indicate there were troubles with
* loading the media.
*/
protected function setupBrokenImage (w :int = -1, h :int = -1) :void
{
if (w == -1) {
w = 100;
}
if (h == -1) {
h = 100;
}
setMediaObject(ImageUtil.createErrorImage(w, h));
}
/**
* Get the application domain being used by this media, or null if
* none or not applicable.
*/
public function getApplicationDomain () :ApplicationDomain
{
return (_media is Loader)
? (_media as Loader).contentLoaderInfo.applicationDomain
: null;
}
/**
* Unload the media we're displaying, clean up any resources.
*
* @param completely if true, we're going away and should stop
* everything. Otherwise, we're just loading up new media.
*/
public function shutdown (completely :Boolean = true) :void
{
try {
// remove the mask
if (_media != null && _media.mask != null) {
rawChildren.removeChild(_media.mask);
_media.mask = null;
}
if (_media is Loader) {
var loader :Loader = (_media as Loader);
// remove any listeners
removeListeners(loader.contentLoaderInfo);
// dispose of media
try {
loader.close();
} catch (ioe :IOError) {
// ignore
}
loader.unload();
rawChildren.removeChild(loader);
} else if (_media is VideoDisplay) {
var vid :VideoDisplay = (_media as VideoDisplay);
// remove any listeners
vid.removeEventListener(ProgressEvent.PROGRESS,
loadVideoProgress);
vid.removeEventListener(VideoEvent.READY, loadVideoReady);
vid.removeEventListener(VideoEvent.REWIND, videoDidRewind);
// dispose of media
vid.pause();
try {
vid.close();
} catch (ioe :IOError) {
// ignore
}
vid.stop();
// remove from hierarchy
removeChild(vid);
} else if (_media != null) {
if (_media is UIComponent) {
removeChild(_media);
} else {
rawChildren.removeChild(_media);
}
}
} catch (ioe :IOError) {
log.warning("Error shutting down media: " + ioe);
log.logStackTrace(ioe);
}
// clean everything up
_w = 0;
_h = 0;
_media = null;
}
/**
* Get the width of the content, bounded by the maximum.
*/
public function getContentWidth () :int
{
return Math.min(Math.abs(_w * getMediaScaleX()), getMaxContentWidth());
}
/**
* Get the height of the content, bounded by the maximum.
*/
public function getContentHeight () :int
{
return Math.min(Math.abs(_h * getMediaScaleY()), getMaxContentHeight());
}
/**
* Get the maximum allowable width for our content.
*/
public function getMaxContentWidth () :int
{
return int.MAX_VALUE;
}
/**
* Get the maximum allowable height for our content.
*/
public function getMaxContentHeight () :int
{
return int.MAX_VALUE;
}
/**
* Get the X scaling factor to use on the actual media.
*/
public function getMediaScaleX () :Number
{
return 1;
}
/**
* Get the Y scaling factor to use on the actual media.
*/
public function getMediaScaleY () :Number
{
return 1;
}
/**
* Return the LoaderContext that should be used to load the media
* at the specified url.
*/
protected function getContext (url :String) :LoaderContext
{
if (isImage(url)) {
// load images into our domain so that we can view their pixels
return new LoaderContext(true,
new ApplicationDomain(ApplicationDomain.currentDomain),
SecurityDomain.currentDomain);
} else {
// share nothing, trust nothing
return new LoaderContext(false, null, null);
}
}
/**
* Does the specified url represent an image?
*/
protected function isImage (url :String) :Boolean
{
// look at the last 4 characters in the lowercased url
switch (url.toLowerCase().slice(-4)) {
case ".png":
case ".jpg":
case ".gif":
return true;
default:
return false;
}
}
/**
* Remove our listeners from the LoaderInfo object.
*/
protected function removeListeners (info :LoaderInfo) :void
{
info.removeEventListener(Event.COMPLETE, loadingComplete);
info.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
info.removeEventListener(ProgressEvent.PROGRESS, loadProgress);
}
/**
* A callback to receive IO_ERROR events.
*/
protected function loadError (event :IOErrorEvent) :void
{
setupBrokenImage(-1, -1);
}
/**
* A callback to receive PROGRESS events.
*/
protected function loadProgress (event :ProgressEvent) :void
{
updateLoadingProgress(event.bytesLoaded, event.bytesTotal);
var info :LoaderInfo = (event.target as LoaderInfo);
try {
updateContentDimensions(info.width, info.height);
} catch (err :Error) {
// an error is thrown trying to access these props before they're
// ready
}
}
/**
* A callback to receive PROGRESS events on the video.
*/
protected function loadVideoProgress (event :ProgressEvent) :void
{
var vid :VideoDisplay = (event.currentTarget as VideoDisplay);
updateContentDimensions(vid.videoWidth, vid.videoHeight);
updateLoadingProgress(vid.bytesLoaded, vid.bytesTotal);
}
/**
* A callback to receive READY events for video.
*/
protected function loadVideoReady (event :VideoEvent) :void
{
var vid :VideoDisplay = (event.currentTarget as VideoDisplay);
updateContentDimensions(vid.videoWidth, vid.videoHeight);
updateLoadingProgress(1, 1);
vid.play();
// remove the two listeners
vid.removeEventListener(ProgressEvent.PROGRESS, loadVideoProgress);
vid.removeEventListener(VideoEvent.READY, loadVideoReady);
}
/**
* Callback function to receive COMPLETE events for swfs or images.
*/
protected function loadingComplete (event :Event) :void
{
var info :LoaderInfo = (event.target as LoaderInfo);
removeListeners(info);
// trace("Loading complete: " + info.url +
// ", childAllowsParent=" + info.childAllowsParent +
// ", parentAllowsChild=" + info.parentAllowsChild +
// ", sameDomain=" + info.sameDomain);
updateContentDimensions(info.width, info.height);
updateLoadingProgress(1, 1);
// // Bitmap smoothing
// if (_media is Loader) {
// var l :Loader = Loader(_media);
// try {
// if (l.content is Bitmap) {
// Bitmap(l.content).smoothing = true;
// trace("--- made bitmap smooth");
// }
// } catch (er :Error) {
// trace("--- error bitmap smooth");
// }
// }
}
/**
* Called when the video auto-rewinds.
*/
protected function videoDidRewind (event :VideoEvent) :void
{
(_media as VideoDisplay).play();
}
/**
* Configure the mask for this object.
*/
protected function configureMask (ww :int, hh :int) :void
{
var mask :Shape;
if (_media.mask != null) {
mask = (_media.mask as Shape);
} else {
mask = new Shape();
// the mask must be added to the display list (which is wacky)
rawChildren.addChild(mask);
_media.mask = mask;
}
mask.graphics.clear();
mask.graphics.beginFill(0xFFFFFF);
mask.graphics.drawRect(0, 0, ww, hh);
mask.graphics.endFill();
}
/**
* Called during loading as we figure out how big the content we're
* loading is.
*/
protected function updateContentDimensions (ww :int, hh :int) :void
{
// update our saved size, and possibly notify our container
if (_w != ww || _h != hh) {
_w = ww;
_h = hh;
// TODO: I think that I'll want to create a subclass of the
// basic media container which does things that are usefulish
// but separate from MsoySprite. SIZE_KNOWN is one of those
// things that should probably be moved. Maybe BaseMediaContainer
// and MediaContainer? FancyMediaContainer?
dispatchEvent(new Event(SIZE_KNOWN));
contentDimensionsUpdated();
}
}
/**
* Called when we know the true size of the content.
*/
protected function contentDimensionsUpdated () :void
{
// nada, by default
}
/**
* Update the graphics to indicate how much is loaded.
*/
protected function updateLoadingProgress (
soFar :Number, total :Number) :void
{
// nada, by default
}
/** The unaltered URL of the content we're displaying. */
protected var _url :String;
/** The unscaled width of our content. */
protected var _w :int;
/** The unscaled height of our content. */
protected var _h :int;
/** Either a Loader or a VideoDisplay. */
protected var _media :DisplayObject;
}
}
|
package com.threerings.util {
//import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.Shape;
import flash.display.Sprite;
import flash.errors.IOError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.events.NetStatusEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.events.StatusEvent;
import flash.events.TextEvent;
import flash.geom.Point;
import flash.media.Video;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
import flash.system.SecurityDomain;
import flash.net.URLRequest;
import com.threerings.util.StringUtil;
import com.threerings.media.image.ImageUtil;
/**
* A wrapper class for all media that will be placed on the screen.
* Subject to change.
*/
public class MediaContainer extends Sprite
{
/** An event we dispatch when our size is known. */
public static const SIZE_KNOWN :String = "mediaSizeKnown";
/** A log instance that can be shared by sprites. */
protected static const log :Log = Log.getLog(MediaContainer);
/**
* Constructor.
*/
public function MediaContainer (url :String = null)
{
if (url != null) {
setMedia(url);
}
mouseEnabled = false;
mouseChildren = true;
}
/**
* Get the media. If the media was loaded using a URL, this will
* likely be the Loader object holding the real media.
*/
public function getMedia () :DisplayObject
{
return _media;
}
/**
* Configure the media to display.
*/
public function setMedia (url :String) :void
{
if (Util.equals(_url, url)) {
return; // no change
}
_url = url;
// shutdown any previous media
if (_media != null) {
shutdown(false);
}
// set up the new media
if (StringUtil.endsWith(url.toLowerCase(), ".flv")) {
setupVideo(url);
} else {
setupSwfOrImage(url);
}
}
/**
* Configure our media as an instance of the specified class.
*/
public function setMediaClass (clazz :Class) :void
{
setMediaObject(new clazz() as DisplayObject);
}
/**
* Configure an already-instantiated DisplayObject as our media.
*/
public function setMediaObject (disp :DisplayObject) :void
{
_url = null;
if (_media != null) {
shutdown(false);
}
addChild(disp);
_media = disp;
updateContentDimensions(disp.width, disp.height);
}
/**
* Configure this sprite to show a video.
*/
protected function setupVideo (url :String) :void
{
// var vid :VideoDisplay = new VideoDisplay();
// vid.autoPlay = false;
// _media = vid;
// addChild(vid);
// vid.addEventListener(ProgressEvent.PROGRESS, loadVideoProgress);
// vid.addEventListener(VideoEvent.READY, loadVideoReady);
// vid.addEventListener(VideoEvent.REWIND, videoDidRewind);
//
// // start it loading
// vid.source = url;
// vid.load();
}
/**
* Configure this sprite to show an image or flash movie.
*/
protected function setupSwfOrImage (url :String) :void
{
// create our loader and set up some event listeners
var loader :Loader = new Loader();
_media = loader;
var info :LoaderInfo = loader.contentLoaderInfo;
info.addEventListener(Event.COMPLETE, loadingComplete);
info.addEventListener(IOErrorEvent.IO_ERROR, loadError);
info.addEventListener(ProgressEvent.PROGRESS, loadProgress);
// create a mask to prevent the media from drawing out of bounds
if (getMaxContentWidth() < int.MAX_VALUE &&
getMaxContentHeight() < int.MAX_VALUE) {
configureMask(getMaxContentWidth(), getMaxContentHeight());
}
// start it loading, add it as a child
loader.load(new URLRequest(url), getContext(url));
addChild(loader);
try {
updateContentDimensions(info.width, info.height);
} catch (err :Error) {
// an error is thrown trying to access these props before they're
// ready
}
}
/**
* Display a 'broken image' to indicate there were troubles with
* loading the media.
*/
protected function setupBrokenImage (w :int = -1, h :int = -1) :void
{
if (w == -1) {
w = 100;
}
if (h == -1) {
h = 100;
}
setMediaObject(ImageUtil.createErrorImage(w, h));
}
/**
* Get the application domain being used by this media, or null if
* none or not applicable.
*/
public function getApplicationDomain () :ApplicationDomain
{
return (_media is Loader)
? (_media as Loader).contentLoaderInfo.applicationDomain
: null;
}
/**
* Unload the media we're displaying, clean up any resources.
*
* @param completely if true, we're going away and should stop
* everything. Otherwise, we're just loading up new media.
*/
public function shutdown (completely :Boolean = true) :void
{
try {
// remove the mask
if (_media != null && _media.mask != null) {
removeChild(_media.mask);
_media.mask = null;
}
if (_media is Loader) {
var loader :Loader = (_media as Loader);
// remove any listeners
removeListeners(loader.contentLoaderInfo);
// dispose of media
try {
loader.close();
} catch (ioe :IOError) {
// ignore
}
loader.unload();
removeChild(loader);
// } else if (_media is VideoDisplay) {
// var vid :VideoDisplay = (_media as VideoDisplay);
// // remove any listeners
// vid.removeEventListener(ProgressEvent.PROGRESS,
// loadVideoProgress);
// vid.removeEventListener(VideoEvent.READY, loadVideoReady);
// vid.removeEventListener(VideoEvent.REWIND, videoDidRewind);
//
// // dispose of media
// vid.pause();
// try {
// vid.close();
// } catch (ioe :IOError) {
// // ignore
// }
// vid.stop();
//
// // remove from hierarchy
// removeChild(vid);
} else if (_media != null) {
removeChild(_media);
}
} catch (ioe :IOError) {
log.warning("Error shutting down media: " + ioe);
log.logStackTrace(ioe);
}
// clean everything up
_w = 0;
_h = 0;
_media = null;
}
/**
* Get the width of the content, bounded by the maximum.
*/
public function getContentWidth () :int
{
return Math.min(Math.abs(_w * getMediaScaleX()), getMaxContentWidth());
}
/**
* Get the height of the content, bounded by the maximum.
*/
public function getContentHeight () :int
{
return Math.min(Math.abs(_h * getMediaScaleY()), getMaxContentHeight());
}
/**
* Get the maximum allowable width for our content.
*/
public function getMaxContentWidth () :int
{
return int.MAX_VALUE;
}
/**
* Get the maximum allowable height for our content.
*/
public function getMaxContentHeight () :int
{
return int.MAX_VALUE;
}
/**
* Get the X scaling factor to use on the actual media.
*/
public function getMediaScaleX () :Number
{
return 1;
}
/**
* Get the Y scaling factor to use on the actual media.
*/
public function getMediaScaleY () :Number
{
return 1;
}
/**
* Return the LoaderContext that should be used to load the media
* at the specified url.
*/
protected function getContext (url :String) :LoaderContext
{
if (isImage(url)) {
// load images into our domain so that we can view their pixels
return new LoaderContext(true,
new ApplicationDomain(ApplicationDomain.currentDomain),
SecurityDomain.currentDomain);
} else {
// share nothing, trust nothing
return new LoaderContext(false, null, null);
}
}
/**
* Does the specified url represent an image?
*/
protected function isImage (url :String) :Boolean
{
// look at the last 4 characters in the lowercased url
switch (url.toLowerCase().slice(-4)) {
case ".png":
case ".jpg":
case ".gif":
return true;
default:
return false;
}
}
/**
* Remove our listeners from the LoaderInfo object.
*/
protected function removeListeners (info :LoaderInfo) :void
{
info.removeEventListener(Event.COMPLETE, loadingComplete);
info.removeEventListener(IOErrorEvent.IO_ERROR, loadError);
info.removeEventListener(ProgressEvent.PROGRESS, loadProgress);
}
/**
* A callback to receive IO_ERROR events.
*/
protected function loadError (event :IOErrorEvent) :void
{
setupBrokenImage(-1, -1);
}
/**
* A callback to receive PROGRESS events.
*/
protected function loadProgress (event :ProgressEvent) :void
{
updateLoadingProgress(event.bytesLoaded, event.bytesTotal);
var info :LoaderInfo = (event.target as LoaderInfo);
try {
updateContentDimensions(info.width, info.height);
} catch (err :Error) {
// an error is thrown trying to access these props before they're
// ready
}
}
/**
* A callback to receive PROGRESS events on the video.
*/
protected function loadVideoProgress (event :ProgressEvent) :void
{
// var vid :VideoDisplay = (event.currentTarget as VideoDisplay);
// updateContentDimensions(vid.videoWidth, vid.videoHeight);
//
// updateLoadingProgress(vid.bytesLoaded, vid.bytesTotal);
}
/**
* A callback to receive READY events for video.
*/
// protected function loadVideoReady (event :VideoEvent) :void
// {
// var vid :VideoDisplay = (event.currentTarget as VideoDisplay);
// updateContentDimensions(vid.videoWidth, vid.videoHeight);
// updateLoadingProgress(1, 1);
//
// vid.play();
//
// // remove the two listeners
// vid.removeEventListener(ProgressEvent.PROGRESS, loadVideoProgress);
// vid.removeEventListener(VideoEvent.READY, loadVideoReady);
// }
/**
* Callback function to receive COMPLETE events for swfs or images.
*/
protected function loadingComplete (event :Event) :void
{
var info :LoaderInfo = (event.target as LoaderInfo);
removeListeners(info);
// trace("Loading complete: " + info.url +
// ", childAllowsParent=" + info.childAllowsParent +
// ", parentAllowsChild=" + info.parentAllowsChild +
// ", sameDomain=" + info.sameDomain);
updateContentDimensions(info.width, info.height);
updateLoadingProgress(1, 1);
}
/**
* Called when the video auto-rewinds.
*/
// protected function videoDidRewind (event :VideoEvent) :void
// {
// (_media as VideoDisplay).play();
// }
/**
* Configure the mask for this object.
*/
protected function configureMask (ww :int, hh :int) :void
{
var mask :Shape;
if (_media.mask != null) {
mask = (_media.mask as Shape);
} else {
mask = new Shape();
// the mask must be added to the display list (which is wacky)
addChild(mask);
_media.mask = mask;
}
mask.graphics.clear();
mask.graphics.beginFill(0xFFFFFF);
mask.graphics.drawRect(0, 0, ww, hh);
mask.graphics.endFill();
}
/**
* Called during loading as we figure out how big the content we're
* loading is.
*/
protected function updateContentDimensions (ww :int, hh :int) :void
{
// update our saved size, and possibly notify our container
if (_w != ww || _h != hh) {
_w = ww;
_h = hh;
// TODO: I think that I'll want to create a subclass of the
// basic media container which does things that are usefulish
// but separate from MsoySprite. SIZE_KNOWN is one of those
// things that should probably be moved. Maybe BaseMediaContainer
// and MediaContainer? FancyMediaContainer?
dispatchEvent(new Event(SIZE_KNOWN));
contentDimensionsUpdated();
}
}
/**
* Called when we know the true size of the content.
*/
protected function contentDimensionsUpdated () :void
{
// nada, by default
}
/**
* Update the graphics to indicate how much is loaded.
*/
protected function updateLoadingProgress (
soFar :Number, total :Number) :void
{
// nada, by default
}
/** The unaltered URL of the content we're displaying. */
protected var _url :String;
/** The unscaled width of our content. */
protected var _w :int;
/** The unscaled height of our content. */
protected var _h :int;
/** Either a Loader or a VideoDisplay. */
protected var _media :DisplayObject;
}
}
|
Convert MediaContainer to be just a subclass of Sprite, so that I can de-flex the 'world' portions of metasoy.
|
Convert MediaContainer to be just a subclass of Sprite, so that I can
de-flex the 'world' portions of metasoy.
git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@4506 542714f4-19e9-0310-aa3c-eee0fc999fb1
|
ActionScript
|
lgpl-2.1
|
threerings/narya,threerings/narya,threerings/narya,threerings/narya,threerings/narya
|
bd4809f54c289ce4b860f36552da017fd9967a1a
|
src/com/google/analytics/core/BrowserInfo.as
|
src/com/google/analytics/core/BrowserInfo.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
{
import com.google.analytics.utils.Environment;
import com.google.analytics.utils.Variables;
import com.google.analytics.utils.Version;
import com.google.analytics.v4.Configuration;
/**
* The BrowserInfo class.
*/
public class BrowserInfo
{
private var _config:Configuration;
private var _info:Environment;
/**
* Creates a new BrowserInfo instance.
* @param info The Environment reference of the BrowserInfo instance.
*/
public function BrowserInfo( config:Configuration, info:Environment )
{
_config = config;
_info = info;
}
/**
* Language encoding for the browser.
* <p>Some browsers don't set this, in which case it is set to "-".</p>
* <p>Example : <b>utmcs=ISO-8859-1</b></p>
*/
public function get utmcs():String
{
return _info.languageEncoding;
}
/**
* The Screen resolution
* <p>Example : <b>utmsr=2400x1920</b></p>
*/
public function get utmsr():String
{
return _info.screenWidth + "x" + _info.screenHeight;
}
/**
* Screen color depth
* <p>Example :<b>utmsc=24-bit</b></p>
*/
public function get utmsc():String
{
return _info.screenColorDepth + "-bit";
}
/**
* Browser language.
* <p>Example :<b>utmul=pt-br</b></p>
*/
public function get utmul():String
{
return _info.language.toLowerCase();
}
/**
* Indicates if browser is Java-enabled.
* <p>Example :<b>utmje=1</b></p>
*/
public function get utmje():String
{
return "0"; //not supported
}
/**
* Flash Version.
* <p>Example :<b>utmfl=9.0%20r48</b></p>
*/
public function get utmfl():String
{
if( _config.detectFlash )
{
var v:Version = _info.flashVersion;
return v.major+"."+v.minor+" r"+v.build;
}
return "-";
}
/**
* Returns a Variables object representation.
* @return a Variables object representation.
*/
public function toVariables():Variables
{
var variables:Variables = new Variables();
variables.URIencode = true;
variables.utmcs = utmcs;
variables.utmsr = utmsr;
variables.utmsc = utmsc;
variables.utmul = utmul;
variables.utmje = utmje;
variables.utmfl = utmfl;
return variables;
}
/**
* Returns the url String representation of the object.
* @return the url String representation of the object.
*/
public function toURLString():String
{
var v:Variables = toVariables();
return v.toString();
}
}
}
|
/*
* 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
{
import com.google.analytics.utils.Environment;
import com.google.analytics.utils.Variables;
import com.google.analytics.v4.Configuration;
import core.version;
public class BrowserInfo
{
private var _config:Configuration;
private var _info:Environment;
/**
* Creates a new BrowserInfo instance.
* @param info The Environment reference of the BrowserInfo instance.
*/
public function BrowserInfo( config:Configuration, info:Environment )
{
_config = config;
_info = info;
}
/**
* Language encoding for the browser.
* <p>Some browsers don't set this, in which case it is set to "-".</p>
* <p>Example : <b>utmcs=ISO-8859-1</b></p>
*/
public function get utmcs():String
{
return _info.languageEncoding;
}
/**
* The Screen resolution
* <p>Example : <b>utmsr=2400x1920</b></p>
*/
public function get utmsr():String
{
return _info.screenWidth + "x" + _info.screenHeight;
}
/**
* Screen color depth
* <p>Example :<b>utmsc=24-bit</b></p>
*/
public function get utmsc():String
{
return _info.screenColorDepth + "-bit";
}
/**
* Browser language.
* <p>Example :<b>utmul=pt-br</b></p>
*/
public function get utmul():String
{
return _info.language.toLowerCase();
}
/**
* Indicates if browser is Java-enabled.
* <p>Example :<b>utmje=1</b></p>
*/
public function get utmje():String
{
return "0"; //not supported
}
/**
* Flash Version.
* <p>Example :<b>utmfl=9.0%20r48</b></p>
*/
public function get utmfl():String
{
if( _config.detectFlash )
{
var v:version = _info.flashVersion;
return v.major+"."+v.minor+" r"+v.build;
}
return "-";
}
/**
* Returns a Variables object representation.
* @return a Variables object representation.
*/
public function toVariables():Variables
{
var variables:Variables = new Variables();
variables.URIencode = true;
variables.utmcs = utmcs;
variables.utmsr = utmsr;
variables.utmsc = utmsc;
variables.utmul = utmul;
variables.utmje = utmje;
variables.utmfl = utmfl;
return variables;
}
/**
* Returns the url String representation of the object.
* @return the url String representation of the object.
*/
public function toURLString():String
{
var v:Variables = toVariables();
return v.toString();
}
}
}
|
replace class Version by core.version
|
replace class Version by core.version
|
ActionScript
|
apache-2.0
|
nsdevaraj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash,minimedj/gaforflash
|
68a458b7e9d5046880ffb44413a22fb0ddf41219
|
src/org/flintparticles/twoD/actions/TweenToZone.as
|
src/org/flintparticles/twoD/actions/TweenToZone.as
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2011
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.twoD.actions
{
import org.flintparticles.common.actions.ActionBase;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.initializers.Initializer;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.twoD.particles.Particle2D;
import org.flintparticles.twoD.zones.Zone2D;
import flash.geom.Point;
[DefaultProperty("zone")]
/**
* The TweenToZone action adjusts the particle's position between two
* locations as it ages. The start location is wherever the particle starts
* from, depending on the emitter and the initializers. The end position is
* a random point within the specified zone. The current position is relative
* to the particle's energy,
* which changes as the particle ages in accordance with the energy easing
* function used. This action should be used in conjunction with the Age action.
*/
public class TweenToZone extends ActionBase implements Initializer
{
private var _zone:Zone2D;
/**
* The constructor creates a TweenToZone action for use by an emitter.
* To add a TweenToZone to all particles created by an emitter, use the
* emitter's addAction method.
*
* @see org.flintparticles.common.emitters.Emitter#addAction()
*
* @param zone The zone for the particle's position when its energy is 0.
*/
public function TweenToZone( zone:Zone2D )
{
_zone = zone;
priority = -10;
}
/**
* The zone for the particle's position when its energy is 0.
*/
public function get zone():Zone2D
{
return _zone;
}
public function set zone( value:Zone2D ):void
{
_zone = value;
}
/**
*
*/
override public function addedToEmitter( emitter:Emitter ):void
{
if( ! emitter.hasInitializer( this ) )
{
emitter.addInitializer( this );
}
}
override public function removedFromEmitter( emitter:Emitter ):void
{
emitter.removeInitializer( this );
}
/**
*
*/
public function initialize( emitter:Emitter, particle:Particle ):void
{
var p:Particle2D = Particle2D( particle );
var pt:Point = _zone.getLocation();
var data:TweenToZoneData = new TweenToZoneData( p.x, p.y, pt.x, pt.y );
p.dictionary[this] = data;
}
/**
* Calculates the current position of the particle based on it's energy.
*
* <p>This method is called by the emitter and need not be called by the
* user.</p>
*
* @param emitter The Emitter that created the particle.
* @param particle The particle to be updated.
* @param time The duration of the frame - used for time based updates.
*
* @see org.flintparticles.common.actions.Action#update()
*/
override public function update( emitter:Emitter, particle:Particle, time:Number ):void
{
var p:Particle2D = Particle2D( particle );
if( ! p.dictionary[this] )
{
initialize( emitter, particle );
}
var data:TweenToZoneData = p.dictionary[this];
p.x = data.endX + data.diffX * p.energy;
p.y = data.endY + data.diffY * p.energy;
}
}
}
class TweenToZoneData
{
public var diffX:Number;
public var diffY:Number;
public var endX:Number;
public var endY:Number;
public function TweenToZoneData( startX:Number, startY:Number, endX:Number, endY:Number )
{
this.diffX = startX - endX;
this.diffY = startY - endY;
this.endX = endX;
this.endY = endY;
}
}
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2011
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.twoD.actions
{
import org.flintparticles.common.actions.ActionBase;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.initializers.Initializer;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.twoD.particles.Particle2D;
import org.flintparticles.twoD.zones.Zone2D;
import flash.geom.Point;
[DefaultProperty("zone")]
/**
* The TweenToZone action adjusts the particle's position between two
* locations as it ages. The start location is wherever the particle starts
* from, depending on the emitter and the initializers. The end position is
* a random point within the specified zone. The current position is relative
* to the particle's energy,
* which changes as the particle ages in accordance with the energy easing
* function used. This action should be used in conjunction with the Age action.
*/
public class TweenToZone extends ActionBase implements Initializer
{
private var _zone:Zone2D;
/**
* The constructor creates a TweenToZone action for use by an emitter.
* To add a TweenToZone to all particles created by an emitter, use the
* emitter's addAction method.
*
* @see org.flintparticles.common.emitters.Emitter#addAction()
*
* @param zone The zone for the particle's position when its energy is 0.
*/
public function TweenToZone( zone:Zone2D=null )
{
_zone = zone;
priority = -10;
}
/**
* The zone for the particle's position when its energy is 0.
*/
public function get zone():Zone2D
{
return _zone;
}
public function set zone( value:Zone2D ):void
{
_zone = value;
}
/**
*
*/
override public function addedToEmitter( emitter:Emitter ):void
{
if( ! emitter.hasInitializer( this ) )
{
emitter.addInitializer( this );
}
}
override public function removedFromEmitter( emitter:Emitter ):void
{
emitter.removeInitializer( this );
}
/**
*
*/
public function initialize( emitter:Emitter, particle:Particle ):void
{
var p:Particle2D = Particle2D( particle );
var pt:Point = _zone.getLocation();
var data:TweenToZoneData = new TweenToZoneData( p.x, p.y, pt.x, pt.y );
p.dictionary[this] = data;
}
/**
* Calculates the current position of the particle based on it's energy.
*
* <p>This method is called by the emitter and need not be called by the
* user.</p>
*
* @param emitter The Emitter that created the particle.
* @param particle The particle to be updated.
* @param time The duration of the frame - used for time based updates.
*
* @see org.flintparticles.common.actions.Action#update()
*/
override public function update( emitter:Emitter, particle:Particle, time:Number ):void
{
var p:Particle2D = Particle2D( particle );
if( ! p.dictionary[this] )
{
initialize( emitter, particle );
}
var data:TweenToZoneData = p.dictionary[this];
p.x = data.endX + data.diffX * p.energy;
p.y = data.endY + data.diffY * p.energy;
}
}
}
class TweenToZoneData
{
public var diffX:Number;
public var diffY:Number;
public var endX:Number;
public var endY:Number;
public function TweenToZoneData( startX:Number, startY:Number, endX:Number, endY:Number )
{
this.diffX = startX - endX;
this.diffY = startY - endY;
this.endX = endX;
this.endY = endY;
}
}
|
Add default parameter to support MXML.
|
Add default parameter to support MXML.
|
ActionScript
|
mit
|
richardlord/Flint
|
d4ad47bc048bd5f8496ef46eb2f9b93bfe1adb1d
|
src/aerys/minko/render/material/basic/BasicShader.as
|
src/aerys/minko/render/material/basic/BasicShader.as
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.DrawCall;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderInstance;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.DiffuseShaderPart;
import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.BlendingSource;
import aerys.minko.type.enum.DepthTest;
import aerys.minko.type.enum.StencilAction;
import aerys.minko.type.enum.TriangleCulling;
/**
* The BasicShader is a simple shader program handling hardware vertex
* animations (skinning and morphing), a diffuse color or a texture and
* a directional light.
*
* <table class="bindingsSummary">
* <tr>
* <th>Property Name</th>
* <th>Source</th>
* <th>Type</th>
* <th>Description</th>
* <th>Requires</th>
* </tr>
* <tr>
* <td>lightEnabled</td>
* <td>Scene</td>
* <td>Boolean</td>
* <td>Whether the light is enabled or not on the scene.</td>
* <td>lightDirection, lightAmbient, lightAmbientColor, lightDiffuse, lightDiffuseColor</td>
* </tr>
* <tr>
* <td>lightDirection</td>
* <td>Scene</td>
* <td>Vector4</td>
* <td>The direction of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightAmbient</td>
* <td>Scene</td>
* <td>Number</td>
* <td>The ambient factor of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightAmbientColor</td>
* <td>Scene</td>
* <td>uint or Vector4</td>
* <td>The ambient color of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightDiffuse</td>
* <td>Scene</td>
* <td>Number</td>
* <td>The diffuse factor of the light</td>
* <td></td>
* </tr>
* <tr>
* <td>lightDiffuseColor</td>
* <td>Scene</td>
* <td>uint or Vector4</td>
* <td>The diffuse color of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightEnabled</td>
* <td>Mesh</td>
* <td>Boolean</td>
* <td>Whether the light is enabled or not on the mesh.</td>
* <td></td>
* </tr>
* <tr>
* <td>diffuseMap</td>
* <td>Mesh</td>
* <td>TextureResource</td>
* <td>The texture to use for rendering.</td>
* <td></td>
* </tr>
* <tr>
* <td>diffuseColor</td>
* <td>Mesh</td>
* <td>uint or Vector4</td>
* <td>The color to use for rendering. If the "diffuseMap" binding is set, this
* value is not used.</td>
* <td></td>
* </tr>
* </table>
*
* @author Jean-Marc Le Roux
*
*/
public class BasicShader extends Shader
{
private var _vertexAnimationPart : VertexAnimationShaderPart = null;
private var _diffuseShaderPart : DiffuseShaderPart = null;
private var _vertexNormal : SFloat = null;
protected function get diffuse() : DiffuseShaderPart
{
return _diffuseShaderPart;
}
protected function get vertexAnimation() : VertexAnimationShaderPart
{
return _vertexAnimationPart;
}
/**
* @param priority Default value is 0.
* @param target Default value is null.
*/
public function BasicShader(target : RenderTarget = null,
priority : Number = 0.)
{
super(target, priority);
// init shader parts
_vertexAnimationPart = new VertexAnimationShaderPart(this);
_diffuseShaderPart = new DiffuseShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
super.initializeSettings(settings);
// depth test
settings.depthWriteEnabled = meshBindings.getConstant(
BasicProperties.DEPTH_WRITE_ENABLED, true
);
settings.depthTest = meshBindings.getConstant(
BasicProperties.DEPTH_TEST, DepthTest.LESS
);
settings.triangleCulling = meshBindings.getConstant(
BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK
);
// stencil operations
settings.stencilTriangleFace = meshBindings.getConstant(
BasicProperties.STENCIL_TRIANGLE_FACE, TriangleCulling.BOTH
);
settings.stencilCompareMode = meshBindings.getConstant(
BasicProperties.STENCIL_COMPARE_MODE, DepthTest.EQUAL
);
settings.stencilActionOnBothPass = meshBindings.getConstant(
BasicProperties.STENCIL_ACTION_BOTH_PASS, StencilAction.KEEP
);
settings.stencilActionOnDepthFail = meshBindings.getConstant(
BasicProperties.STENCIL_ACTION_DEPTH_FAIL, StencilAction.KEEP
);
settings.stencilActionOnDepthPassStencilFail = meshBindings.getConstant(
BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, StencilAction.KEEP
);
settings.stencilReferenceValue = meshBindings.getConstant(
BasicProperties.STENCIL_REFERENCE_VALUE, 0
);
settings.stencilReadMask = meshBindings.getConstant(
BasicProperties.STENCIL_READ_MASK, 255
);
settings.stencilWriteMask = meshBindings.getConstant(
BasicProperties.STENCIL_WRITE_MASK, 255
);
// blending and priority
var blending : uint = meshBindings.getConstant(
BasicProperties.BLENDING, Blending.NORMAL
);
if ((blending & 0xff) == BlendingSource.SOURCE_ALPHA)
{
settings.priority -= 0.5;
settings.depthSortDrawCalls = true;
}
settings.blending = blending;
settings.enabled = true;
settings.scissorRectangle = null;
}
/**
* @return The position of the vertex in clip space (normalized
* screen space).
*
*/
override protected function getVertexPosition() : SFloat
{
var triangleCulling : uint = meshBindings.getConstant(
BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK
);
_vertexNormal = _vertexAnimationPart.getAnimatedVertexNormal();
// flip the normal when the triangle culling is flipped
if (triangleCulling == TriangleCulling.FRONT)
_vertexNormal = multiply(vertexNormal, float4(-1, -1, -1, 1));
_vertexNormal = deltaLocalToWorld(_vertexNormal);
return localToScreen(
_vertexAnimationPart.getAnimatedVertexPosition()
);
}
/**
* @return The pixel color using a diffuse color/map and an optional
* directional light.
*/
override protected function getPixelColor() : SFloat
{
var diffuse : SFloat = _diffuseShaderPart.getDiffuse();
if (meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD))
{
var alphaThreshold : SFloat = meshBindings.getParameter(
BasicProperties.ALPHA_THRESHOLD, 1
);
kill(subtract(0.5, lessThan(diffuse.w, alphaThreshold)));
}
return diffuse;
}
}
}
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.DrawCall;
import aerys.minko.render.RenderTarget;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderInstance;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.DiffuseShaderPart;
import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart;
import aerys.minko.type.enum.Blending;
import aerys.minko.type.enum.BlendingSource;
import aerys.minko.type.enum.DepthTest;
import aerys.minko.type.enum.StencilAction;
import aerys.minko.type.enum.TriangleCulling;
/**
* The BasicShader is a simple shader program handling hardware vertex
* animations (skinning and morphing), a diffuse color or a texture and
* a directional light.
*
* <table class="bindingsSummary">
* <tr>
* <th>Property Name</th>
* <th>Source</th>
* <th>Type</th>
* <th>Description</th>
* <th>Requires</th>
* </tr>
* <tr>
* <td>lightEnabled</td>
* <td>Scene</td>
* <td>Boolean</td>
* <td>Whether the light is enabled or not on the scene.</td>
* <td>lightDirection, lightAmbient, lightAmbientColor, lightDiffuse, lightDiffuseColor</td>
* </tr>
* <tr>
* <td>lightDirection</td>
* <td>Scene</td>
* <td>Vector4</td>
* <td>The direction of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightAmbient</td>
* <td>Scene</td>
* <td>Number</td>
* <td>The ambient factor of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightAmbientColor</td>
* <td>Scene</td>
* <td>uint or Vector4</td>
* <td>The ambient color of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightDiffuse</td>
* <td>Scene</td>
* <td>Number</td>
* <td>The diffuse factor of the light</td>
* <td></td>
* </tr>
* <tr>
* <td>lightDiffuseColor</td>
* <td>Scene</td>
* <td>uint or Vector4</td>
* <td>The diffuse color of the light.</td>
* <td></td>
* </tr>
* <tr>
* <td>lightEnabled</td>
* <td>Mesh</td>
* <td>Boolean</td>
* <td>Whether the light is enabled or not on the mesh.</td>
* <td></td>
* </tr>
* <tr>
* <td>diffuseMap</td>
* <td>Mesh</td>
* <td>TextureResource</td>
* <td>The texture to use for rendering.</td>
* <td></td>
* </tr>
* <tr>
* <td>diffuseColor</td>
* <td>Mesh</td>
* <td>uint or Vector4</td>
* <td>The color to use for rendering. If the "diffuseMap" binding is set, this
* value is not used.</td>
* <td></td>
* </tr>
* </table>
*
* @author Jean-Marc Le Roux
*
*/
public class BasicShader extends Shader
{
private var _vertexAnimationPart : VertexAnimationShaderPart = null;
private var _diffuseShaderPart : DiffuseShaderPart = null;
private var _vertexNormal : SFloat = null;
protected function get diffuse() : DiffuseShaderPart
{
return _diffuseShaderPart;
}
protected function get vertexAnimation() : VertexAnimationShaderPart
{
return _vertexAnimationPart;
}
/**
* @param priority Default value is 0.
* @param target Default value is null.
*/
public function BasicShader(target : RenderTarget = null,
priority : Number = 0.)
{
super(target, priority);
// init shader parts
_vertexAnimationPart = new VertexAnimationShaderPart(this);
_diffuseShaderPart = new DiffuseShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
super.initializeSettings(settings);
// depth test
settings.depthWriteEnabled = meshBindings.getConstant(
BasicProperties.DEPTH_WRITE_ENABLED, true
);
settings.depthTest = meshBindings.getConstant(
BasicProperties.DEPTH_TEST, DepthTest.LESS
);
settings.triangleCulling = meshBindings.getConstant(
BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK
);
// stencil operations
settings.stencilTriangleFace = meshBindings.getConstant(
BasicProperties.STENCIL_TRIANGLE_FACE, TriangleCulling.BOTH
);
settings.stencilCompareMode = meshBindings.getConstant(
BasicProperties.STENCIL_COMPARE_MODE, DepthTest.EQUAL
);
settings.stencilActionOnBothPass = meshBindings.getConstant(
BasicProperties.STENCIL_ACTION_BOTH_PASS, StencilAction.KEEP
);
settings.stencilActionOnDepthFail = meshBindings.getConstant(
BasicProperties.STENCIL_ACTION_DEPTH_FAIL, StencilAction.KEEP
);
settings.stencilActionOnDepthPassStencilFail = meshBindings.getConstant(
BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, StencilAction.KEEP
);
settings.stencilReferenceValue = meshBindings.getConstant(
BasicProperties.STENCIL_REFERENCE_VALUE, 0
);
settings.stencilReadMask = meshBindings.getConstant(
BasicProperties.STENCIL_READ_MASK, 255
);
settings.stencilWriteMask = meshBindings.getConstant(
BasicProperties.STENCIL_WRITE_MASK, 255
);
// blending and priority
var blending : uint = meshBindings.getConstant(
BasicProperties.BLENDING, Blending.NORMAL
);
if ((blending & 0xff) == BlendingSource.SOURCE_ALPHA)
{
settings.priority -= 0.5;
settings.depthSortDrawCalls = true;
}
settings.blending = blending;
settings.enabled = true;
settings.scissorRectangle = null;
}
/**
* @return The position of the vertex in clip space (normalized
* screen space).
*
*/
override protected function getVertexPosition() : SFloat
{
var triangleCulling : uint = meshBindings.getConstant(
BasicProperties.TRIANGLE_CULLING, TriangleCulling.BACK
);
_vertexNormal = _vertexAnimationPart.getAnimatedVertexNormal();
// flip the normal when the triangle culling is flipped
if (triangleCulling == TriangleCulling.FRONT)
_vertexNormal = multiply(vertexNormal, float4(-1, -1, -1, 1));
_vertexNormal = deltaLocalToWorld(_vertexNormal);
return localToScreen(
_vertexAnimationPart.getAnimatedVertexPosition()
);
}
/**
* @return The pixel color using a diffuse color/map and an optional
* directional light.
*/
override protected function getPixelColor() : SFloat
{
var diffuse : SFloat = _diffuseShaderPart.getDiffuseColor();
if (meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD))
{
var alphaThreshold : SFloat = meshBindings.getParameter(
BasicProperties.ALPHA_THRESHOLD, 1
);
kill(subtract(0.5, lessThan(diffuse.w, alphaThreshold)));
}
return diffuse;
}
}
}
|
update shader to use DiffuseShaderPart.getDiffuseColor() instead of DiffuseShaderPart.getDiffuse()
|
update shader to use DiffuseShaderPart.getDiffuseColor() instead of DiffuseShaderPart.getDiffuse()
|
ActionScript
|
mit
|
aerys/minko-as3
|
768bcddfcce54d93dbe35e7393813ad8c7b4c597
|
FlexUnit4/src/org/flexunit/runners/model/TestClass.as
|
FlexUnit4/src/org/flexunit/runners/model/TestClass.as
|
/**
* Copyright (c) 2009 Digital Primates IT Consulting Group
*
* 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.
*
* @author Michael Labriola <[email protected]>
* @version
**/
package org.flexunit.runners.model {
import flash.utils.Dictionary;
import flex.lang.reflect.Klass;
import flex.lang.reflect.Method;
import mx.collections.IViewCursor;
import org.flexunit.runner.manipulation.MethodSorter;
/**
* Wraps a class to be run, providing method validation and annotation searching
*/
public class TestClass {
private var klass:Class;
private var _klassInfo:Klass
private var metaDataDictionary:Dictionary = new Dictionary( false );
//TODO: I'm guessing JDK should be replaced with something else
/**
* Creates a {@code TestClass} wrapping {@code klass}. Each time this
* constructor executes, the class is scanned for annotations, which can be
* an expensive process (we hope in future JDK's it will not be.) Therefore,
* try to share instances of {@code TestClass} where possible.
*/
public function TestClass( klass:Class ) {
this.klass = klass;
_klassInfo = new Klass( klass );
//Ensures that the Order argument of the Test, Begin, After and BeforeClass and AfterClass are respected
var sorter:MethodSorter = new MethodSorter( _klassInfo.methods );
sorter.sort();
var cursor:IViewCursor = sorter.createCursor();
var method:Method;
while (!cursor.afterLast ) {
method = cursor.current as Method;
addToMetaDataDictionary( new FrameworkMethod( method ) );
cursor.moveNext();
}
}
public function get klassInfo():Klass {
return _klassInfo;
}
private function addToMetaDataDictionary( testMethod:FrameworkMethod ):void {
var metaDataList:XMLList = testMethod.metadata;
var metaTag:String;
var entry:Array;
if ( metaDataList ) {
for ( var i:int=0; i<metaDataList.length(); i++ ) {
metaTag = metaDataList[ i ].@name;
entry = metaDataDictionary[ metaTag ];
if ( !entry ) {
metaDataDictionary[ metaTag ] = new Array();
entry = metaDataDictionary[ metaTag ]
}
entry.push( testMethod );
}
}
}
/**
* Returns the underlying class.
*/
public function get asClass():Class {
return klass;
}
/**
* Returns the class's name.
*/
public function get name():String {
if (!klassInfo) {
return "null";
}
return klassInfo.name;
}
/**
* Returns the metadata on this class
*/
public function get metadata():XMLList {
if ( !klassInfo ) {
return null;
}
return klassInfo.metadata;
}
/**
* Returns, efficiently, all the non-overridden methods in this class and
* its superclasses that contain the metadata tag {@code metaTag}.
*/
public function getMetaDataMethods( metaTag:String ):Array {
var methodArray:Array;
methodArray = metaDataDictionary[ metaTag ];
if ( !methodArray ) {
methodArray = new Array();
}
return methodArray;
}
public function toString():String {
var str:String = "TestClass ";
if ( _klassInfo ) {
str += ( "(" + _klassInfo.name + ")" );
}
return str;
}
}
}
|
/**
* Copyright (c) 2009 Digital Primates IT Consulting Group
*
* 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.
*
* @author Michael Labriola <[email protected]>
* @version
**/
package org.flexunit.runners.model {
import flash.utils.Dictionary;
import flex.lang.reflect.Klass;
import flex.lang.reflect.Method;
import mx.collections.IViewCursor;
import org.flexunit.runner.manipulation.MethodSorter;
/**
* Wraps a class to be run, providing method validation and annotation searching
*/
public class TestClass {
private var klass:Class;
private var _klassInfo:Klass
private var metaDataDictionary:Dictionary = new Dictionary( false );
//TODO: I'm guessing JDK should be replaced with something else
/**
* Creates a {@code TestClass} wrapping {@code klass}. Each time this
* constructor executes, the class is scanned for annotations, which can be
* an expensive process (we hope in future JDK's it will not be.) Therefore,
* try to share instances of {@code TestClass} where possible.
*/
public function TestClass( klass:Class ) {
this.klass = klass;
_klassInfo = new Klass( klass );
//Ensures that the Order argument of the Test, Begin, After and BeforeClass and AfterClass are respected
var sorter:MethodSorter = new MethodSorter( _klassInfo.methods );
sorter.sort();
var cursor:IViewCursor = sorter.createCursor();
var method:Method;
while (!cursor.afterLast ) {
method = cursor.current as Method;
addToMetaDataDictionary( new FrameworkMethod( method ) );
cursor.moveNext();
}
}
public function get klassInfo():Klass {
return _klassInfo;
}
private function addToMetaDataDictionary( testMethod:FrameworkMethod ):void {
var metaDataList:XMLList = testMethod.metadata;
var metaTag:String;
var entry:Array;
if ( metaDataList ) {
for ( var i:int=0; i<metaDataList.length(); i++ ) {
metaTag = metaDataList[ i ].@name;
entry = metaDataDictionary[ metaTag ];
if ( !entry ) {
metaDataDictionary[ metaTag ] = new Array();
entry = metaDataDictionary[ metaTag ]
}
var found:Boolean = false;
//Before we push this onto the stack, we take a quick pass to ensure it is not already there
//this covers the case where someone double flags a test with a piece of metadata
//bugID="FXU-33")
for ( var j:int=0; j<entry.length; j++ ) {
if ( ( entry[ j ] as FrameworkMethod ).method === testMethod.method ) {
found = true;
break;
}
}
if ( !found ) {
entry.push( testMethod );
}
}
}
}
/**
* Returns the underlying class.
*/
public function get asClass():Class {
return klass;
}
/**
* Returns the class's name.
*/
public function get name():String {
if (!klassInfo) {
return "null";
}
return klassInfo.name;
}
/**
* Returns the metadata on this class
*/
public function get metadata():XMLList {
if ( !klassInfo ) {
return null;
}
return klassInfo.metadata;
}
/**
* Returns, efficiently, all the non-overridden methods in this class and
* its superclasses that contain the metadata tag {@code metaTag}.
*/
public function getMetaDataMethods( metaTag:String ):Array {
var methodArray:Array;
methodArray = metaDataDictionary[ metaTag ];
if ( !methodArray ) {
methodArray = new Array();
}
return methodArray;
}
public function toString():String {
var str:String = "TestClass ";
if ( _klassInfo ) {
str += ( "(" + _klassInfo.name + ")" );
}
return str;
}
}
}
|
Fix for FXU-33
|
Fix for FXU-33
git-svn-id: 9278a788294a4258aac04586390fc35fb4a5f335@7348 a9308255-753e-0410-a2e9-80b3fbc4fff6
|
ActionScript
|
apache-2.0
|
apache/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit,SlavaRa/flex-flexunit,apache/flex-flexunit,apache/flex-flexunit,SlavaRa/flex-flexunit
|
1c92fe124900d7eaa13edb74c09a57912816ef95
|
src/aerys/minko/render/resource/texture/TextureResource.as
|
src/aerys/minko/render/resource/texture/TextureResource.as
|
package aerys.minko.render.resource.texture
{
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.enum.SamplerFormat;
import flash.display.BitmapData;
import flash.display3D.Context3DTextureFormat;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Matrix;
import flash.utils.ByteArray;
/**
* @inheritdoc
* @author Jean-Marc Le Roux
*
*/
public class TextureResource implements ITextureResource
{
private static const MAX_SIZE : uint = 2048;
private static const TMP_MATRIX : Matrix = new Matrix();
private static const FORMAT_BGRA : String = Context3DTextureFormat.BGRA
private static const FORMAT_COMPRESSED : String = Context3DTextureFormat.COMPRESSED;
private static const FORMAT_COMPRESSED_ALPHA : String = Context3DTextureFormat.COMPRESSED_ALPHA;
private static const TEXTURE_FORMAT_TO_SAMPLER : Array = []
{
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_BGRA] = SamplerFormat.RGBA;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED] = SamplerFormat.COMPRESSED;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED_ALPHA] = SamplerFormat.COMPRESSED_ALPHA;
}
private var _texture : Texture = null;
private var _mipmap : Boolean = false;
private var _bitmapData : BitmapData = null;
private var _atf : ByteArray = null;
private var _atfFormat : uint = 0;
private var _format : String = FORMAT_BGRA;
private var _width : Number = 0;
private var _height : Number = 0;
private var _update : Boolean = false;
public function get format() : uint
{
return TEXTURE_FORMAT_TO_SAMPLER[_format];
}
public function get mipMapping() : Boolean
{
return _mipmap;
}
public function get width() : uint
{
return _width;
}
public function get height() : uint
{
return _height;
}
public function TextureResource(width : uint = 0,
height : uint = 0)
{
_width = width;
_height = height;
}
public function setContentFromBitmapData(bitmapData : BitmapData,
mipmap : Boolean,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = bitmapData.width;
var bitmapHeight : uint = bitmapData.height;
var w : int = 0;
var h : int = 0;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (w > MAX_SIZE)
w = MAX_SIZE;
if (h > MAX_SIZE)
h = MAX_SIZE;
if (_bitmapData == null || _bitmapData.width != w || _bitmapData.height != h)
_bitmapData = new BitmapData(w, h, bitmapData.transparent, 0);
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_bitmapData.draw(bitmapData, TMP_MATRIX);
}
else
{
_bitmapData.draw(bitmapData);
}
if (_texture
&& (mipmap != _mipmap
|| bitmapData.width != _width
|| bitmapData.height != _height))
{
_texture.dispose();
_texture = null;
}
_width = _bitmapData.width;
_height = _bitmapData.height;
_mipmap = mipmap;
_update = true;
}
public function setContentFromATF(atf : ByteArray) : void
{
_atf = atf;
_bitmapData = null;
_update = true;
var oldWidth : Number = _width;
var oldHeight : Number = _height;
var oldMipmap : Boolean = _mipmap;
atf.position = 6;
var formatByte : uint = atf.readUnsignedByte();
_atfFormat = formatByte & 7;
_width = 1 << atf.readUnsignedByte();
_height = 1 << atf.readUnsignedByte();
_mipmap = atf.readUnsignedByte() > 1;
atf.position = 0;
if (_atfFormat == 5)
_format = FORMAT_COMPRESSED_ALPHA;
else if (_atfFormat == 3)
_format = FORMAT_COMPRESSED;
if (_texture
&& (oldMipmap != _mipmap
|| oldWidth != _width
|| oldHeight != _height))
{
_texture.dispose();
_texture = null;
}
}
public function getTexture(context : Context3DResource) : TextureBase
{
if (!_texture && _width && _height)
{
if (_texture)
_texture.dispose();
_texture = context.createTexture(
_width,
_height,
_format,
_bitmapData == null && _atf == null
);
}
if (_update)
{
_update = false;
uploadBitmapDataWithMipMaps();
}
_atf = null;
_bitmapData = null;
return _texture;
}
private function uploadBitmapDataWithMipMaps() : void
{
if (_bitmapData)
{
if (_mipmap)
{
var level : uint = 0;
var size : uint = _width > _height ? _width : _height;
var transparent : Boolean = _bitmapData.transparent;
var tmp : BitmapData = new BitmapData(size, size, transparent, 0);
var transform : Matrix = new Matrix();
while (size >= 1)
{
tmp.draw(_bitmapData, transform, null, null, null, true);
_texture.uploadFromBitmapData(tmp, level);
transform.scale(.5, .5);
level++;
size >>= 1;
if (tmp.transparent)
tmp.fillRect(tmp.rect, 0);
}
tmp.dispose();
}
else
{
_texture.uploadFromBitmapData(_bitmapData, 0);
}
_bitmapData.dispose();
}
else if (_atf)
{
_texture.uploadCompressedTextureFromByteArray(_atf, 0);
}
}
public function dispose() : void
{
if (_texture)
{
_texture.dispose();
_texture = null;
}
}
}
}
|
package aerys.minko.render.resource.texture
{
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.enum.SamplerFormat;
import flash.display.BitmapData;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Matrix;
import flash.utils.ByteArray;
/**
* @inheritdoc
* @author Jean-Marc Le Roux
*
*/
public class TextureResource implements ITextureResource
{
private static const MAX_SIZE : uint = 2048;
private static const TMP_MATRIX : Matrix = new Matrix();
private static const FORMAT_BGRA : String = 'bgra';
private static const FORMAT_COMPRESSED : String = 'compressed';
private static const FORMAT_COMPRESSED_ALPHA : String = 'compressedAlpha';
private static const TEXTURE_FORMAT_TO_SAMPLER : Array = []
{
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_BGRA] = SamplerFormat.RGBA;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED] = SamplerFormat.COMPRESSED;
TEXTURE_FORMAT_TO_SAMPLER[FORMAT_COMPRESSED_ALPHA] = SamplerFormat.COMPRESSED_ALPHA;
}
private var _texture : Texture;
private var _mipmap : Boolean;
private var _bitmapData : BitmapData;
private var _atf : ByteArray;
private var _atfFormat : uint;
private var _format : String;
private var _width : Number;
private var _height : Number;
private var _update : Boolean;
public function get format() : uint
{
return TEXTURE_FORMAT_TO_SAMPLER[_format];
}
public function get mipMapping() : Boolean
{
return _mipmap;
}
public function get width() : uint
{
return _width;
}
public function get height() : uint
{
return _height;
}
public function TextureResource(width : uint = 0,
height : uint = 0)
{
_width = width;
_height = height;
_format = FORMAT_BGRA;
}
public function setContentFromBitmapData(bitmapData : BitmapData,
mipmap : Boolean,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = bitmapData.width;
var bitmapHeight : uint = bitmapData.height;
var w : int = 0;
var h : int = 0;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (w > MAX_SIZE)
w = MAX_SIZE;
if (h > MAX_SIZE)
h = MAX_SIZE;
if (_bitmapData == null || _bitmapData.width != w || _bitmapData.height != h)
_bitmapData = new BitmapData(w, h, bitmapData.transparent, 0);
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_bitmapData.draw(bitmapData, TMP_MATRIX);
}
else
{
_bitmapData.draw(bitmapData);
}
if (_texture
&& (_format != FORMAT_BGRA
|| mipmap != _mipmap
|| bitmapData.width != _width
|| bitmapData.height != _height))
{
_texture.dispose();
_texture = null;
}
_width = _bitmapData.width;
_height = _bitmapData.height;
_format = FORMAT_BGRA;
_mipmap = mipmap;
_update = true;
}
public function setContentFromATF(atf : ByteArray) : void
{
_atf = atf;
_bitmapData = null;
_update = true;
var oldWidth : Number = _width;
var oldHeight : Number = _height;
var oldMipmap : Boolean = _mipmap;
var oldFormat : String = _format;
atf.position = 6;
var formatByte : uint = atf.readUnsignedByte();
_atfFormat = formatByte & 7;
_width = 1 << atf.readUnsignedByte();
_height = 1 << atf.readUnsignedByte();
_mipmap = atf.readUnsignedByte() > 1;
atf.position = 0;
if (_atfFormat == 5)
_format = FORMAT_COMPRESSED_ALPHA;
else if (_atfFormat == 3)
_format = FORMAT_COMPRESSED;
else
_format = FORMAT_BGRA;
if (_texture
&& (oldFormat != _format
|| oldMipmap != _mipmap
|| oldWidth != _width
|| oldHeight != _height))
{
_texture.dispose();
_texture = null;
}
}
public function getTexture(context : Context3DResource) : TextureBase
{
if (!_texture && _width && _height)
{
if (_texture)
_texture.dispose();
_texture = context.createTexture(
_width,
_height,
_format,
_bitmapData == null && _atf == null
);
}
if (_update)
{
_update = false;
uploadBitmapDataWithMipMaps();
}
_atf = null;
_bitmapData = null;
return _texture;
}
private function uploadBitmapDataWithMipMaps() : void
{
if (_bitmapData)
{
if (_mipmap)
{
var level : uint = 0;
var size : uint = _width > _height ? _width : _height;
var transparent : Boolean = _bitmapData.transparent;
var tmp : BitmapData = new BitmapData(size, size, transparent, 0);
var transform : Matrix = new Matrix();
while (size >= 1)
{
tmp.draw(_bitmapData, transform, null, null, null, true);
_texture.uploadFromBitmapData(tmp, level);
transform.scale(.5, .5);
level++;
size >>= 1;
if (tmp.transparent)
tmp.fillRect(tmp.rect, 0);
}
tmp.dispose();
}
else
{
_texture.uploadFromBitmapData(_bitmapData, 0);
}
_bitmapData.dispose();
}
else if (_atf)
{
_texture.uploadCompressedTextureFromByteArray(_atf, 0);
}
}
public function dispose() : void
{
if (_texture)
{
_texture.dispose();
_texture = null;
}
}
}
}
|
use string literals for texture formats to avoid compatibility issues
|
use string literals for texture formats to avoid compatibility issues
|
ActionScript
|
mit
|
aerys/minko-as3
|
4f9e27ccf3882edb8abfb752f207ef5d8a5071c5
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/FlexibleFirstChildHorizontalLayout.as
|
frameworks/as/projects/FlexJSJX/src/org/apache/flex/html/beads/layouts/FlexibleFirstChildHorizontalLayout.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IParent;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The FlexibleFirstChildHorizontalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* horizontally in one row, separating them according to
* CSS layout rules for margin and padding styles. But it
* will size the first child to take up as much or little
* room as possible.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class FlexibleFirstChildHorizontalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function FlexibleFirstChildHorizontalLayout()
{
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener("layoutNeeded", changeHandler);
IEventDispatcher(value).addEventListener("widthChanged", changeHandler);
IEventDispatcher(value).addEventListener("childrenAdded", changeHandler);
IEventDispatcher(value).addEventListener("itemsCreated", changeHandler);
}
private function changeHandler(event:Event):void
{
var layoutParent:ILayoutParent = _strand.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParent = layoutParent.contentView;
var n:int = contentView.numElements;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var maxHeight:Number = 0;
var verticalMargins:Array = [];
for (var i:int = n - 1; i >= 0; i--)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
if (margin is Array)
{
if (margin.length == 1)
marginLeft = marginTop = marginRight = marginBottom = margin[0];
else if (margin.length <= 3)
{
marginLeft = marginRight = margin[1];
marginTop = marginBottom = margin[0];
}
else if (margin.length == 4)
{
marginLeft = margin[3];
marginBottom = margin[2];
marginRight = margin[1];
marginTop = margin[0];
}
}
else if (margin == null)
{
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
}
else
{
marginLeft = marginTop = marginBottom = marginRight = margin;
}
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmr:Number;
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
child.y = mt;
maxHeight = Math.max(maxHeight, ml + child.height + mr);
var xx:Number = layoutParent.resizableView.width;
if (i == 0)
{
child.x = ml;
child.width = xx - mr;
}
else
child.x = xx - child.width - mr;
xx -= child.width + mr + ml;
lastmr = mr;
var valign:Object = ValuesManager.valuesImpl.getValue(child, "vertical-align");
verticalMargins.push({ marginTop: mt, marginBottom: mb, valign: valign });
}
for (i = 0; i < n; i++)
{
var obj:Object = verticalMargins[0]
child = contentView.getElementAt(i) as IUIBase;
if (obj.valign == "middle")
child.y = maxHeight - child.height / 2;
else if (valign == "bottom")
child.y = maxHeight - child.height - obj.marginBottom;
else
child.y = obj.marginTop;
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IParent;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The FlexibleFirstChildHorizontalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* horizontally in one row, separating them according to
* CSS layout rules for margin and padding styles. But it
* will size the first child to take up as much or little
* room as possible.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class FlexibleFirstChildHorizontalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function FlexibleFirstChildHorizontalLayout()
{
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
IEventDispatcher(value).addEventListener("layoutNeeded", changeHandler);
IEventDispatcher(value).addEventListener("widthChanged", changeHandler);
IEventDispatcher(value).addEventListener("childrenAdded", changeHandler);
IEventDispatcher(value).addEventListener("itemsCreated", changeHandler);
}
private function changeHandler(event:Event):void
{
var layoutParent:ILayoutParent = _strand.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParent = layoutParent.contentView;
var n:int = contentView.numElements;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var maxHeight:Number = 0;
var verticalMargins:Array = [];
var xx:Number = layoutParent.resizableView.width;
var padding:Object = determinePadding();
xx -= padding.paddingLeft + padding.paddingRight;
for (var i:int = n - 1; i >= 0; i--)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
if (margin is Array)
{
if (margin.length == 1)
marginLeft = marginTop = marginRight = marginBottom = margin[0];
else if (margin.length <= 3)
{
marginLeft = marginRight = margin[1];
marginTop = marginBottom = margin[0];
}
else if (margin.length == 4)
{
marginLeft = margin[3];
marginBottom = margin[2];
marginRight = margin[1];
marginTop = margin[0];
}
}
else if (margin == null)
{
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
}
else
{
marginLeft = marginTop = marginBottom = marginRight = margin;
}
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmr:Number;
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
child.y = mt;
maxHeight = Math.max(maxHeight, ml + child.height + mr);
if (i == 0)
{
child.x = ml;
child.width = xx - mr;
}
else
child.x = xx - child.width - mr;
xx -= child.width + mr + ml;
lastmr = mr;
var valign:Object = ValuesManager.valuesImpl.getValue(child, "vertical-align");
verticalMargins.push({ marginTop: mt, marginBottom: mb, valign: valign });
}
for (i = 0; i < n; i++)
{
var obj:Object = verticalMargins[0]
child = contentView.getElementAt(i) as IUIBase;
if (obj.valign == "middle")
child.y = maxHeight - child.height / 2;
else if (valign == "bottom")
child.y = maxHeight - child.height - obj.marginBottom;
else
child.y = obj.marginTop;
}
layoutParent.resizableView.height = maxHeight;
}
// TODO (aharui): utility class or base class
/**
* Determines the top and left padding values, if any, as set by
* padding style values. This includes "padding" for all padding values
* as well as "padding-left" and "padding-top".
*
* Returns an object with paddingLeft and paddingTop properties.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
protected function determinePadding():Object
{
var paddingLeft:Object;
var paddingTop:Object;
var paddingRight:Object;
var padding:Object = ValuesManager.valuesImpl.getValue(_strand, "padding");
if (typeof(padding) == "Array")
{
if (padding.length == 1)
paddingLeft = paddingTop = paddingRight = padding[0];
else if (padding.length <= 3)
{
paddingLeft = padding[1];
paddingTop = padding[0];
paddingRight = padding[1];
}
else if (padding.length == 4)
{
paddingLeft = padding[3];
paddingTop = padding[0];
paddingRight = padding[1];
}
}
else if (padding == null)
{
paddingLeft = ValuesManager.valuesImpl.getValue(_strand, "padding-left");
paddingTop = ValuesManager.valuesImpl.getValue(_strand, "padding-top");
paddingRight = ValuesManager.valuesImpl.getValue(_strand, "padding-right");
}
else
{
paddingLeft = paddingTop = paddingRight = padding;
}
var pl:Number = Number(paddingLeft);
var pt:Number = Number(paddingTop);
var pr:Number = Number(paddingRight);
return {paddingLeft:pl, paddingTop:pt, paddingRight:pr};
}
}
}
|
handle padding
|
handle padding
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
e8115793802b69419955484caeeb45dd604309b6
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
dolly-framework/src/main/actionscript/dolly/Cloner.as
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.IMetadataContainer;
import org.as3commons.reflect.Type;
import org.as3commons.reflect.Variable;
use namespace dolly_internal;
public class Cloner {
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function isVariableCloneable(variable:Variable, skipMetadataChecking:Boolean = true):Boolean {
return !variable.isStatic && (skipMetadataChecking || variable.hasMetadata(MetadataName.CLONEABLE));
}
private static function isAccessorCloneable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean {
return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() &&
(skipMetadataChecking || accessor.hasMetadata(MetadataName.CLONEABLE));
}
dolly_internal static function getCloneableFieldsForType(type:Type):Vector.<Field> {
const result:Vector.<Field> = new Vector.<Field>();
var variable:Variable;
var accessor:Accessor;
const isClassCloneable:Boolean = isTypeCloneable(type);
if (isClassCloneable) {
for each(variable in type.variables) {
if (isVariableCloneable(variable)) {
result.push(variable);
}
}
for each(accessor in type.accessors) {
if (isAccessorCloneable(accessor)) {
result.push(accessor);
}
}
} else {
const metadataContainers:Array = type.getMetadataContainers(MetadataName.CLONEABLE);
for each(var metadataContainer:IMetadataContainer in metadataContainers) {
if (metadataContainer is Variable) {
variable = metadataContainer as Variable;
if (isVariableCloneable(variable, false)) {
result.push(variable);
}
} else if (metadataContainer is Accessor) {
accessor = metadataContainer as Accessor;
if (isAccessorCloneable(accessor, false)) {
result.push(accessor);
}
}
}
}
return result;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
const clone:* = new (type.clazz)();
const fieldsToClone:Vector.<Field> = getCloneableFieldsForType(type);
var name:String;
for each(var field:Field in fieldsToClone) {
name = field.name;
clone[name] = source[name];
}
return clone;
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.errors.CloningError;
import dolly.core.metadata.MetadataName;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.Field;
import org.as3commons.reflect.IMetadataContainer;
import org.as3commons.reflect.Type;
import org.as3commons.reflect.Variable;
use namespace dolly_internal;
public class Cloner {
private static function isTypeCloneable(type:Type):Boolean {
return type.hasMetadata(MetadataName.CLONEABLE);
}
private static function isVariableCloneable(variable:Variable, skipMetadataChecking:Boolean = true):Boolean {
return !variable.isStatic && (skipMetadataChecking || variable.hasMetadata(MetadataName.CLONEABLE));
}
private static function isAccessorCloneable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean {
return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() &&
(skipMetadataChecking || accessor.hasMetadata(MetadataName.CLONEABLE));
}
dolly_internal static function getCloneableFieldsForType(type:Type):Vector.<Field> {
const result:Vector.<Field> = new Vector.<Field>();
var variable:Variable;
var accessor:Accessor;
const isClassCloneable:Boolean = isTypeCloneable(type);
if (isClassCloneable) {
for each(variable in type.variables) {
if (isVariableCloneable(variable)) {
result.push(variable);
}
}
for each(accessor in type.accessors) {
if (isAccessorCloneable(accessor)) {
result.push(accessor);
}
}
} else {
const metadataContainers:Array = type.getMetadataContainers(MetadataName.CLONEABLE);
for each(var metadataContainer:IMetadataContainer in metadataContainers) {
if (metadataContainer is Variable) {
variable = metadataContainer as Variable;
if (isVariableCloneable(variable, false)) {
result.push(variable);
}
} else if (metadataContainer is Accessor) {
accessor = metadataContainer as Accessor;
if (isAccessorCloneable(accessor, false)) {
result.push(accessor);
}
}
}
}
return result;
}
public static function clone(source:*):* {
const type:Type = Type.forInstance(source);
if (!isTypeCloneable(type)) {
throw new CloningError(
CloningError.CLASS_IS_NOT_CLONEABLE_MESSAGE,
CloningError.CLASS_IS_NOT_CLONEABLE_CODE
);
}
const clone:* = new (type.clazz)();
// Find all public writable fields in a hierarchy of a source object
// and assign their values to a clone object.
const fieldsToClone:Vector.<Field> = getCloneableFieldsForType(type);
var name:String;
for each(var field:Field in fieldsToClone) {
name = field.name;
clone[name] = source[name];
}
return clone;
}
}
}
|
Add comment.
|
Add comment.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
cdc8cb87fac953666662479b00c88c477b530f99
|
examples/web/app/classes/server/FMSClient.as
|
examples/web/app/classes/server/FMSClient.as
|
package server {
dynamic public class FMSClient extends Object {
public function FMSClient() {
super();
}
public function onRegisterUser(user:String, result:Object):void {
trace('FMSClient.onRegisterUser:', user, result);
}
public function onSigninUser(user:String, result:Object):void {
trace('FMSClient.onSigninUser:', user, result);
}
public function onStartGame(user:String):void {
trace('FMSClient.onStartGame:', user);
}
public function onChangePlayer(user:String, player:uint):void {
trace('FMSClient.onChangePlayer:', user, player);
}
public function onDisconnect(user:String):void {
trace('FMSClient.onDisconnect:', user);
}
}
}
|
package server {
dynamic public class FMSClient extends Object {
public function FMSClient() {
super();
}
public function onRegisterUser(user:String, result:Object):void {
trace('FMSClient.onRegisterUser:', user, result);
}
public function onSigninUser(user:String, result:Object):void {
trace('FMSClient.onSigninUser:', user, result);
}
public function onStartGame(user:String):void {
trace('FMSClient.onStartGame:', user);
}
public function onChangePlayer(user:String, player:uint):void {
trace('FMSClient.onChangePlayer:', user, player);
}
public function onUpdateScore(score:uint):void {
trace('FMSClient.onUpdateScore:', score);
}
public function onDisconnect(user:String):void {
trace('FMSClient.onDisconnect:', user);
}
}
}
|
Update FMSClient.as
|
Update FMSClient.as
|
ActionScript
|
apache-2.0
|
adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler,adriancmiranda/flash-compiler
|
9cafef2ab0d7228ef89b1f9cf235141edb77ae4c
|
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;
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;
};
this.onEnterFrame = function ()
{
buttonsUI[i].oOver();
this.stop();
};
var Private_lv = new LoadVars ();
Private_lv.load ("/assets/tendes.txt");
Private_lv.onLoad = function ()
{
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;
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 ()
{
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
|
8770b6704d3da8f5b60eb203f996626197376f92
|
frameworks/projects/Core/src/main/flex/org/apache/flex/utils/MixinManager.as
|
frameworks/projects/Core/src/main/flex/org/apache/flex/utils/MixinManager.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.utils
{
COMPILE::SWF
{
import flash.system.ApplicationDomain;
}
import org.apache.flex.core.IBead;
import org.apache.flex.core.IFlexInfo;
import org.apache.flex.core.IStrand;
/**
* The MixinManager class is the class that instantiates mixins
* linked into the application. Mixins are classes with [Mixin]
* metadata and are often linked in via the -includes option.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class MixinManager implements IBead
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function MixinManager()
{
super();
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
* @flexjsignorecoercion Array
* @flexjsignorecoercion org.apache.flex.core.IFlexInfo
* @flexjsignoreimport org.apache.flex.core.IFlexInfo
*/
public function set strand(value:IStrand):void
{
_strand = value;
COMPILE::SWF
{
var app:IFlexInfo = value as IFlexInfo;
if (app)
{
var mixins:Array = app.info().mixins;
var domain:ApplicationDomain = app.info().currentDomain;
for each (var mixin:String in mixins)
{
var mixinClass:Object = domain.getDefinition(mixin);
mixinClass.init(value);
}
}
}
COMPILE::JS
{
var app:IFlexInfo = value as IFlexInfo;
if (app)
{
var mixins:Array = app.info()['mixins'] as Array;
if (mixins) {
var n:int = mixins.length;
for (var i:int = 0; i < n; i++)
{
mixins[i].init(value);
}
}
}
}
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.utils
{
COMPILE::SWF
{
import flash.system.ApplicationDomain;
}
import org.apache.flex.core.IBead;
import org.apache.flex.core.IFlexInfo;
import org.apache.flex.core.IStrand;
/**
* The MixinManager class is the class that instantiates mixins
* linked into the application. Mixins are classes with [Mixin]
* metadata and are often linked in via the -includes option.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class MixinManager implements IBead
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function MixinManager()
{
super();
}
private var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
* @flexjsignorecoercion Array
* @flexjsignorecoercion org.apache.flex.core.IFlexInfo
* @flexjsignoreimport org.apache.flex.core.IFlexInfo
*/
public function set strand(value:IStrand):void
{
_strand = value;
COMPILE::SWF
{
var app:IFlexInfo = value as IFlexInfo;
if (app)
{
var mixins:Array = app.info().mixins;
var domain:ApplicationDomain = app.info().currentDomain;
for each (var mixin:String in mixins)
{
var mixinClass:Object = domain.getDefinition(mixin);
mixinClass.init(value);
}
}
}
COMPILE::JS
{
var app:IFlexInfo = value as IFlexInfo;
if (app)
{
var info:Object = app.info();
if (info)
{
var mixins:Array = info['mixins'] as Array;
if (mixins) {
var n:int = mixins.length;
for (var i:int = 0; i < n; i++)
{
mixins[i].init(value);
}
}
}
}
}
}
}
}
|
handle having no mixins
|
handle having no mixins
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
d49a43dfe6cb6bcb148641ef3c2168eabc723982
|
snowplow-as3-tracker-tests/src/TrackerPayloadTest.as
|
snowplow-as3-tracker-tests/src/TrackerPayloadTest.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
{
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload;
import org.flexunit.Assert;
public class TrackerPayloadTest
{
[Test]
public function testAddString():void {
var payload:IPayload = new TrackerPayload();
payload.add("foo", "bar");
var res:String = "{\"foo\":\"bar\"}";
Assert.assertEquals(res, payload.toString());
}
[Test]
public function testAddObject():void {
var payload:IPayload = new TrackerPayload();
var map:Object = {};
map["foo"] = "bar";
map["more foo"] = "more bar";
payload.add("map", map);
var res1:String = "{\"map\":{\"foo\":\"bar\",\"more foo\":\"more bar\"}}";
var res2:String = "{\"map\":{\"more foo\":\"more bar\",\"foo\":\"bar\"}}";
var payloadString:String = payload.toString();
Assert.assertTrue(payloadString == res1 || payloadString == res2);
}
[Test]
public function testAddMap():void {
var foo:Object = {};
var bar:Array = [];
bar.push("somebar");
bar.push("somebar2");
foo["myKey"] = "my Value";
foo["mehh"] = bar;
var payload:IPayload = new TrackerPayload();
payload.addMap(foo);
var res1:String = "{\"myKey\":\"my Value\",\"mehh\":[\"somebar\",\"somebar2\"]}";
var res2:String = "{\"mehh\":[\"somebar\",\"somebar2\"],\"myKey\":\"my Value\"}";
var payloadString:String = payload.toString();
Assert.assertTrue(payloadString == res1 || payloadString == res2);
}
[Test]
public function testAddMapNotEncoding():void {
var foo:Object = {};
var bar:Array = [];
bar.push("somebar");
bar.push("somebar2");
foo["myKey"] = "my Value";
foo["mehh"] = bar;
var payload:IPayload = new TrackerPayload();
payload.addMap(foo, false, "cx", "co");
var res1:String = "{\"co\":\"{\\\"myKey\\\":\\\"my Value\\\",\\\"mehh\\\":[\\\"somebar\\\",\\\"somebar2\\\"]}\"}";
var res2:String = "{\"co\":\"{\\\"mehh\\\":[\\\"somebar\\\",\\\"somebar2\\\"],\\\"myKey\\\":\\\"my Value\\\"}\"}";
var payloadString:String = payload.toString();
Assert.assertTrue(payloadString == res1 || payloadString == res2);
}
[Test]
public function testAddMapEncoding():void {
var foo:Object = {};
var bar:Array = [];
bar.push("somebar");
bar.push("somebar2");
foo["myKey"] = "my Value";
foo["mehh"] = bar;
var payload:IPayload = new TrackerPayload();
payload.addMap(foo, true, "cx", "co");
var res1:String = "{\"cx\":\"eyJteUtleSI6Im15IFZhbHVlIiwibWVoaCI6WyJzb21lYmFyIiwic29tZWJhcjIiXX0=\"}";
var res2:String = "{\"cx\":\"eyJtZWhoIjpbInNvbWViYXIiLCJzb21lYmFyMiJdLCJteUtleSI6Im15IFZhbHVlIn0=\"}";
var payloadString:String = payload.toString();
Assert.assertTrue(payloadString == res1 || payloadString == res2);
}
[Test]
public function testSetData():void {
var payload:IPayload;
var res:String;
var foo:Object = {};
var bar:Array = [];
bar.push("somebar");
bar.push("somebar2");
foo["myKey"] = "my Value";
foo["mehh"] = bar;
var myarray:Array = ["arrayItem","arrayItem2"];
payload = new TrackerPayload();
payload.add("myarray", myarray);
res = "{\"myarray\":[\"arrayItem\",\"arrayItem2\"]}";
Assert.assertEquals(res, payload.toString());
payload = new TrackerPayload();
payload.add("foo", foo);
res = "{\"foo\":{\"myKey\":\"my Value\",\"mehh\":[\"somebar\",\"somebar2\"]}}";
var res2:String = "{\"foo\":{\"mehh\":[\"somebar\",\"somebar2\"],\"myKey\":\"my Value\"}}";
var payloadString:String = payload.toString();
Assert.assertTrue(res == payloadString || res2 == payloadString);
payload = new TrackerPayload();
payload.add("bar", bar);
res = "{\"bar\":[\"somebar\",\"somebar2\"]}";
Assert.assertEquals(res, payload.toString());
}
[Test]
public function testSetSchema():void {
var payload:SchemaPayload = new SchemaPayload();
payload.setSchema("iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0");
var res:String = "{\"schema\":\"iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0\"}";
Assert.assertEquals(res, payload.toString());
}
[Test]
public function testGetMap():void {
var payload:SchemaPayload;
var res:String;
var foo:Object = {};
var bar:Array = [];
bar.push("somebar");
bar.push("somebar2");
foo["myKey"] = "my Value";
foo["mehh"] = bar;
var data:Object = {};
data["data"] = foo;
payload = new SchemaPayload();
payload.setData(foo);
Assert.assertTrue(Helpers.compareObjects(data, payload.getMap()));
}
}
}
|
/*
* 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
{
import com.snowplowanalytics.snowplow.tracker.payload.IPayload;
import com.snowplowanalytics.snowplow.tracker.payload.SchemaPayload;
import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload;
import org.flexunit.Assert;
public class TrackerPayloadTest
{
[Test]
public function testAddString():void {
var payload:IPayload = new TrackerPayload();
payload.add("foo", "bar");
var res:String = "{\"foo\":\"bar\"}";
Assert.assertEquals(res, payload.toString());
}
[Test]
public function testAddObject():void {
var payload:IPayload = new TrackerPayload();
var map:Object = {};
map["foo"] = "bar";
map["more foo"] = "more bar";
payload.add("map", map);
var res1:String = "{\"map\":{\"foo\":\"bar\",\"more foo\":\"more bar\"}}";
var res2:String = "{\"map\":{\"more foo\":\"more bar\",\"foo\":\"bar\"}}";
var payloadString:String = payload.toString();
Assert.assertTrue(payloadString == res1 || payloadString == res2);
}
[Test]
public function testAddMap():void {
var foo:Object = {};
var bar:Array = [];
bar.push("somebar");
bar.push("somebar2");
foo["myKey"] = "my Value";
foo["mehh"] = bar;
var payload:IPayload = new TrackerPayload();
payload.addMap(foo);
var res1:String = "{\"myKey\":\"my Value\",\"mehh\":[\"somebar\",\"somebar2\"]}";
var res2:String = "{\"mehh\":[\"somebar\",\"somebar2\"],\"myKey\":\"my Value\"}";
var payloadString:String = payload.toString();
Assert.assertTrue(payloadString == res1 || payloadString == res2);
}
[Test]
public function testAddMapNotEncoding():void {
var foo:Object = {};
var bar:Array = [];
bar.push("somebar");
bar.push("somebar2");
foo["myKey"] = "my Value";
foo["mehh"] = bar;
var payload:IPayload = new TrackerPayload();
payload.addMap(foo, false, "cx", "co");
var res1:String = "{\"co\":\"{\\\"myKey\\\":\\\"my Value\\\",\\\"mehh\\\":[\\\"somebar\\\",\\\"somebar2\\\"]}\"}";
var res2:String = "{\"co\":\"{\\\"mehh\\\":[\\\"somebar\\\",\\\"somebar2\\\"],\\\"myKey\\\":\\\"my Value\\\"}\"}";
var payloadString:String = payload.toString();
Assert.assertTrue(payloadString == res1 || payloadString == res2);
}
[Test]
public function testAddMapEncoding():void {
var foo:Object = {};
var bar:Array = [];
bar.push("somebar");
bar.push("somebar2");
foo["myKey"] = "my Value";
foo["mehh"] = bar;
var payload:IPayload = new TrackerPayload();
payload.addMap(foo, true, "cx", "co");
var res1:String = "{\"cx\":\"eyJteUtleSI6Im15IFZhbHVlIiwibWVoaCI6WyJzb21lYmFyIiwic29tZWJhcjIiXX0=\"}";
var res2:String = "{\"cx\":\"eyJteUtleSI6Im15IFZhbHVlIiwibWVoaCI6WyJzb21lYmFyIiwic29tZWJhcjIiXX0\"}";
var res3:String = "{\"cx\":\"eyJtZWhoIjpbInNvbWViYXIiLCJzb21lYmFyMiJdLCJteUtleSI6Im15IFZhbHVlIn0=\"}";
var res4:String = "{\"cx\":\"eyJtZWhoIjpbInNvbWViYXIiLCJzb21lYmFyMiJdLCJteUtleSI6Im15IFZhbHVlIn0\"}";
var payloadString:String = payload.toString();
Assert.assertTrue(payloadString == res1 || payloadString == res2 || payloadString == res3 || payloadString == res4);
}
[Test]
public function testSetData():void {
var payload:IPayload;
var res:String;
var foo:Object = {};
var bar:Array = [];
bar.push("somebar");
bar.push("somebar2");
foo["myKey"] = "my Value";
foo["mehh"] = bar;
var myarray:Array = ["arrayItem","arrayItem2"];
payload = new TrackerPayload();
payload.add("myarray", myarray);
res = "{\"myarray\":[\"arrayItem\",\"arrayItem2\"]}";
Assert.assertEquals(res, payload.toString());
payload = new TrackerPayload();
payload.add("foo", foo);
res = "{\"foo\":{\"myKey\":\"my Value\",\"mehh\":[\"somebar\",\"somebar2\"]}}";
var res2:String = "{\"foo\":{\"mehh\":[\"somebar\",\"somebar2\"],\"myKey\":\"my Value\"}}";
var payloadString:String = payload.toString();
Assert.assertTrue(res == payloadString || res2 == payloadString);
payload = new TrackerPayload();
payload.add("bar", bar);
res = "{\"bar\":[\"somebar\",\"somebar2\"]}";
Assert.assertEquals(res, payload.toString());
}
[Test]
public function testSetSchema():void {
var payload:SchemaPayload = new SchemaPayload();
payload.setSchema("iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0");
var res:String = "{\"schema\":\"iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-0\"}";
Assert.assertEquals(res, payload.toString());
}
[Test]
public function testGetMap():void {
var payload:SchemaPayload;
var res:String;
var foo:Object = {};
var bar:Array = [];
bar.push("somebar");
bar.push("somebar2");
foo["myKey"] = "my Value";
foo["mehh"] = bar;
var data:Object = {};
data["data"] = foo;
payload = new SchemaPayload();
payload.setData(foo);
Assert.assertTrue(Helpers.compareObjects(data, payload.getMap()));
}
}
}
|
fix unit test so that travis will not fail
|
fix unit test so that travis will not fail
|
ActionScript
|
apache-2.0
|
snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker
|
3e544ac2f5dbd1c3aa6efe5fe544e28843778120
|
WEB-INF/lps/lfc/kernel/swf9/LFCApplication.as
|
WEB-INF/lps/lfc/kernel/swf9/LFCApplication.as
|
/**
* LFCApplication.as
*
* @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
* @author Henry Minsky <[email protected]>
*/
public class LFCApplication {
// This serves as the superclass of DefaultApplication, currently that is where
// the compiler puts top level code to run.
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.text.*;
import flash.system.*;
import flash.net.*;
import flash.ui.*;
import flash.text.Font;
}#
// The application sprite
public var _sprite:Sprite;
public function addChild(child:DisplayObject):DisplayObject {
_sprite.addChild(child);
}
// Allow anyone access to the stage object (see ctor below)
public static var stage:Stage = null;
// Allow anyone access to write to the debugger
public static var write:Function;
public function LFCApplication (sprite:Sprite) {
_sprite = sprite;
// Allow anyone to access the stage object
LFCApplication.stage = _sprite.stage;
LFCApplication.write = this.write;
// trace("LFCApplication.stage = " + LFCApplication.stage);
// trace(" loaderInfo.loaderURL = " + LFCApplication.stage.loaderInfo.loaderURL);
var idleTimerPeriod = 14; // msecs
//trace('idle timer period = ', idleTimerPeriod , 'msecs');
LzIdleKernel.startTimer( idleTimerPeriod );
stage.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp);
// necessary for consistent behavior - in netscape browsers HTML is ignored
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
//Stage.align = ('canvassalign' in global && global.canvassalign != null) ? global.canvassalign : "LT";
//Stage.scaleMode = ('canvasscale' in global && global.canvasscale != null) ? global.canvasscale : "noScale";
stage.addEventListener(Event.RESIZE, resizeHandler);
// Register for callbacks from the kernel
LzMouseKernel.setCallback(lz.ModeManager, 'rawMouseEvent');
/* TODO [hqm 2008-01] Do we want to do anything with other
* events, like click, or mousewheel ?
stage.addEventListener(MouseEvent.CLICK, reportClick);
stage.addEventListener(MouseEvent.MOUSE_WHEEL, reportWheel);
*/
LzKeyboardKernel.setCallback(lz.Keys, '__keyEvent');
////////////////////////////////////////////////////////////////
// cheapo debug console
lzconsole = this;
var tfield:TextField = new TextField();
tfield.visible = false;
tfield.background = true;
tfield.backgroundColor = 0xcccccc;
tfield.x = 0;
tfield.y = 400;
tfield.wordWrap = true;
tfield.multiline = true;
tfield.width = 800;
tfield.height = 160;
tfield.border = true;
consoletext = tfield;
var ci:TextField = new TextField();
consoleinputtext = ci;
ci.visible = false;
ci.background = true;
ci.backgroundColor = 0xffcccc;
ci.x = 0;
ci.y = 560;
ci.wordWrap = false;
ci.multiline = false;
ci.width = 800;
ci.height = 20;
ci.border = true;
ci.type = TextFieldType.INPUT;
ci.addEventListener(KeyboardEvent.KEY_DOWN, consoleInputHandler);
/* var allFonts:Array = Font.enumerateFonts(true);
allFonts.sortOn("fontName", Array.CASEINSENSITIVE);
var embeddedFonts:Array = Font.enumerateFonts(false);
embeddedFonts.sortOn("fontName", Array.CASEINSENSITIVE);
*/
var newFormat:TextFormat = new TextFormat();
newFormat.size = 11;
newFormat.font = "Verdana";
ci.defaultTextFormat = newFormat;
consoletext.defaultTextFormat = newFormat;
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Testing runtime code loading
////////////////////////////////////////////////////////////////
}
var debugloader:Loader;
// Debugger loader completion handler
function debugEvalListener (e:Event):void {
debugloader.unload();
//DebugExec(e.target.content).doit();
}
function consoleInputHandler (event:KeyboardEvent ){
if (event.charCode == Keyboard.ENTER) {
var expr = consoleinputtext.text;
write(expr);
consoleinputtext.text = "";
debugloader = new Loader();
debugloader.contentLoaderInfo.addEventListener(Event.INIT, debugEvalListener);
// Send EVAL request to LPS server
// It doesn't matter what path/filename we use, as long as it has ".lzx" suffix, so it is
// handled by the LPS. The lzt=eval causes the request to be served by the EVAL Responder.
var url = "hello.lzx?lzr=swf9&lz_load=false&lzt=eval&lz_script=" + encodeURIComponent(expr)+"&lzbc=" +(new Date()).getTime();
debugloader.load(new URLRequest(url),
new LoaderContext(false,
new ApplicationDomain(ApplicationDomain.currentDomain)));
}
}
////////////////////////////////////////////////////////////////
// A crude debugger output window for now
public var consoletext:TextField;
public var consoleinputtext:TextField;
public function write (...args) {
consoletext.visible = true;
consoleinputtext.visible = true;
consoletext.appendText( "\n" + args.join(" "));
consoletext.scrollV = consoletext.maxScrollV;
}
////////////////////////////////////////////////////////////////
function reportWheel(event:MouseEvent):void {
/*
Debug.write(event.currentTarget.toString() +
" dispatches MouseWheelEvent. delta = " + event.delta); */
lz.Keys.__mousewheelEvent(event.delta);
}
function resizeHandler(event:Event):void {
//trace('LFCApplication.resizeHandler stage width/height = ', stage.stageWidth, stage.stageHeight);
LzScreenKernel.handleResizeEvent();
}
function reportKeyUp(event:KeyboardEvent):void {
/*
trace("Key Released: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: " +
event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event, 'onkeyup');
}
function reportKeyDown(event:KeyboardEvent):void {
/*
trace("Key Pressed: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: "
+ event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event, 'onkeydown');
}
}
// Resource library
// contains {ptype, class, frames, width, height}
// ptype is one of "ar" (app relative) or "sr" (system relative)
var LzResourceLibrary = {};
var lzconsole;
|
/**
* LFCApplication.as
*
* @copyright Copyright 2007, 2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic swf9
* @author Henry Minsky <[email protected]>
*/
public class LFCApplication {
// This serves as the superclass of DefaultApplication, currently that is where
// the compiler puts top level code to run.
#passthrough (toplevel:true) {
import flash.display.*;
import flash.events.*;
import flash.utils.*;
import flash.text.*;
import flash.system.*;
import flash.net.*;
import flash.ui.*;
import flash.text.Font;
}#
// The application sprite
public var _sprite:Sprite;
public function addChild(child:DisplayObject):DisplayObject {
_sprite.addChild(child);
}
// Allow anyone access to the stage object (see ctor below)
public static var stage:Stage = null;
// Allow anyone access to write to the debugger
public static var write:Function;
public function LFCApplication (sprite:Sprite) {
_sprite = sprite;
// Allow anyone to access the stage object
LFCApplication.stage = _sprite.stage;
LFCApplication.write = this.write;
// trace("LFCApplication.stage = " + LFCApplication.stage);
// trace(" loaderInfo.loaderURL = " + LFCApplication.stage.loaderInfo.loaderURL);
var idleTimerPeriod = 14; // msecs
//trace('idle timer period = ', idleTimerPeriod , 'msecs');
LzIdleKernel.startTimer( idleTimerPeriod );
stage.addEventListener(KeyboardEvent.KEY_DOWN,reportKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,reportKeyUp);
// necessary for consistent behavior - in netscape browsers HTML is ignored
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
//Stage.align = ('canvassalign' in global && global.canvassalign != null) ? global.canvassalign : "LT";
//Stage.scaleMode = ('canvasscale' in global && global.canvasscale != null) ? global.canvasscale : "noScale";
stage.addEventListener(Event.RESIZE, resizeHandler);
// Register for callbacks from the kernel
LzMouseKernel.setCallback(lz.ModeManager, 'rawMouseEvent');
/* TODO [hqm 2008-01] Do we want to do anything with other
* events, like click, or mousewheel ?
stage.addEventListener(MouseEvent.CLICK, reportClick);
stage.addEventListener(MouseEvent.MOUSE_WHEEL, reportWheel);
*/
LzKeyboardKernel.setCallback(lz.Keys, '__keyEvent');
////////////////////////////////////////////////////////////////
// cheapo debug console
lzconsole = this;
var tfield:TextField = new TextField();
tfield.visible = false;
tfield.background = true;
tfield.backgroundColor = 0xcccccc;
tfield.x = 0;
tfield.y = 400;
tfield.wordWrap = true;
tfield.multiline = true;
tfield.width = 800;
tfield.height = 160;
tfield.border = true;
consoletext = tfield;
var ci:TextField = new TextField();
consoleinputtext = ci;
ci.visible = false;
ci.background = true;
ci.backgroundColor = 0xffcccc;
ci.x = 0;
ci.y = 560;
ci.wordWrap = false;
ci.multiline = false;
ci.width = 800;
ci.height = 20;
ci.border = true;
ci.type = TextFieldType.INPUT;
ci.addEventListener(KeyboardEvent.KEY_DOWN, consoleInputHandler);
/* var allFonts:Array = Font.enumerateFonts(true);
allFonts.sortOn("fontName", Array.CASEINSENSITIVE);
var embeddedFonts:Array = Font.enumerateFonts(false);
embeddedFonts.sortOn("fontName", Array.CASEINSENSITIVE);
*/
var newFormat:TextFormat = new TextFormat();
newFormat.size = 11;
newFormat.font = "Verdana";
ci.defaultTextFormat = newFormat;
consoletext.defaultTextFormat = newFormat;
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// Testing runtime code loading
////////////////////////////////////////////////////////////////
}
// Debugger loader completion handler
function debugEvalListener (e:Event):void {
e.target.loader.unload();
//DebugExec(e.target.content).doit();
}
function consoleInputHandler (event:KeyboardEvent ){
if (event.charCode == Keyboard.ENTER) {
var expr = consoleinputtext.text;
write(expr);
consoleinputtext.text = "";
var debugloader:Loader = new Loader();
debugloader.contentLoaderInfo.addEventListener(Event.INIT, debugEvalListener);
// Send EVAL request to LPS server
// It doesn't matter what path/filename we use, as long as it has ".lzx" suffix, so it is
// handled by the LPS. The lzt=eval causes the request to be served by the EVAL Responder.
var url = "hello.lzx?lzr=swf9&lz_load=false&lzt=eval&lz_script=" + encodeURIComponent(expr)+"&lzbc=" +(new Date()).getTime();
debugloader.load(new URLRequest(url),
new LoaderContext(false,
new ApplicationDomain(ApplicationDomain.currentDomain)));
}
}
////////////////////////////////////////////////////////////////
// A crude debugger output window for now
public var consoletext:TextField;
public var consoleinputtext:TextField;
public function write (...args) {
consoletext.visible = true;
consoleinputtext.visible = true;
consoletext.appendText( "\n" + args.join(" "));
consoletext.scrollV = consoletext.maxScrollV;
}
////////////////////////////////////////////////////////////////
function reportWheel(event:MouseEvent):void {
/*
Debug.write(event.currentTarget.toString() +
" dispatches MouseWheelEvent. delta = " + event.delta); */
lz.Keys.__mousewheelEvent(event.delta);
}
function resizeHandler(event:Event):void {
//trace('LFCApplication.resizeHandler stage width/height = ', stage.stageWidth, stage.stageHeight);
LzScreenKernel.handleResizeEvent();
}
function reportKeyUp(event:KeyboardEvent):void {
/*
trace("Key Released: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: " +
event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event, 'onkeyup');
}
function reportKeyDown(event:KeyboardEvent):void {
/*
trace("Key Pressed: " + String.fromCharCode(event.charCode) +
" (key code: " + event.keyCode + " character code: "
+ event.charCode + ")");
*/
LzKeyboardKernel.__keyboardEvent(event, 'onkeydown');
}
}
// Resource library
// contains {ptype, class, frames, width, height}
// ptype is one of "ar" (app relative) or "sr" (system relative)
var LzResourceLibrary = {};
var lzconsole;
|
Change 20080814-bargull-COE by bargull@dell--p4--2-53 on 2008-08-14 00:26:17 in /home/Admin/src/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20080814-bargull-COE by bargull@dell--p4--2-53 on 2008-08-14 00:26:17
in /home/Admin/src/svn/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: swf9 debugloader
New Features:
Bugs Fixed: LPP-6840
Technical Reviewer: ptw
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details:
If there are multiple calls to LFCApplication#consoleInputHandler(), only the last Loader will be saved in LFCApplication#debugloader. Could be an issue when unloading the movieclip in LFCApplication#debugEvalListener().
Tests:
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@10688 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
e7c023589ed450556a6ff950c96124048624c00a
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/layouts/VerticalLayout.as
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/layouts/VerticalLayout.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IBeadModel;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.geom.Rectangle;
import org.apache.flex.utils.dbg.DOMPathUtil;
import org.apache.flex.utils.CSSUtils;
import org.apache.flex.utils.CSSContainerUtils;
/**
* The VerticalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* vertically in one column, separating them according to
* CSS layout rules for margin and horizontal-align styles.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class VerticalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function VerticalLayout()
{
}
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
host = value as ILayoutChild;
}
public function layout():Boolean
{
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent ? layoutParent.contentView : IParentIUIBase(host);
var padding:Rectangle = CSSContainerUtils.getPaddingMetrics(host);
var n:int = contentView.numElements;
var hasHorizontalFlex:Boolean;
var hostSizedToContent:Boolean = host.isWidthSizedToContent();
var flexibleHorizontalMargins:Array = [];
var ilc:ILayoutChild;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var maxWidth:Number = 0;
// asking for contentView.width can result in infinite loop if host isn't sized already
var w:Number = hostSizedToContent ? 0 : contentView.width;
var h:Number = contentView.height;
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
ilc = child as ILayoutChild;
var left:Number = ValuesManager.valuesImpl.getValue(child, "left");
var right:Number = ValuesManager.valuesImpl.getValue(child, "right");
margin = ValuesManager.valuesImpl.getValue(child, "margin");
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
var ml:Number = CSSUtils.getLeftValue(marginLeft, margin, w);
var mr:Number = CSSUtils.getRightValue(marginRight, margin, w);
var mt:Number = CSSUtils.getTopValue(marginTop, margin, h);
var mb:Number = CSSUtils.getBottomValue(marginBottom, margin, h);
var lastmb:Number;
var yy:Number;
if (i == 0)
{
if (ilc)
ilc.setY(mt + padding.top);
else
child.y = mt + padding.top;
}
else
{
if (ilc)
ilc.setY(yy + Math.max(mt, lastmb));
else
child.y = yy + Math.max(mt, lastmb);
}
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, !isNaN(ilc.percentWidth));
}
lastmb = mb;
var marginObject:Object = {};
flexibleHorizontalMargins[i] = marginObject;
if (marginLeft == "auto")
{
ml = 0;
marginObject.marginLeft = marginLeft;
hasHorizontalFlex = true;
}
else
{
ml = Number(marginLeft);
if (isNaN(ml))
{
ml = 0;
marginObject.marginLeft = marginLeft;
}
else
marginObject.marginLeft = ml;
}
if (marginRight == "auto")
{
mr = 0;
marginObject.marginRight = marginRight;
hasHorizontalFlex = true;
}
else
{
mr = Number(marginRight);
if (isNaN(mr))
{
mr = 0;
marginObject.marginRight = marginRight;
}
else
marginObject.marginRight = mr;
}
if (!hostSizedToContent)
{
// if host is sized by parent,
// we can position and size children horizontally now
setPositionAndWidth(child, left, ml, padding.left,
right, mr, padding.right, w);
}
else
{
if (!isNaN(left))
{
ml = left;
marginObject.left = ml;
}
if (!isNaN(right))
{
mr = right;
marginObject.right = mr;
}
maxWidth = Math.max(maxWidth, ml + child.width + mr);
}
yy = child.y + child.height;
}
if (hostSizedToContent)
{
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
var obj:Object = flexibleHorizontalMargins[i];
setPositionAndWidth(child, obj.left, obj.marginLeft, padding.left,
obj.right, obj.marginRight, padding.right, maxWidth);
}
}
if (hasHorizontalFlex)
{
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
ilc = child as ILayoutChild;
obj = flexibleHorizontalMargins[i];
if (hasHorizontalFlex)
{
if (ilc)
{
if (obj.marginLeft == "auto" && obj.marginRight == "auto")
ilc.setX(maxWidth - child.width / 2);
else if (obj.marginLeft == "auto")
ilc.setX(maxWidth - child.width - obj.marginRight - padding.right);
}
else
{
if (obj.marginLeft == "auto" && obj.marginRight == "auto")
child.x = maxWidth - child.width / 2;
else if (obj.marginLeft == "auto")
child.x = maxWidth - child.width - obj.marginRight - padding.right;
}
}
}
}
// Only return true if the contentView needs to be larger; that new
// size is stored in the model.
var sizeChanged:Boolean = true;
host.dispatchEvent( new Event("layoutComplete") );
return sizeChanged;
}
private function setPositionAndWidth(child:IUIBase, left:Number, ml:Number, pl:Number,
right:Number, mr:Number, pr:Number, w:Number):void
{
var widthSet:Boolean = false;
var ww:Number = w;
var ilc:ILayoutChild = child as ILayoutChild;
if (!isNaN(left))
{
if (ilc)
ilc.setX(left + ml);
else
child.x = left + ml;
ww -= left + ml;
}
else
{
if (ilc)
ilc.setX(ml + pl);
else
child.x = ml + pl;
ww -= ml + pl;
}
if (!isNaN(right))
{
if (!isNaN(left))
{
if (ilc)
ilc.setWidth(ww - right - mr, true);
else
{
child.width = ww - right - mr;
widthSet = true;
}
}
else
{
if (ilc)
ilc.setX(w - right - mr - child.width);
else
child.x = w - right - mr - child.width;
}
}
if (ilc)
{
if (!isNaN(ilc.percentWidth))
ilc.setWidth(w * ilc.percentWidth / 100, true);
}
if (!widthSet)
child.dispatchEvent(new Event("sizeChanged"));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IBeadModel;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.geom.Rectangle;
import org.apache.flex.utils.CSSContainerUtils;
import org.apache.flex.utils.CSSUtils;
import org.apache.flex.utils.dbg.DOMPathUtil;
/**
* The VerticalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* vertically in one column, separating them according to
* CSS layout rules for margin and horizontal-align styles.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class VerticalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function VerticalLayout()
{
}
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
host = value as ILayoutChild;
}
public function layout():Boolean
{
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent ? layoutParent.contentView : IParentIUIBase(host);
var padding:Rectangle = CSSContainerUtils.getPaddingMetrics(host);
var n:int = contentView.numElements;
var hasHorizontalFlex:Boolean;
var hostSizedToContent:Boolean = host.isWidthSizedToContent();
var flexibleHorizontalMargins:Array = [];
var ilc:ILayoutChild;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var maxWidth:Number = 0;
var cssValue:*;
// asking for contentView.width can result in infinite loop if host isn't sized already
var w:Number = hostSizedToContent ? 0 : contentView.width;
var h:Number = contentView.height;
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
ilc = child as ILayoutChild;
var left:Number = NaN;
cssValue = ValuesManager.valuesImpl.getValue(child, "left");
if (cssValue !== undefined)
left = CSSUtils.toNumber(cssValue);
var right:Number = NaN;
cssValue = ValuesManager.valuesImpl.getValue(child, "right");
if (cssValue !== undefined)
right = CSSUtils.toNumber(cssValue);
margin = ValuesManager.valuesImpl.getValue(child, "margin");
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
var ml:Number = CSSUtils.getLeftValue(marginLeft, margin, w);
var mr:Number = CSSUtils.getRightValue(marginRight, margin, w);
var mt:Number = CSSUtils.getTopValue(marginTop, margin, h);
var mb:Number = CSSUtils.getBottomValue(marginBottom, margin, h);
var lastmb:Number;
var yy:Number;
if (i == 0)
{
if (ilc)
ilc.setY(mt + padding.top);
else
child.y = mt + padding.top;
}
else
{
if (ilc)
ilc.setY(yy + Math.max(mt, lastmb));
else
child.y = yy + Math.max(mt, lastmb);
}
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, !isNaN(ilc.percentWidth));
}
lastmb = mb;
var marginObject:Object = {};
flexibleHorizontalMargins[i] = marginObject;
if (marginLeft == "auto")
{
ml = 0;
marginObject.marginLeft = marginLeft;
hasHorizontalFlex = true;
}
else
{
ml = Number(marginLeft);
if (isNaN(ml))
{
ml = 0;
marginObject.marginLeft = marginLeft;
}
else
marginObject.marginLeft = ml;
}
if (marginRight == "auto")
{
mr = 0;
marginObject.marginRight = marginRight;
hasHorizontalFlex = true;
}
else
{
mr = Number(marginRight);
if (isNaN(mr))
{
mr = 0;
marginObject.marginRight = marginRight;
}
else
marginObject.marginRight = mr;
}
if (!hostSizedToContent)
{
// if host is sized by parent,
// we can position and size children horizontally now
setPositionAndWidth(child, left, ml, padding.left,
right, mr, padding.right, w);
}
else
{
if (!isNaN(left))
{
ml = left;
marginObject.left = ml;
}
if (!isNaN(right))
{
mr = right;
marginObject.right = mr;
}
maxWidth = Math.max(maxWidth, ml + child.width + mr);
}
yy = child.y + child.height;
}
if (hostSizedToContent)
{
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
var obj:Object = flexibleHorizontalMargins[i];
setPositionAndWidth(child, obj.left, obj.marginLeft, padding.left,
obj.right, obj.marginRight, padding.right, maxWidth);
}
}
if (hasHorizontalFlex)
{
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
ilc = child as ILayoutChild;
obj = flexibleHorizontalMargins[i];
if (hasHorizontalFlex)
{
if (ilc)
{
if (obj.marginLeft == "auto" && obj.marginRight == "auto")
ilc.setX(maxWidth - child.width / 2);
else if (obj.marginLeft == "auto")
ilc.setX(maxWidth - child.width - obj.marginRight - padding.right);
}
else
{
if (obj.marginLeft == "auto" && obj.marginRight == "auto")
child.x = maxWidth - child.width / 2;
else if (obj.marginLeft == "auto")
child.x = maxWidth - child.width - obj.marginRight - padding.right;
}
}
}
}
// Only return true if the contentView needs to be larger; that new
// size is stored in the model.
var sizeChanged:Boolean = true;
host.dispatchEvent( new Event("layoutComplete") );
return sizeChanged;
}
private function setPositionAndWidth(child:IUIBase, left:Number, ml:Number, pl:Number,
right:Number, mr:Number, pr:Number, w:Number):void
{
var widthSet:Boolean = false;
var ww:Number = w;
var ilc:ILayoutChild = child as ILayoutChild;
if (!isNaN(left))
{
if (ilc)
ilc.setX(left + ml);
else
child.x = left + ml;
ww -= left + ml;
}
else
{
if (ilc)
ilc.setX(ml + pl);
else
child.x = ml + pl;
ww -= ml + pl;
}
if (!isNaN(right))
{
if (!isNaN(left))
{
if (ilc)
ilc.setWidth(ww - right - mr, true);
else
{
child.width = ww - right - mr;
widthSet = true;
}
}
else
{
if (ilc)
ilc.setX(w - right - mr - child.width);
else
child.x = w - right - mr - child.width;
}
}
if (ilc)
{
if (!isNaN(ilc.percentWidth))
ilc.setWidth(w * ilc.percentWidth / 100, true);
}
if (!widthSet)
child.dispatchEvent(new Event("sizeChanged"));
}
}
}
|
handle units for left/right
|
handle units for left/right
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
32cbcf497dd81e5eee41b210072f6605a4ff7484
|
Game/Scripts/Cart.as
|
Game/Scripts/Cart.as
|
class Cart{
Hub @hub;
Entity @self;
float speed;
bool trigger;
float stopTime;
float endTime;
float a;
float b;
float c;
Component::Physics @minecartPhysics;
Component::Physics @stopPhysics;
Cart(Entity @entity){
@hub = Managers();
@self = @entity;
speed = 20.0f;
stopTime = 0.0f;
endTime = 7.5f;
// Calculate second grade equation.
float t = endTime;
c = speed;
a = (3.0f * c - 300.0f / t) / (t * t);
b = 100.0f / (t * t) - 2.0f * a * t / 3.0f - 2.0f * c / t;
Entity @stopTrigger = self.GetParent().GetChild("GateAndLever").GetChild("StopTrigger");
@minecartPhysics = self.GetPhysics();
@stopPhysics = stopTrigger.GetPhysics();
trigger = false;
RegisterUpdate();
RegisterTrigger(stopPhysics, minecartPhysics, "OnTrigger");
}
//Update carts movements and send it's position to Player Script.
void Update(float deltaTime){
self.position.z -= speed*deltaTime;
if (self.position.z < 450.0f && stopTime < endTime){
stopTime += deltaTime;
float t = stopTime;
float zPos = a * t * t * t / 3.0f + b * t * t / 2.0f + c * t;
self.position.z = 450.0f - zPos;
} else if (stopTime >= endTime && !trigger) {
self.position.z = 400.0f;
speed = 0.0f;
} else if (trigger){
if (speed < 20.0f)
speed += 0.0664f;
}
}
void ReceiveMessage(int signal){
if (signal == 1)
trigger = true;
}
void OnTrigger(Component::Physics @trigger, Component::Physics @enterer) {
}
}
|
class Cart{
Hub @hub;
Entity @self;
float speed;
bool trigger;
float stopTime;
float endTime;
float a;
float b;
float c;
Component::Physics @minecartPhysics;
Component::Physics @stopPhysics;
Cart(Entity @entity){
@hub = Managers();
@self = @entity;
speed = 20.0f;
stopTime = 0.0f;
endTime = 7.5f;
// Calculate second grade equation.
float t = endTime;
c = speed;
a = (3.0f * c - 300.0f / t) / (t * t);
b = 100.0f / (t * t) - 2.0f * a * t / 3.0f - 2.0f * c / t;
Entity @stopTrigger = self.GetParent().GetChild("GateAndLever").GetChild("StopTrigger");
@minecartPhysics = self.GetPhysics();
@stopPhysics = stopTrigger.GetPhysics();
trigger = false;
RegisterUpdate();
RegisterTrigger(stopPhysics, minecartPhysics, "OnTrigger");
}
//Update carts movements and send it's position to Player Script.
void Update(float deltaTime){
self.position.z -= speed*deltaTime;
if (self.position.z < 450.0f && stopTime < endTime){
stopTime += deltaTime;
float t = stopTime;
float zPos = a * t * t * t / 3.0f + b * t * t / 2.0f + c * t;
self.position.z = 450.0f - zPos;
} else if (stopTime >= endTime && !trigger) {
self.position.z = 400.0f;
speed = 0.0f;
} else if (trigger){
if (speed < 20.0f)
speed += 0.0664f;
}
}
void ReceiveMessage(int signal){
if (signal == 1)
trigger = true;
}
void OnTrigger(Component::Physics @trigger, Component::Physics @enterer) {
print("WOW! WHAT A COLLISION!");
}
}
|
Print a message when colliding
|
Print a message when colliding
|
ActionScript
|
mit
|
Chainsawkitten/LargeGameProjectEngine,Chainsawkitten/LargeGameProjectEngine
|
7e5074cbe04f35b2bf1f9f69557be10796f62c9c
|
src/aerys/minko/scene/node/light/SpotLight.as
|
src/aerys/minko/scene/node/light/SpotLight.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.SpotLightController;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.type.enum.ShadowMappingType;
import aerys.minko.type.math.Vector4;
use namespace minko_scene;
/**
*
* @author Romain Gilliotte
* @author Jean-Marc Le Roux
*
*/
public class SpotLight extends AbstractLight
{
public static const LIGHT_TYPE : uint = 3;
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 get innerRadius() : Number
{
return lightData.getLightProperty('innerRadius') as Number;
}
public function set innerRadius(v : Number) : void
{
lightData.setLightProperty('innerRadius', v);
if (lightData.getLightProperty('smoothRadius') != (innerRadius != outerRadius))
lightData.setLightProperty('smoothRadius', innerRadius != outerRadius)
}
public function get outerRadius() : Number
{
return lightData.getLightProperty('outerRadius') as Number;
}
public function set outerRadius(v : Number) : void
{
lightData.setLightProperty('outerRadius', v);
if (lightData.getLightProperty('smoothRadius') != (innerRadius != outerRadius))
lightData.setLightProperty('smoothRadius', innerRadius != outerRadius)
}
public function get attenuationDistance() : Number
{
return lightData.getLightProperty('attenuationDistance') as Number;
}
public function set attenuationDistance(v : Number) : void
{
lightData.setLightProperty('attenuationDistance', v);
if (lightData.getLightProperty('attenuationEnabled') != (v != 0))
lightData.setLightProperty('attenuationEnabled', v != 0);
}
public function get shadowZNear() : Number
{
return lightData.getLightProperty('shadowZNear');
}
public function set shadowZNear(v : Number) : void
{
lightData.setLightProperty('shadowZNear', 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 set shininess(v : Number) : void
{
lightData.setLightProperty('shininess', v);
}
public function get shadowMapSize() : uint
{
return lightData.getLightProperty('shadowMapSize') as uint;
}
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 SpotLight(color : uint = 0xFFFFFFFF,
diffuse : Number = .6,
specular : Number = .8,
shininess : Number = 64,
attenuationDistance : Number = 0,
outerRadius : Number = 1.57079632679,
innerRadius : Number = 0,
emissionMask : uint = 0x1,
shadowCastingType : uint = 0,
shadowMapSize : uint = 512,
shadowZNear : Number = 0.1,
shadowZFar : Number = 1000,
shadowQuality : uint = 0,
shadowSpread : uint = 1,
shadowBias : uint = 1. / 256. / 256.)
{
super(
new SpotLightController(),
LIGHT_TYPE,
color,
emissionMask
);
this.diffuse = diffuse;
this.specular = specular;
this.shininess = shininess;
this.innerRadius = innerRadius;
this.outerRadius = outerRadius;
this.attenuationDistance = attenuationDistance;
this.shadowCastingType = shadowCastingType;
this.shadowZNear = shadowZNear;
this.shadowZFar = shadowZFar;
this.shadowMapSize = shadowMapSize;
this.shadowQuality = shadowQuality;
this.shadowSpread = shadowSpread;
this.shadowBias = shadowBias;
transform.lookAt(Vector4.Z_AXIS, Vector4.ZERO);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var light : SpotLight = new SpotLight(
color,
diffuse,
specular,
shininess,
attenuationDistance,
outerRadius,
innerRadius,
emissionMask,
shadowCastingType,
shadowMapSize,
shadowZNear,
shadowZFar,
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.SpotLightController;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.type.enum.ShadowMappingType;
import aerys.minko.type.math.Vector4;
use namespace minko_scene;
/**
*
* @author Romain Gilliotte
* @author Jean-Marc Le Roux
*
*/
public class SpotLight extends AbstractLight
{
public static const LIGHT_TYPE : uint = 3;
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 get innerRadius() : Number
{
return lightData.getLightProperty('innerRadius') as Number;
}
public function set innerRadius(v : Number) : void
{
lightData.setLightProperty('innerRadius', v);
if (lightData.getLightProperty('smoothRadius') != (innerRadius != outerRadius))
lightData.setLightProperty('smoothRadius', innerRadius != outerRadius)
}
public function get outerRadius() : Number
{
return lightData.getLightProperty('outerRadius') as Number;
}
public function set outerRadius(v : Number) : void
{
lightData.setLightProperty('outerRadius', v);
if (lightData.getLightProperty('smoothRadius') != (innerRadius != outerRadius))
lightData.setLightProperty('smoothRadius', innerRadius != outerRadius)
}
public function get attenuationDistance() : Number
{
return lightData.getLightProperty('attenuationDistance') as Number;
}
public function set attenuationDistance(v : Number) : void
{
lightData.setLightProperty('attenuationDistance', v);
if (lightData.getLightProperty('attenuationEnabled') != (v != 0))
lightData.setLightProperty('attenuationEnabled', v != 0);
}
public function get shadowZNear() : Number
{
return lightData.getLightProperty('shadowZNear');
}
public function set shadowZNear(v : Number) : void
{
lightData.setLightProperty('shadowZNear', 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 set shininess(v : Number) : void
{
lightData.setLightProperty('shininess', v);
}
public function get shadowMapSize() : uint
{
return lightData.getLightProperty('shadowMapSize') as uint;
}
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 SpotLight(color : uint = 0xFFFFFFFF,
diffuse : Number = .6,
specular : Number = .8,
shininess : Number = 64,
attenuationDistance : Number = 0,
outerRadius : Number = 1.57079632679,
innerRadius : Number = 0,
emissionMask : uint = 0x1,
shadowCastingType : uint = 0,
shadowMapSize : uint = 512,
shadowZNear : Number = 0.1,
shadowZFar : Number = 1000,
shadowQuality : uint = 0,
shadowSpread : uint = 1,
shadowBias : uint = 1. / 256. / 256.)
{
super(
new SpotLightController(),
LIGHT_TYPE,
color,
emissionMask
);
this.diffuse = diffuse;
this.specular = specular;
this.shininess = shininess;
this.innerRadius = innerRadius;
this.outerRadius = outerRadius;
this.attenuationDistance = attenuationDistance;
this.shadowCastingType = shadowCastingType;
this.shadowZNear = shadowZNear;
this.shadowZFar = shadowZFar;
this.shadowMapSize = shadowMapSize;
this.shadowQuality = shadowQuality;
this.shadowSpread = shadowSpread;
this.shadowBias = shadowBias;
transform.lookAt(Vector4.Z_AXIS, Vector4.ZERO);
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var light : SpotLight = new SpotLight(
color,
diffuse,
specular,
shininess,
attenuationDistance,
outerRadius,
innerRadius,
emissionMask,
shadowCastingType,
shadowMapSize,
shadowZNear,
shadowZFar,
shadowQuality,
shadowSpread,
shadowBias
);
light.name = this.name;
light.transform.copyFrom(this.transform);
return light;
}
}
}
|
fix coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
f22bb03e3a7411099c704b76893526229419ac46
|
src/aerys/minko/render/resource/IndexBuffer3DResource.as
|
src/aerys/minko/render/resource/IndexBuffer3DResource.as
|
package aerys.minko.render.resource
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.geometry.stream.IndexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import flash.display3D.Context3D;
import flash.display3D.IndexBuffer3D;
import flash.events.Event;
/**
* IndexBuffer3DResource objects handle index buffers allocation
* and disposal using the Stage3D API.
*
* @author Jean-Marc Le Roux
*
*/
public final class IndexBuffer3DResource implements IResource
{
use namespace minko_stream;
private var _stream : IndexStream = null;
private var _update : Boolean = true;
private var _lengthChanged : Boolean = true;
private var _indexBuffer : IndexBuffer3D = null;
private var _numIndices : uint = 0;
private var _disposed : Boolean = false;
public function get numIndices() : uint
{
return _numIndices;
}
public function IndexBuffer3DResource(source : IndexStream)
{
_stream = source;
_stream.changed.add(indexStreamChangedHandler);
}
private function indexStreamChangedHandler(stream : IndexStream) : void
{
_update = true;
_lengthChanged = stream.length != _numIndices;
}
public function getIndexBuffer3D(context : Context3DResource) : IndexBuffer3D
{
var update : Boolean = _update;
if (_disposed)
throw new Error('Unable to render a disposed buffer.');
if (_indexBuffer == null || _lengthChanged)
{
_lengthChanged = false;
if (_indexBuffer)
_indexBuffer.dispose();
update = true;
_indexBuffer = context.createIndexBuffer(_stream.length);
}
if (update)
{
_indexBuffer.uploadFromVector(_stream._data, 0, _stream.length);
_update = false;
_numIndices = _stream.length;
if (!(_stream.usage & StreamUsage.READ))
_stream.disposeLocalData();
}
return _indexBuffer;
}
public function dispose() : void
{
if (_indexBuffer)
{
_indexBuffer.dispose();
_indexBuffer = null;
}
_disposed = true;
_stream = null;
_numIndices = 0;
}
}
}
|
package aerys.minko.render.resource
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.geometry.stream.IndexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import flash.display3D.Context3D;
import flash.display3D.IndexBuffer3D;
import flash.events.Event;
/**
* IndexBuffer3DResource objects handle index buffers allocation
* and disposal using the Stage3D API.
*
* @author Jean-Marc Le Roux
*
*/
public final class IndexBuffer3DResource implements IResource
{
use namespace minko_stream;
private var _stream : IndexStream = null;
private var _update : Boolean = true;
private var _lengthChanged : Boolean = true;
private var _indexBuffer : IndexBuffer3D = null;
private var _numIndices : uint = 0;
private var _disposed : Boolean = false;
public function get numIndices() : uint
{
return _numIndices;
}
public function IndexBuffer3DResource(source : IndexStream)
{
_stream = source;
_stream.changed.add(indexStreamChangedHandler);
}
private function indexStreamChangedHandler(stream : IndexStream) : void
{
_update = true;
_lengthChanged = stream.length != _numIndices;
}
public function getIndexBuffer3D(context : Context3DResource) : IndexBuffer3D
{
var update : Boolean = _update;
if (_disposed)
throw new Error('Unable to render a disposed buffer.');
if (_indexBuffer == null || _lengthChanged)
{
_lengthChanged = false;
if (_indexBuffer)
_indexBuffer.dispose();
update = true;
_indexBuffer = context.createIndexBuffer(_stream.length);
}
if (update)
{
_indexBuffer.uploadFromVector(_stream._data, 0, _stream.length);
_update = false;
_numIndices = _stream.length;
if (!(_stream.usage & StreamUsage.READ) || _stream._localDispose)
_stream.disposeLocalData(false);
}
return _indexBuffer;
}
public function dispose() : void
{
if (_indexBuffer)
{
_indexBuffer.dispose();
_indexBuffer = null;
}
_disposed = true;
_stream = null;
_numIndices = 0;
}
}
}
|
handle IndexStream._localDipose in IndexBuffer3DResource.getIndexBuffer3D()
|
handle IndexStream._localDipose in IndexBuffer3DResource.getIndexBuffer3D()
|
ActionScript
|
mit
|
aerys/minko-as3
|
80f468c5cd383e2c420969a3d55bbcfdc5d9a70f
|
src/main/org/shypl/common/util/BitmapUtils.as
|
src/main/org/shypl/common/util/BitmapUtils.as
|
package org.shypl.common.util {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.IBitmapDrawable;
import flash.display.PixelSnapping;
import flash.geom.Matrix;
import flash.geom.Rectangle;
public final class BitmapUtils {
public static function getRectangle(source:BitmapData, rect:Rectangle):BitmapData {
var copy:BitmapData = new BitmapData(rect.width, rect.height);
copy.copyPixels(source, rect, StaticPoint0.INSTANCE);
return copy;
}
public static function createBitmap(image:BitmapData, smoothing:Boolean = true, pixelSnapping:String = PixelSnapping.AUTO, x:Number = 0, y:Number = 0,
scale:Number = 1
):Bitmap {
const bitmap:Bitmap = new Bitmap(image, pixelSnapping, smoothing);
bitmap.x = x;
bitmap.y = y;
bitmap.scaleX = scale;
bitmap.scaleY = scale;
return bitmap;
}
public static function defineVisibleBounds(target:IBitmapDrawable):Rectangle {
if (target is DisplayObject) {
return defineVisibleBoundsForDisplayObject(DisplayObject(target));
}
return defineVisibleBoundsForBitmapData(BitmapData(target));
}
public static function defineVisibleBoundsForDisplayObject(target:DisplayObject):Rectangle {
var object:DisplayObject = DisplayObject(target);
var data:BitmapData = new BitmapData(object.width, object.height, true, 0);
data.draw(object);
var rect:Rectangle = defineVisibleBounds(data);
data.dispose();
return rect;
}
public static function defineVisibleBoundsForBitmapData(target:BitmapData):Rectangle {
var w:int = target.width;
var h:int = target.height;
var x:int;
var y:int;
var l:int = -1;
var t:int = -1;
var r:int = -1;
var b:int = -1;
for (x = 0; x < w; x++) {
for (y = 0; y < h; y++) {
if (0 != target.getPixel32(x, y)) {
l = x;
break;
}
}
if (l >= 0) {
break;
}
}
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
if (0 != target.getPixel32(x, y)) {
t = y;
break;
}
}
if (t >= 0) {
break;
}
}
for (x = w - 1; x >= 0; x--) {
for (y = 0; y < h; y++) {
if (0 != target.getPixel32(x, y)) {
r = x + 1;
break;
}
}
if (r >= 0) {
break;
}
}
for (y = h - 1; y >= 0; y--) {
for (x = 0; x < w; x++) {
if (0 != target.getPixel32(x, y)) {
b = y + 1;
break;
}
}
if (b >= 0) {
break;
}
}
if (l == -1) {
l = 0;
r = 0;
t = 0;
b = 0;
}
return new Rectangle(l, t, r - l, b - t);
}
public static function resize(source:BitmapData, width:int, height:int):BitmapData {
var target:BitmapData = new BitmapData(width, height, true, 0);
var matrix:Matrix = new Matrix();
matrix.scale(width / source.width, height / source.height);
target.draw(source, matrix, null, null, null, true);
return target;
}
}
}
|
package org.shypl.common.util {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BitmapDataChannel;
import flash.display.DisplayObject;
import flash.display.IBitmapDrawable;
import flash.display.PixelSnapping;
import flash.geom.Matrix;
import flash.geom.Rectangle;
public final class BitmapUtils {
public static function createBitmap(image:BitmapData, smoothing:Boolean = true, pixelSnapping:String = PixelSnapping.AUTO, x:Number = 0, y:Number = 0,
scale:Number = 1
):Bitmap {
const bitmap:Bitmap = new Bitmap(image, pixelSnapping, smoothing);
bitmap.x = x;
bitmap.y = y;
bitmap.scaleX = scale;
bitmap.scaleY = scale;
return bitmap;
}
public static function getRectangle(source:BitmapData, rect:Rectangle):BitmapData {
var copy:BitmapData = new BitmapData(rect.width, rect.height);
copy.copyPixels(source, rect, StaticPoint0.INSTANCE);
return copy;
}
public static function resize(source:BitmapData, width:int, height:int):BitmapData {
var target:BitmapData = new BitmapData(width, height, true, 0);
var matrix:Matrix = new Matrix();
matrix.scale(width / source.width, height / source.height);
target.draw(source, matrix, null, null, null, true);
return target;
}
public static function applyInnerAlphaMask(source:BitmapData, horizontal:Boolean = true, rect:Rectangle = null):BitmapData {
if (rect == null) {
rect = new Rectangle(0, 0,
horizontal ? source.width : (source.width / 2),
horizontal ? (source.height / 2) : source.height
);
}
var result:BitmapData = new BitmapData(rect.width, rect.height, true, 0);
var resultRect:Rectangle = new Rectangle(0, 0, rect.width, rect.height);
var maskRect:Rectangle = new Rectangle(
horizontal ? 0 : rect.width,
horizontal ? rect.height : 0,
rect.width, rect.height);
result.copyPixels(source, resultRect, StaticPoint0.INSTANCE);
result.copyChannel(source, maskRect, StaticPoint0.INSTANCE, BitmapDataChannel.RED, BitmapDataChannel.ALPHA);
return result;
}
public static function defineVisibleBounds(target:IBitmapDrawable):Rectangle {
if (target is DisplayObject) {
return defineVisibleBoundsForDisplayObject(DisplayObject(target));
}
return defineVisibleBoundsForBitmapData(BitmapData(target));
}
public static function defineVisibleBoundsForDisplayObject(target:DisplayObject):Rectangle {
var object:DisplayObject = DisplayObject(target);
var data:BitmapData = new BitmapData(object.width, object.height, true, 0);
data.draw(object);
var rect:Rectangle = defineVisibleBounds(data);
data.dispose();
return rect;
}
public static function defineVisibleBoundsForBitmapData(target:BitmapData):Rectangle {
var w:int = target.width;
var h:int = target.height;
var x:int;
var y:int;
var l:int = -1;
var t:int = -1;
var r:int = -1;
var b:int = -1;
for (x = 0; x < w; x++) {
for (y = 0; y < h; y++) {
if (0 != target.getPixel32(x, y)) {
l = x;
break;
}
}
if (l >= 0) {
break;
}
}
for (y = 0; y < h; y++) {
for (x = 0; x < w; x++) {
if (0 != target.getPixel32(x, y)) {
t = y;
break;
}
}
if (t >= 0) {
break;
}
}
for (x = w - 1; x >= 0; x--) {
for (y = 0; y < h; y++) {
if (0 != target.getPixel32(x, y)) {
r = x + 1;
break;
}
}
if (r >= 0) {
break;
}
}
for (y = h - 1; y >= 0; y--) {
for (x = 0; x < w; x++) {
if (0 != target.getPixel32(x, y)) {
b = y + 1;
break;
}
}
if (b >= 0) {
break;
}
}
if (l == -1) {
l = 0;
r = 0;
t = 0;
b = 0;
}
return new Rectangle(l, t, r - l, b - t);
}
}
}
|
Add BitmapUtils.applyInnerAlphaMask
|
Add BitmapUtils.applyInnerAlphaMask
|
ActionScript
|
apache-2.0
|
shypl/common-flash
|
79b2ddc851996b4640b81e45270b480a18926abb
|
dolly-framework/src/main/actionscript/dolly/utils/PropertyUtil.as
|
dolly-framework/src/main/actionscript/dolly/utils/PropertyUtil.as
|
package dolly.utils {
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
public class PropertyUtil {
private static function copyArray(targetObj:*, propertyName:String, sourceProperty:*):void {
targetObj[propertyName] = (sourceProperty as Array).slice();
}
private static function copyArrayList(targetObj:*, propertyName:String, arrayList:ArrayList):void {
targetObj[propertyName] = arrayList.source ? new ArrayList(arrayList.source) : new ArrayList();
}
private static function copyArrayCollection(targetObj:*, propertyName:String, sourceProperty:*):void {
const arrayCollection:ArrayCollection = (sourceProperty as ArrayCollection);
targetObj[propertyName] = arrayCollection.source ?
new ArrayCollection(arrayCollection.source.slice()) :
new ArrayCollection();
}
private static function copyObject(targetObj:*, propertyName:String, sourceProperty:*):void {
targetObj[propertyName] = sourceProperty;
}
public static function copyProperty(sourceObj:*, targetObj:*, propertyName:String):void {
const sourceProperty:* = sourceObj[propertyName];
if (sourceProperty is Array) {
copyArray(targetObj, propertyName, sourceProperty);
return;
}
if (sourceProperty is ArrayList) {
copyArrayList(targetObj, propertyName, sourceObj);
return;
}
if (sourceProperty is ArrayCollection) {
copyArrayCollection(targetObj, propertyName, sourceProperty);
return;
}
copyObject(targetObj, propertyName, sourceProperty);
}
public static function cloneProperty(sourceObj:*, targetObj:*, propertyName:String):void {
const sourceProperty:* = sourceObj[propertyName];
if (sourceProperty is Array) {
copyArray(targetObj, propertyName, sourceProperty);
return;
}
if (sourceProperty is ArrayList) {
copyArrayList(targetObj, propertyName, sourceProperty);
return;
}
if (sourceProperty is ArrayCollection) {
copyArrayCollection(targetObj, propertyName, sourceProperty);
return;
}
copyObject(targetObj, propertyName, sourceProperty);
}
}
}
|
package dolly.utils {
import dolly.core.dolly_internal;
import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
use namespace dolly_internal;
public class PropertyUtil {
dolly_internal static function copyArray(targetObj:*, propertyName:String, sourceProperty:*):void {
targetObj[propertyName] = (sourceProperty as Array).slice();
}
dolly_internal static function copyArrayList(targetObj:*, propertyName:String, arrayList:ArrayList):void {
targetObj[propertyName] = arrayList.source ? new ArrayList(arrayList.source) : new ArrayList();
}
dolly_internal static function copyArrayCollection(targetObj:*, propertyName:String, sourceProperty:*):void {
const arrayCollection:ArrayCollection = (sourceProperty as ArrayCollection);
targetObj[propertyName] = arrayCollection.source ?
new ArrayCollection(arrayCollection.source.slice()) :
new ArrayCollection();
}
private static function copyObject(targetObj:*, propertyName:String, sourceProperty:*):void {
targetObj[propertyName] = sourceProperty;
}
public static function copyProperty(sourceObj:*, targetObj:*, propertyName:String):void {
const sourceProperty:* = sourceObj[propertyName];
if (sourceProperty is Array) {
copyArray(targetObj, propertyName, sourceProperty);
return;
}
if (sourceProperty is ArrayList) {
copyArrayList(targetObj, propertyName, sourceObj);
return;
}
if (sourceProperty is ArrayCollection) {
copyArrayCollection(targetObj, propertyName, sourceProperty);
return;
}
copyObject(targetObj, propertyName, sourceProperty);
}
public static function cloneProperty(sourceObj:*, targetObj:*, propertyName:String):void {
const sourceProperty:* = sourceObj[propertyName];
if (sourceProperty is Array) {
copyArray(targetObj, propertyName, sourceProperty);
return;
}
if (sourceProperty is ArrayList) {
copyArrayList(targetObj, propertyName, sourceProperty);
return;
}
if (sourceProperty is ArrayCollection) {
copyArrayCollection(targetObj, propertyName, sourceProperty);
return;
}
copyObject(targetObj, propertyName, sourceProperty);
}
}
}
|
Change namespace of methods in PropertyUtil class from "private" to "dolly_internal".
|
Change namespace of methods in PropertyUtil class from "private" to "dolly_internal".
|
ActionScript
|
mit
|
Yarovoy/dolly
|
aa177f1a53ea74db52ae038af097b4a752ff6771
|
VectorEditorStandalone/src/org/jbei/registry/Constants.as
|
VectorEditorStandalone/src/org/jbei/registry/Constants.as
|
package org.jbei.registry
{
/**
* @author Zinovii Dmytriv
*/
public final class Constants
{
public static const APPLICATION_NAME:String = "Vector Editor (Beta)";
public static const VERSION:String = "1.4.7";
public static const ENTRY_REGISTRY_URL:String = "https://registry.jbei.org/entry/view/";
public static const REPORT_BUG_URL:String = "http://code.google.com/p/vectoreditor/issues/entry?template=Report%20Bug";
public static const SUGGEST_FEATURE_URL:String = "http://code.google.com/p/vectoreditor/issues/entry?template=Suggest%20Feature";
}
}
|
package org.jbei.registry
{
/**
* @author Zinovii Dmytriv
*/
public final class Constants
{
public static const APPLICATION_NAME:String = "Vector Editor (Beta)";
public static const VERSION:String = "1.4.8";
public static const ENTRY_REGISTRY_URL:String = "https://registry.jbei.org/entry/view/";
public static const REPORT_BUG_URL:String = "http://code.google.com/p/vectoreditor/issues/entry?template=Report%20Bug";
public static const SUGGEST_FEATURE_URL:String = "http://code.google.com/p/vectoreditor/issues/entry?template=Suggest%20Feature";
}
}
|
Bump up version number to 1.4.8: copy jbei-seq-xml to clipboard
|
Bump up version number to 1.4.8: copy jbei-seq-xml to clipboard
git-svn-id: adbdea8fc1759bd16b0eaf24a244a7e5f870a654@278 fe3f0490-d73e-11de-a956-c71e7d3a9d2f
|
ActionScript
|
bsd-3-clause
|
CIDARLAB/mage-editor,CIDARLAB/mage-editor,CIDARLAB/mage-editor
|
4bae1b893fe181e323b34ed144a467d6cfb74202
|
src/aerys/minko/render/Viewport.as
|
src/aerys/minko/render/Viewport.as
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import aerys.minko.type.Signal;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.Stage3D;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.geom.Point;
/**
* The Viewport is the display area where a 3D scene can be rendered.
*
* @author Jean-Marc Le Roux
*
*/
public class Viewport extends Sprite
{
private static const ZERO2 : Point = new Point();
private var _stage3d : Stage3D = null;
private var _context3d : Context3DResource = null;
private var _width : uint = 0;
private var _height : uint = 0;
private var _autoResize : Boolean = false;
private var _antiAliasing : uint = 0;
private var _backgroundColor : uint = 0;
private var _backBuffer : RenderTarget = null;
private var _invalidBackBuffer : Boolean = false;
private var _alwaysOnTop : Boolean = false;
private var _mask : Shape = new Shape();
private var _mouseManager : MouseManager = new MouseManager();
private var _keyboardManager : KeyboardManager = new KeyboardManager();
private var _resized : Signal = new Signal('Viewport.resized');
minko_render function get context3D() : Context3DResource
{
return _context3d;
}
minko_render function get backBuffer() : RenderTarget
{
var positionOnStage : Point = localToGlobal(ZERO2);
if (_stage3d.x != positionOnStage.x || _stage3d.y != positionOnStage.y)
updateStage3D()
return _backBuffer;
}
public function get ready() : Boolean
{
return _stage3d != null && _stage3d.context3D != null && _backBuffer != null;
}
/**
* Whether the viewport is visible or not.
* @return
*
*/
override public function set visible(value : Boolean) : void
{
if (_stage3d)
_stage3d.visible = value;
super.visible = value;
}
override public function set x(value : Number) : void
{
super.x = value;
updateStage3D();
}
override public function set y(value : Number) : void
{
super.y = value;
updateStage3D();
}
/**
* The width of the display area.
* @return
*
*/
override public function get width() : Number
{
return _width;
}
override public function set width(value : Number) : void
{
resize(value, _height);
}
/**
* The height of the display area.
* @return
*
*/
override public function get height() : Number
{
return _height;
}
override public function set height(value : Number) : void
{
resize(_width, value);
}
public function get alwaysOnTop() : Boolean
{
return _alwaysOnTop;
}
public function set alwaysOnTop(value : Boolean) : void
{
_alwaysOnTop = value;
}
public function get keyboardManager() : KeyboardManager
{
return _keyboardManager;
}
public function get mouseManager() : MouseManager
{
return _mouseManager;
}
/**
* The signal executed when the viewport is resized.
* Callback functions for this signal should accept the following
* arguments:
* <ul>
* <li>viewport : Viewport, the viewport executing the signal</li>
* <li>width : Number, the new width of the viewport</li>
* <li>height : Number, the new height of the viewport</li>
* </ul>
* @return
*
*/
public function get resized() : Signal
{
return _resized;
}
/**
* The background color of the display area. This value must use the
* RGB format.
* @return
*
*/
public function get backgroundColor() : uint
{
return _backgroundColor;
}
public function set backgroundColor(value : uint) : void
{
_backgroundColor = value;
updateBackBuffer();
}
/**
* The anti-aliasing to use (0, 2, 4, 8 or 16). The actual anti-aliasing
* used for rendering depends on the hardware capabilities. If the specified
* anti-aliasing value is not supported, the value 0 will be used.
* @return
*
*/
public function get antiAliasing() : uint
{
return _antiAliasing;
}
public function set antiAliasing(value : uint) : void
{
_antiAliasing = value;
updateStage3D();
}
/**
* The driver informations provided by the Stage3D API.
*/
public function get driverInfo() : String
{
return _stage3d && _stage3d.context3D
? _stage3d.context3D.driverInfo
: null;
}
public function Viewport(antiAliasing : uint = 0,
width : uint = 0,
height : uint = 0)
{
_antiAliasing = antiAliasing;
if (width == 0 && height == 0)
_autoResize = true;
_width = width;
_height = height;
initialize();
}
private function initialize() : void
{
_mouseManager.bind(this);
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
}
private function addedToStageHandler(event : Event) : void
{
_keyboardManager.bind(stage);
parent.addEventListener(Event.RESIZE, parentResizedHandler);
stage.addEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.addEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
stage.addEventListener(Event.RESIZE, stageResizedHandler);
setupOnStage(stage);
}
private function removedFromStageHandler(event : Event) : void
{
_keyboardManager.unbind(stage);
parent.removeEventListener(Event.RESIZE, parentResizedHandler);
stage.removeEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.removeEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
stage.removeEventListener(Event.RESIZE, stageResizedHandler);
if (_stage3d != null)
_stage3d.visible = false;
}
private function setupOnStage(stage : Stage, stage3dId : uint = 0) : void
{
if (_autoResize)
{
_width = stage.stageWidth;
_height = stage.stageHeight;
}
if (!_stage3d)
{
_stage3d = stage.stage3Ds[stage3dId];
_stage3d.addEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d.requestContext3D();
}
else
{
_stage3d.visible = visible;
}
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
}
/**
* Dispose the Viewport and all the Stage3D related objects. After this operation,
* the Viewport cannot be used anymore and is ready for garbage collection.
*/
public function dispose():void
{
if (_stage3d != null)
{
_stage3d.removeEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d = null;
}
if (_context3d != null)
{
_context3d.dispose();
_context3d = null;
}
return ;
}
/**
* Resize the display area. The "resized" signal is executed when the new width and
* height have be set.
* @param width
* @param height
*
*/
public function resize(width : Number, height : Number) : void
{
_autoResize = false;
setSize(width, height);
}
private function setSize(width : Number, height : Number) : void
{
if (width == _width && _height == height)
return ;
_width = width;
_height = height;
updateStage3D();
updateBackBuffer();
_resized.execute(this, width, height);
}
private function stageResizedHandler(event : Event) : void
{
updateMask();
updateStage3D();
updateBackBuffer();
}
private function parentResizedHandler(event : Event) : void
{
if (_autoResize)
{
if (parent == stage)
setSize(stage.stageWidth, stage.stageHeight);
else
setSize(parent.width, parent.height);
}
}
private function context3dCreatedHandler(event : Event) : void
{
_context3d = new Context3DResource(_stage3d.context3D);
updateStage3D();
updateBackBuffer();
dispatchEvent(new Event(Event.INIT));
}
private function updateBackBuffer() : void
{
if (_width == 0 || _height == 0 || _stage3d == null || _stage3d.context3D == null)
return ;
_invalidBackBuffer = false;
var backBufferWidth : Number = _width * getGlobalScaleX();
var backBufferHeight : Number = _height * getGlobalScaleY();
_stage3d.context3D.configureBackBuffer(backBufferWidth, backBufferHeight, _antiAliasing, true);
_backBuffer = new RenderTarget(backBufferWidth, backBufferHeight, null, 0, _backgroundColor);
graphics.clear();
graphics.beginFill(0, 0);
graphics.drawRect(0, 0, _width, _height);
}
private function updateStage3D() : void
{
if (_stage3d == null)
return ;
var upperLeft : Point = localToGlobal(ZERO2);
_stage3d.x = upperLeft.x;
_stage3d.y = upperLeft.y;
if (_width > 2048)
{
_stage3d.x = (_width - 2048) * 0.5;
_width = 2048;
}
else
_stage3d.x = upperLeft.x;
if (_height > 2048)
{
_stage3d.y = (_height - 2048) * 0.5;
_height = 2048;
}
else
_stage3d.y = upperLeft.y;
updateMask();
}
private function updateMask() : void
{
if (!stage)
return ;
var numChildren : uint = stage.numChildren;
var i : uint = 0;
if (_alwaysOnTop)
{
var gfx : Graphics = _mask.graphics;
var stageWidth : int = stage.stageWidth;
var stageHeight : int = stage.stageHeight;
gfx.clear();
gfx.beginFill(0);
gfx.moveTo(0, 0);
gfx.lineTo(stageWidth, 0);
gfx.lineTo(stageWidth, stageHeight);
gfx.lineTo(0., stageHeight);
gfx.lineTo(0, 0);
gfx.moveTo(_stage3d.x, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y);
gfx.endFill();
for (i = 0; i < numChildren; ++i)
stage.getChildAt(i).mask = _mask;
}
else
{
for (i = 0; i < numChildren; ++i)
{
var child : DisplayObject = stage.getChildAt(i);
if (child.mask == _mask)
child.mask = null;
}
}
}
private function displayObjectAddedToStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (displayObject.parent == stage)
updateMask();
}
private function displayObjectRemovedFromStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (_autoResize && displayObject.parent == stage)
displayObject.mask = null;
}
private function getGlobalScaleX() : Number
{
var currentParent : DisplayObjectContainer = parent;
var scale : Number = scaleX;
while(currentParent != stage)
{
scale *= currentParent.scaleX;
currentParent = currentParent.parent;
}
return scale;
}
private function getGlobalScaleY() : Number
{
var currentParent : DisplayObjectContainer = parent;
var scale : Number = scaleY;
while(currentParent != stage)
{
scale *= currentParent.scaleY;
currentParent = currentParent.parent;
}
return scale;
}
}
}
|
package aerys.minko.render
{
import aerys.minko.ns.minko_render;
import aerys.minko.render.resource.Context3DResource;
import aerys.minko.type.KeyboardManager;
import aerys.minko.type.MouseManager;
import aerys.minko.type.Signal;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.Stage;
import flash.display.Stage3D;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.geom.Point;
/**
* The Viewport is the display area where a 3D scene can be rendered.
*
* @author Jean-Marc Le Roux
*
*/
public class Viewport extends Sprite
{
private static const ZERO2 : Point = new Point();
private var _stage3d : Stage3D = null;
private var _context3d : Context3DResource = null;
private var _stage3dId : uint = 0;
private var _width : uint = 0;
private var _height : uint = 0;
private var _autoResize : Boolean = false;
private var _antiAliasing : uint = 0;
private var _backgroundColor : uint = 0;
private var _backBuffer : RenderTarget = null;
private var _invalidBackBuffer : Boolean = false;
private var _alwaysOnTop : Boolean = false;
private var _mask : Shape = new Shape();
private var _mouseManager : MouseManager = new MouseManager();
private var _keyboardManager : KeyboardManager = new KeyboardManager();
private var _resized : Signal = new Signal('Viewport.resized');
minko_render function get context3D() : Context3DResource
{
return _context3d;
}
minko_render function get backBuffer() : RenderTarget
{
var positionOnStage : Point = localToGlobal(ZERO2);
if (_stage3d.x != positionOnStage.x || _stage3d.y != positionOnStage.y)
updateStage3D()
return _backBuffer;
}
public function get ready() : Boolean
{
return _stage3d != null && _stage3d.context3D != null && _backBuffer != null;
}
/**
* Whether the viewport is visible or not.
* @return
*
*/
override public function set visible(value : Boolean) : void
{
if (_stage3d)
_stage3d.visible = value;
super.visible = value;
}
override public function set x(value : Number) : void
{
super.x = value;
updateStage3D();
}
override public function set y(value : Number) : void
{
super.y = value;
updateStage3D();
}
/**
* The width of the display area.
* @return
*
*/
override public function get width() : Number
{
return _width;
}
override public function set width(value : Number) : void
{
resize(value, _height);
}
/**
* The height of the display area.
* @return
*
*/
override public function get height() : Number
{
return _height;
}
override public function set height(value : Number) : void
{
resize(_width, value);
}
public function get alwaysOnTop() : Boolean
{
return _alwaysOnTop;
}
public function set alwaysOnTop(value : Boolean) : void
{
_alwaysOnTop = value;
}
public function get keyboardManager() : KeyboardManager
{
return _keyboardManager;
}
public function get mouseManager() : MouseManager
{
return _mouseManager;
}
/**
* The signal executed when the viewport is resized.
* Callback functions for this signal should accept the following
* arguments:
* <ul>
* <li>viewport : Viewport, the viewport executing the signal</li>
* <li>width : Number, the new width of the viewport</li>
* <li>height : Number, the new height of the viewport</li>
* </ul>
* @return
*
*/
public function get resized() : Signal
{
return _resized;
}
/**
* The background color of the display area. This value must use the
* RGB format.
* @return
*
*/
public function get backgroundColor() : uint
{
return _backgroundColor;
}
public function set backgroundColor(value : uint) : void
{
_backgroundColor = value;
updateBackBuffer();
}
/**
* The anti-aliasing to use (0, 2, 4, 8 or 16). The actual anti-aliasing
* used for rendering depends on the hardware capabilities. If the specified
* anti-aliasing value is not supported, the value 0 will be used.
* @return
*
*/
public function get antiAliasing() : uint
{
return _antiAliasing;
}
public function set antiAliasing(value : uint) : void
{
_antiAliasing = value;
updateStage3D();
}
/**
* The driver informations provided by the Stage3D API.
*/
public function get driverInfo() : String
{
return _stage3d && _stage3d.context3D
? _stage3d.context3D.driverInfo
: null;
}
public function Viewport(antiAliasing : uint = 0,
stage3dId : uint = 0,
width : uint = 0,
height : uint = 0)
{
_stage3dId = stage3dId;
_antiAliasing = antiAliasing;
_autoResize = width == 0 && height == 0;
_width = width;
_height = height;
initialize();
}
private function initialize() : void
{
_mouseManager.bind(this);
addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStageHandler);
}
private function addedToStageHandler(event : Event) : void
{
_keyboardManager.bind(stage);
parent.addEventListener(Event.RESIZE, parentResizedHandler);
stage.addEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.addEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
stage.addEventListener(Event.RESIZE, stageResizedHandler);
setupOnStage(stage);
}
private function removedFromStageHandler(event : Event) : void
{
_keyboardManager.unbind(stage);
parent.removeEventListener(Event.RESIZE, parentResizedHandler);
stage.removeEventListener(Event.ADDED_TO_STAGE, displayObjectAddedToStageHandler);
stage.removeEventListener(Event.REMOVED_FROM_STAGE, displayObjectRemovedFromStageHandler);
stage.removeEventListener(Event.RESIZE, stageResizedHandler);
if (_stage3d != null)
_stage3d.visible = false;
}
private function setupOnStage(stage : Stage) : void
{
if (_autoResize)
{
_width = stage.stageWidth;
_height = stage.stageHeight;
}
if (!_stage3d)
{
_stage3d = stage.stage3Ds[_stage3dId];
_stage3d.addEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d.requestContext3D();
}
else
{
_stage3d.visible = visible;
}
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
}
/**
* Dispose the Viewport and all the Stage3D related objects. After this operation,
* the Viewport cannot be used anymore and is ready for garbage collection.
*/
public function dispose():void
{
if (_stage3d != null)
{
_stage3d.removeEventListener(Event.CONTEXT3D_CREATE, context3dCreatedHandler);
_stage3d = null;
}
if (_context3d != null)
{
_context3d.dispose();
_context3d = null;
}
return ;
}
/**
* Resize the display area. The "resized" signal is executed when the new width and
* height have be set.
* @param width
* @param height
*
*/
public function resize(width : Number, height : Number) : void
{
_autoResize = false;
setSize(width, height);
}
private function setSize(width : Number, height : Number) : void
{
if (width == _width && _height == height)
return ;
_width = width;
_height = height;
updateStage3D();
updateBackBuffer();
_resized.execute(this, width, height);
}
private function stageResizedHandler(event : Event) : void
{
updateMask();
updateStage3D();
updateBackBuffer();
}
private function parentResizedHandler(event : Event) : void
{
if (_autoResize)
{
if (parent == stage)
setSize(stage.stageWidth, stage.stageHeight);
else
setSize(parent.width, parent.height);
}
}
private function context3dCreatedHandler(event : Event) : void
{
_context3d = new Context3DResource(_stage3d.context3D);
updateStage3D();
updateBackBuffer();
dispatchEvent(new Event(Event.INIT));
}
private function updateBackBuffer() : void
{
if (_width == 0 || _height == 0 || _stage3d == null || _stage3d.context3D == null)
return ;
_invalidBackBuffer = false;
var backBufferWidth : Number = _width * getGlobalScaleX();
var backBufferHeight : Number = _height * getGlobalScaleY();
_stage3d.context3D.configureBackBuffer(backBufferWidth, backBufferHeight, _antiAliasing, true);
_backBuffer = new RenderTarget(backBufferWidth, backBufferHeight, null, 0, _backgroundColor);
graphics.clear();
graphics.beginFill(0, 0);
graphics.drawRect(0, 0, _width, _height);
}
private function updateStage3D() : void
{
if (_stage3d == null)
return ;
var upperLeft : Point = localToGlobal(ZERO2);
_stage3d.x = upperLeft.x;
_stage3d.y = upperLeft.y;
if (_width > 2048)
{
_stage3d.x = (_width - 2048) * 0.5;
_width = 2048;
}
else
_stage3d.x = upperLeft.x;
if (_height > 2048)
{
_stage3d.y = (_height - 2048) * 0.5;
_height = 2048;
}
else
_stage3d.y = upperLeft.y;
updateMask();
}
private function updateMask() : void
{
if (!stage)
return ;
var numChildren : uint = stage.numChildren;
var i : uint = 0;
if (_alwaysOnTop)
{
var gfx : Graphics = _mask.graphics;
var stageWidth : int = stage.stageWidth;
var stageHeight : int = stage.stageHeight;
gfx.clear();
gfx.beginFill(0);
gfx.moveTo(0, 0);
gfx.lineTo(stageWidth, 0);
gfx.lineTo(stageWidth, stageHeight);
gfx.lineTo(0., stageHeight);
gfx.lineTo(0, 0);
gfx.moveTo(_stage3d.x, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y + height);
gfx.lineTo(_stage3d.x + width, _stage3d.y);
gfx.lineTo(_stage3d.x, _stage3d.y);
gfx.endFill();
for (i = 0; i < numChildren; ++i)
stage.getChildAt(i).mask = _mask;
}
else
{
for (i = 0; i < numChildren; ++i)
{
var child : DisplayObject = stage.getChildAt(i);
if (child.mask == _mask)
child.mask = null;
}
}
}
private function displayObjectAddedToStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (displayObject.parent == stage)
updateMask();
}
private function displayObjectRemovedFromStageHandler(event : Event) : void
{
var displayObject : DisplayObject = event.target as DisplayObject;
if (_autoResize && displayObject.parent == stage)
displayObject.mask = null;
}
private function getGlobalScaleX() : Number
{
var currentParent : DisplayObjectContainer = parent;
var scale : Number = scaleX;
while(currentParent != stage)
{
scale *= currentParent.scaleX;
currentParent = currentParent.parent;
}
return scale;
}
private function getGlobalScaleY() : Number
{
var currentParent : DisplayObjectContainer = parent;
var scale : Number = scaleY;
while(currentParent != stage)
{
scale *= currentParent.scaleY;
currentParent = currentParent.parent;
}
return scale;
}
}
}
|
add stage3dId argument to Viewport constructor
|
add stage3dId argument to Viewport constructor
|
ActionScript
|
mit
|
aerys/minko-as3
|
c715fe38887fa384706b9bdd7c8345fbae3d839a
|
src/aerys/minko/render/shader/part/DiffuseShaderPart.as
|
src/aerys/minko/render/shader/part/DiffuseShaderPart.as
|
package aerys.minko.render.shader.part
{
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class DiffuseShaderPart extends ShaderPart
{
/**
* The shader part to use a diffuse map or fallback and use a solid color.
*
* @param main
*
*/
public function DiffuseShaderPart(main : Shader)
{
super(main);
}
public function getDiffuse() : SFloat
{
var diffuseColor : SFloat = null;
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_MAP))
{
var uv : SFloat = vertexUV.xy;
var diffuseMap : SFloat = meshBindings.getTextureParameter(
BasicProperties.DIFFUSE_MAP,
meshBindings.getConstant(BasicProperties.DIFFUSE_FILTERING, SamplerFiltering.LINEAR),
meshBindings.getConstant(BasicProperties.DIFFUSE_MIPMAPPING, SamplerMipMapping.LINEAR),
meshBindings.getConstant(BasicProperties.DIFFUSE_WRAPPING, SamplerWrapping.REPEAT)
);
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_SCALE))
uv.scaleBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_SCALE, 2));
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_OFFSET))
uv.incrementBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_OFFSET, 2));
diffuseColor = sampleTexture(diffuseMap,interpolate(uv));
}
else if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR))
{
diffuseColor = meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR, 4);
}
else
{
diffuseColor = float4(0., 0., 0., 1.);
}
// Apply HLSA modifiers
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR_MATRIX))
{
diffuseColor = multiply4x4(
diffuseColor,
meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR_MATRIX, 16)
);
}
return diffuseColor;
}
}
}
|
package aerys.minko.render.shader.part
{
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.type.enum.SamplerFiltering;
import aerys.minko.type.enum.SamplerMipMapping;
import aerys.minko.type.enum.SamplerWrapping;
public class DiffuseShaderPart extends ShaderPart
{
/**
* The shader part to use a diffuse map or fallback and use a solid color.
*
* @param main
*
*/
public function DiffuseShaderPart(main : Shader)
{
super(main);
}
public function getDiffuseColor() : SFloat
{
var diffuseColor : SFloat = null;
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_MAP))
{
var uv : SFloat = vertexUV.xy;
var diffuseMap : SFloat = meshBindings.getTextureParameter(
BasicProperties.DIFFUSE_MAP,
meshBindings.getConstant(BasicProperties.DIFFUSE_FILTERING, SamplerFiltering.LINEAR),
meshBindings.getConstant(BasicProperties.DIFFUSE_MIPMAPPING, SamplerMipMapping.LINEAR),
meshBindings.getConstant(BasicProperties.DIFFUSE_WRAPPING, SamplerWrapping.REPEAT)
);
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_SCALE))
uv.scaleBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_SCALE, 2));
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_UV_OFFSET))
uv.incrementBy(meshBindings.getParameter(BasicProperties.DIFFUSE_UV_OFFSET, 2));
diffuseColor = sampleTexture(diffuseMap,interpolate(uv));
}
else if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR))
{
diffuseColor = meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR, 4);
}
else
{
diffuseColor = float4(0., 0., 0., 1.);
}
// Apply HLSA modifiers
if (meshBindings.propertyExists(BasicProperties.DIFFUSE_COLOR_MATRIX))
{
diffuseColor = multiply4x4(
diffuseColor,
meshBindings.getParameter(BasicProperties.DIFFUSE_COLOR_MATRIX, 16)
);
}
return diffuseColor;
}
}
}
|
rename DiffuseShaderPart.getDiffuse() to DiffuseShaderPart.getDiffuseColor() for consistency
|
rename DiffuseShaderPart.getDiffuse() to DiffuseShaderPart.getDiffuseColor() for consistency
|
ActionScript
|
mit
|
aerys/minko-as3
|
6b84e0587356ed09aa74ee8366f6725249b7365f
|
src/aerys/minko/scene/controller/light/LightController.as
|
src/aerys/minko/scene/controller/light/LightController.as
|
package aerys.minko.scene.controller.light
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.data.LightDataProvider;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.light.AbstractLight;
import aerys.minko.type.binding.DataBindings;
import flash.display.BitmapData;
public class LightController extends AbstractController
{
private var _light : AbstractLight;
private var _lightData : LightDataProvider;
public function get lightData() : LightDataProvider
{
return _lightData;
}
protected function get light() : AbstractLight
{
return _light;
}
public function LightController(lightClass : Class)
{
super(lightClass);
initialize();
}
private function initialize() : void
{
targetAdded.add(lightAddedHandler);
targetRemoved.add(lightRemovedHandler);
}
protected function lightAddedHandler(ctrl : LightController,
light : AbstractLight) : void
{
_lightData = new LightDataProvider(-1);
_lightData.setLightProperty('type', light.type);
_lightData.setLightProperty('localToWorld', light.localToWorld);
_lightData.setLightProperty('worldToLocal', light.worldToLocal);
_lightData.setLightProperty('enabled', true);
light.addedToScene.add(lightAddedToSceneHandler);
light.removedFromScene.add(lightRemovedFromSceneHandler);
_light = light;
}
protected function lightRemovedHandler(ctrl : LightController,
light : AbstractLight) : void
{
throw new Error();
}
protected function lightAddedToSceneHandler(light : AbstractLight,
scene : Scene) : void
{
_lightData.changed.add(lightDataChangedHandler);
sortLights(scene);
// if (!scene.enterFrame.hasCallback(sceneEnterFrameHandler))
// scene.enterFrame.add(sceneEnterFrameHandler);
}
protected function lightRemovedFromSceneHandler(light : AbstractLight,
scene : Scene) : void
{
_lightData.changed.remove(lightDataChangedHandler);
if (!scene.enterFrame.hasCallback(sceneEnterFrameHandler))
scene.enterFrame.add(sceneEnterFrameHandler);
}
protected function lightDataChangedHandler(lightData : LightDataProvider,
propertyName : String) : void
{
// nothing
}
private function updateDataProvider(lightId : int) : void
{
var newDataProvider : LightDataProvider = new LightDataProvider(lightId);
for (var propertyName : String in _lightData.dataDescriptor)
{
propertyName = LightDataProvider.getPropertyName(propertyName);
newDataProvider.setLightProperty(
propertyName,
_lightData.getLightProperty(propertyName)
);
}
_lightData.changed.remove(lightDataChangedHandler);
_lightData = newDataProvider;
_lightData.changed.add(lightDataChangedHandler);
}
private static function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : uint) : void
{
scene.enterFrame.remove(sceneEnterFrameHandler);
sortLights(scene);
}
private static function sortLights(scene : Scene) : void
{
var sceneBindings : DataBindings = scene.bindings;
var lights : Vector.<ISceneNode> = scene.getDescendantsByType(AbstractLight);
var numLights : uint = lights.length;
var lightId : uint;
// remove all lights from scene bindings.
var numProviders : uint = sceneBindings.numProviders;
for (var providerId : int = numProviders - 1; providerId >= 0; --providerId)
{
var provider : LightDataProvider = sceneBindings.getProviderAt(providerId)
as LightDataProvider;
if (provider)
sceneBindings.removeProvider(provider);
}
// sorting allows to limit the number of shaders that will be generated
// if (add|remov)ing many lights all the time (add order won't matter anymore).
lights.sort(compare);
// update all descriptors.
for (lightId = 0; lightId < numLights; ++lightId)
{
var light : AbstractLight = lights[lightId] as AbstractLight;
var ctrl : LightController = light.getControllersByType(LightController)[0]
as LightController;
ctrl.updateDataProvider(lightId);
sceneBindings.addProvider(ctrl._lightData);
}
}
private static function compare(light1 : AbstractLight, light2 : AbstractLight) : int
{
return light1.type - light2.type;
}
}
}
|
package aerys.minko.scene.controller.light
{
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.data.LightDataProvider;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Scene;
import aerys.minko.scene.node.light.AbstractLight;
import aerys.minko.type.binding.DataBindings;
import flash.display.BitmapData;
public class LightController extends AbstractController
{
private var _light : AbstractLight;
private var _lightData : LightDataProvider;
public function get lightData() : LightDataProvider
{
return _lightData;
}
protected function get light() : AbstractLight
{
return _light;
}
public function LightController(lightClass : Class)
{
super(lightClass);
initialize();
}
private function initialize() : void
{
targetAdded.add(lightAddedHandler);
targetRemoved.add(lightRemovedHandler);
}
protected function lightAddedHandler(ctrl : LightController,
light : AbstractLight) : void
{
_lightData = new LightDataProvider(-1);
_lightData.setLightProperty('type', light.type);
_lightData.setLightProperty('localToWorld', light.localToWorld);
_lightData.setLightProperty('worldToLocal', light.worldToLocal);
_lightData.setLightProperty('enabled', true);
light.addedToScene.add(lightAddedToSceneHandler);
light.removedFromScene.add(lightRemovedFromSceneHandler);
_light = light;
}
protected function lightRemovedHandler(ctrl : LightController,
light : AbstractLight) : void
{
throw new Error();
}
protected function lightAddedToSceneHandler(light : AbstractLight,
scene : Scene) : void
{
_lightData.changed.add(lightDataChangedHandler);
sortLights(scene);
// if (!scene.enterFrame.hasCallback(sceneEnterFrameHandler))
// scene.enterFrame.add(sceneEnterFrameHandler);
}
protected function lightRemovedFromSceneHandler(light : AbstractLight,
scene : Scene) : void
{
_lightData.changed.remove(lightDataChangedHandler);
sortLights(scene);
// if (!scene.enterFrame.hasCallback(sceneEnterFrameHandler))
// scene.enterFrame.add(sceneEnterFrameHandler);
}
protected function lightDataChangedHandler(lightData : LightDataProvider,
propertyName : String) : void
{
// nothing
}
private function updateDataProvider(lightId : int) : void
{
var newDataProvider : LightDataProvider = new LightDataProvider(lightId);
for (var propertyName : String in _lightData.dataDescriptor)
{
propertyName = LightDataProvider.getPropertyName(propertyName);
newDataProvider.setLightProperty(
propertyName,
_lightData.getLightProperty(propertyName)
);
}
_lightData.changed.remove(lightDataChangedHandler);
_lightData = newDataProvider;
_lightData.changed.add(lightDataChangedHandler);
}
private static function sceneEnterFrameHandler(scene : Scene,
viewport : Viewport,
destination : BitmapData,
time : uint) : void
{
scene.enterFrame.remove(sceneEnterFrameHandler);
sortLights(scene);
}
private static function sortLights(scene : Scene) : void
{
var sceneBindings : DataBindings = scene.bindings;
var lights : Vector.<ISceneNode> = scene.getDescendantsByType(AbstractLight);
var numLights : uint = lights.length;
var lightId : uint;
// remove all lights from scene bindings.
var numProviders : uint = sceneBindings.numProviders;
for (var providerId : int = numProviders - 1; providerId >= 0; --providerId)
{
var provider : LightDataProvider = sceneBindings.getProviderAt(providerId)
as LightDataProvider;
if (provider)
sceneBindings.removeProvider(provider);
}
// sorting allows to limit the number of shaders that will be generated
// if (add|remov)ing many lights all the time (add order won't matter anymore).
lights.sort(compare);
// update all descriptors.
for (lightId = 0; lightId < numLights; ++lightId)
{
var light : AbstractLight = lights[lightId] as AbstractLight;
var ctrl : LightController = light.getControllersByType(LightController)[0]
as LightController;
ctrl.updateDataProvider(lightId);
sceneBindings.addProvider(ctrl._lightData);
}
}
private static function compare(light1 : AbstractLight, light2 : AbstractLight) : int
{
return light1.type - light2.type;
}
}
}
|
fix LightController to sort lights directly when a the its target light is removed from the scene
|
fix LightController to sort lights directly when a the its target light is removed from the scene
|
ActionScript
|
mit
|
aerys/minko-as3
|
de2cd629ecd1807fc95f16c2e88d47db5ed5c523
|
src/aerys/minko/type/stream/VertexStream.as
|
src/aerys/minko/type/stream/VertexStream.as
|
package aerys.minko.type.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.ressource.VertexBufferRessource;
import aerys.minko.type.IVersionnable;
import aerys.minko.type.stream.format.VertexComponent;
import aerys.minko.type.stream.format.VertexComponentType;
import aerys.minko.type.stream.format.VertexFormat;
import flash.utils.ByteArray;
public final class VertexStream implements IVersionnable, IVertexStream
{
use namespace minko_stream;
public static const DEFAULT_FORMAT : VertexFormat = VertexFormat.XYZ_UV;
minko_stream var _data : Vector.<Number> = null;
private var _dynamic : Boolean = false;
private var _version : uint = 0;
private var _format : VertexFormat = null;
private var _ressource : VertexBufferRessource = null;
private var _length : uint = 0;
public function get format() : VertexFormat { return _format; }
public function get version() : uint { return _version; }
public function get dynamic() : Boolean { return _dynamic; }
public function get ressource() : VertexBufferRessource { return _ressource; }
public function get length() : uint { return _length; }
public function VertexStream(data : Vector.<Number> = null,
format : VertexFormat = null,
dynamic : Boolean = false)
{
super();
initialize(data, format, dynamic);
}
private function initialize(data : Vector.<Number> = null,
format : VertexFormat = null,
dynamic : Boolean = false) : void
{
_ressource = new VertexBufferRessource(this);
_format = format || DEFAULT_FORMAT;
if (data && data.length && data.length % _format.dwordsPerVertex)
throw new Error("Incompatible vertex format: the data length does not match.");
_data = data ? data.concat() : new Vector.<Number>();
_dynamic = dynamic;
invalidate();
}
public function deleteVertexByIndex(index : uint) : Boolean
{
if (index > length)
return false;
_data.splice(index, _format.dwordsPerVertex);
invalidate();
return true;
}
public function getSubStreamByComponent(vertexComponent : VertexComponent) : VertexStream
{
if (_format.components.indexOf(vertexComponent) != -1)
return this;
return null;
}
public function getSubStreamById(id : int) : VertexStream
{
return this;
}
public function push(...data) : void
{
var dataLength : int = data.length;
if (dataLength % _format.dwordsPerVertex)
throw new Error("Invalid data length.");
for (var i : int = 0; i < dataLength; i++)
_data.push(data[i]);
invalidate();
}
public function pushData(data : Vector.<Number>) : void
{
var dataLength : int = data.length;
if (dataLength % _format.dwordsPerVertex)
throw new Error("Invalid data length.");
for (var i : int = 0; i < dataLength; i++)
_data.push(data[i]);
invalidate();
}
public function disposeLocalData() : void
{
if (length != ressource.numVertices)
throw new Error("Unable to dispose local data: "
+ "some vertices have not been uploaded.");
_data = null;
_dynamic = false;
}
minko_stream function invalidate() : void
{
_length = _data.length / _format.dwordsPerVertex;
++_version;
}
public static function fromPositionsAndUVs(positions : Vector.<Number>,
uvs : Vector.<Number> = null,
dynamic : Boolean = false) : VertexStream
{
var numVertices : int = positions.length / 3;
var stride : int = uvs ? 5 : 3;
var data : Vector.<Number> = new Vector.<Number>(numVertices * stride, true);
for (var i : int = 0; i < numVertices; ++i)
{
var offset : int = i * stride;
data[offset] = positions[int(i * 3)];
data[int(offset + 1)] = positions[int(i * 3 + 1)];
data[int(offset + 2)] = positions[int(i * 3 + 2)];
if (uvs)
{
data[int(offset + 3)] = uvs[int(i * 2)];
data[int(offset + 4)] = uvs[int(i * 2 + 1)];
}
}
return new VertexStream(data,
uvs ? VertexFormat.XYZ_UV : VertexFormat.XYZ,
dynamic);
}
public static function fromByteArray(data : ByteArray,
count : int,
format : VertexFormat,
dynamic : Boolean = false) : VertexStream
{
var numFormats : int = format.components.length;
var nativeFormats : Vector.<int> = new Vector.<int>(numFormats, true);
var length : int = 0;
var tmp : Vector.<Number> = null;
var stream : VertexStream = new VertexStream(null, format, dynamic);
for (var k : int = 0; k < numFormats; k++)
nativeFormats[k] = format.components[k].nativeFormat;
stream._data = tmp;
tmp = new Vector.<Number>(format.dwordsPerVertex * count, true);
for (var j : int = 0; j < count; ++j)
{
for (var i : int = 0; i < numFormats; ++i)
{
switch (nativeFormats[i])
{
case VertexComponentType.FLOAT_4 :
tmp[int(length++)] = data.readFloat();
case VertexComponentType.FLOAT_3 :
tmp[int(length++)] = data.readFloat();
case VertexComponentType.FLOAT_2 :
tmp[int(length++)] = data.readFloat();
case VertexComponentType.FLOAT_1 :
tmp[int(length++)] = data.readFloat();
break ;
}
}
}
return stream;
}
}
}
|
package aerys.minko.type.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.ressource.VertexBufferRessource;
import aerys.minko.type.IVersionnable;
import aerys.minko.type.stream.format.VertexComponent;
import aerys.minko.type.stream.format.VertexComponentType;
import aerys.minko.type.stream.format.VertexFormat;
import flash.utils.ByteArray;
public final class VertexStream implements IVersionnable, IVertexStream
{
use namespace minko_stream;
public static const DEFAULT_FORMAT : VertexFormat = VertexFormat.XYZ_UV;
minko_stream var _data : Vector.<Number> = null;
private var _dynamic : Boolean = false;
private var _version : uint = 0;
private var _format : VertexFormat = null;
private var _ressource : VertexBufferRessource = null;
private var _length : uint = 0;
public function get format() : VertexFormat { return _format; }
public function get version() : uint { return _version; }
public function get dynamic() : Boolean { return _dynamic; }
public function get ressource() : VertexBufferRessource { return _ressource; }
public function get length() : uint { return _length; }
public function VertexStream(data : Vector.<Number> = null,
format : VertexFormat = null,
dynamic : Boolean = false)
{
super();
initialize(data, format, dynamic);
}
private function initialize(data : Vector.<Number> = null,
format : VertexFormat = null,
dynamic : Boolean = false) : void
{
_ressource = new VertexBufferRessource(this);
_format = format || DEFAULT_FORMAT;
if (data && data.length && data.length % _format.dwordsPerVertex)
throw new Error("Incompatible vertex format: the data length does not match.");
_data = data ? data.concat() : new Vector.<Number>();
_dynamic = dynamic;
invalidate();
}
public function deleteVertexByIndex(index : uint) : Boolean
{
if (index > length)
return false;
_data.splice(index, _format.dwordsPerVertex);
invalidate();
return true;
}
public function getSubStreamByComponent(vertexComponent : VertexComponent) : VertexStream
{
if (_format.components.indexOf(vertexComponent) != -1)
return this;
return null;
}
public function getSubStreamById(id : int) : VertexStream
{
return this;
}
public function push(...data) : void
{
var dataLength : int = data.length;
if (dataLength % _format.dwordsPerVertex)
throw new Error("Invalid data length.");
for (var i : int = 0; i < dataLength; i++)
_data.push(data[i]);
invalidate();
}
public function pushData(data : Vector.<Number>) : void
{
var dataLength : int = data.length;
if (dataLength % _format.dwordsPerVertex)
throw new Error("Invalid data length.");
for (var i : int = 0; i < dataLength; i++)
_data.push(data[i]);
invalidate();
}
public function disposeLocalData() : void
{
if (length != ressource.numVertices)
throw new Error("Unable to dispose local data: "
+ "some vertices have not been uploaded.");
_data = null;
_dynamic = false;
}
minko_stream function invalidate() : void
{
_length = _data.length / _format.dwordsPerVertex;
++_version;
}
public static function fromPositionsAndUVs(positions : Vector.<Number>,
uvs : Vector.<Number> = null,
dynamic : Boolean = false) : VertexStream
{
var numVertices : int = positions.length / 3;
var stride : int = uvs ? 5 : 3;
var data : Vector.<Number> = new Vector.<Number>(numVertices * stride, true);
for (var i : int = 0; i < numVertices; ++i)
{
var offset : int = i * stride;
data[offset] = positions[int(i * 3)];
data[int(offset + 1)] = positions[int(i * 3 + 1)];
data[int(offset + 2)] = positions[int(i * 3 + 2)];
if (uvs)
{
data[int(offset + 3)] = uvs[int(i * 2)];
data[int(offset + 4)] = uvs[int(i * 2 + 1)];
}
}
return new VertexStream(data,
uvs ? VertexFormat.XYZ_UV : VertexFormat.XYZ,
dynamic);
}
public static function fromByteArray(data : ByteArray,
count : int,
format : VertexFormat,
dynamic : Boolean = false,
reader : Function = null) : VertexStream
{
var numFormats : int = format.components.length;
var nativeFormats : Vector.<int> = new Vector.<int>(numFormats, true);
var length : int = 0;
var tmp : Vector.<Number> = null;
var stream : VertexStream = new VertexStream(null, format, dynamic);
for (var k : int = 0; k < numFormats; k++)
nativeFormats[k] = format.components[k].nativeFormat;
if (reader == null)
reader = data.readFloat;
tmp = new Vector.<Number>(format.dwordsPerVertex * count, true);
for (var j : int = 0; j < count; ++j)
{
for (var i : int = 0; i < numFormats; ++i)
{
switch (nativeFormats[i])
{
case VertexComponentType.FLOAT_4 :
tmp[int(length++)] = reader();
case VertexComponentType.FLOAT_3 :
tmp[int(length++)] = reader();
case VertexComponentType.FLOAT_2 :
tmp[int(length++)] = reader();
case VertexComponentType.FLOAT_1 :
tmp[int(length++)] = reader();
break ;
}
}
}
stream._data = tmp;
stream.invalidate();
return stream;
}
}
}
|
Add function reader in function fromByteArray to VertexStream
|
Add function reader in function fromByteArray to VertexStream
M Argument reader change the data type read when the function is going over the byteArray
|
ActionScript
|
mit
|
aerys/minko-as3
|
130f334d80980192adf5fbd48b0b41d5bfd3a7f5
|
src/aerys/minko/render/geometry/primitive/TorusGeometry.as
|
src/aerys/minko/render/geometry/primitive/TorusGeometry.as
|
package aerys.minko.render.geometry.primitive
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.IndexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.geometry.stream.format.VertexFormat;
import aerys.minko.type.math.Vector4;
public class TorusGeometry extends Geometry
{
private static const EPSILON : Number = 0.00001;
private static const DTOR : Number = 0.01745329252;
private var _radius : Number;
private var _tube : Number;
private var _segmentsR : uint;
private var _segmentsT : uint;
private var _arc : Number;
public function TorusGeometry(radius : Number = .375,
tube : Number = .125,
segmentsR : uint = 14,
segmentsT : uint = 13,
arc : Number = Math.PI * 2.,
withUVs : Boolean = true,
withNormals : Boolean = true,
vertexStreamUsage : uint = StreamUsage.STATIC,
indexStreamUsage : uint = StreamUsage.STATIC)
{
_radius = radius;
_tube = tube;
_segmentsR = segmentsR;
_segmentsT = segmentsT;
_arc = arc;
super(
new <IVertexStream>[buildVertexStream(vertexStreamUsage, withUVs, withNormals)],
buildIndexStream(indexStreamUsage)
);
}
private function buildVertexStream(usage : uint, withUVs : Boolean, withNormals : Boolean) : VertexStream
{
var vertexData : Vector.<Number> = new <Number>[];
for (var j : uint = 0; j <= _segmentsR; ++j)
{
for (var i : uint = 0; i <= _segmentsT; ++i)
{
var u : Number = i / _segmentsT * _arc;
var v : Number = j / _segmentsR * _arc;
var cosU : Number = Math.cos(u);
var sinU : Number = Math.sin(u);
var cosV : Number = Math.cos(v);
var x : Number = (_radius + _tube * cosV) * cosU;
var y : Number = (_radius + _tube * cosV) * sinU;
var z : Number = _tube * Math.sin(v);
vertexData.push(x, y, z);
if (withUVs)
vertexData.push(i / _segmentsT, 1 - j / _segmentsR);
if (withNormals)
{
var normalX : Number = x - _radius * cosU;
var normalY : Number = y - _radius * sinU;
var normalZ : Number = z;
var mag : Number = normalX * normalX + normalY * normalY
+ normalZ * normalZ;
normalX /= mag;
normalY /= mag;
normalZ /= mag;
vertexData.push(normalX, normalY, normalZ);
}
}
}
var format : VertexFormat = new VertexFormat(VertexComponent.XYZ);
if (withUVs)
format.addComponent(VertexComponent.UV);
if (withNormals)
format.addComponent(VertexComponent.NORMAL);
return new VertexStream(usage, format, vertexData);
}
private function buildIndexStream(usage : uint) : IndexStream
{
var indices : Vector.<uint> = new <uint>[];
for (var j : uint = 1; j <= _segmentsR; ++j)
{
for (var i : uint = 1; i <= _segmentsT; ++i)
{
var a : uint = (_segmentsT + 1) * j + i - 1;
var b : uint = (_segmentsT + 1) * (j - 1) + i - 1;
var c : uint = (_segmentsT + 1) * (j - 1) + i;
var d : uint = (_segmentsT + 1) * j + i;
indices.push(a, c, b, a, d, c);
}
}
return new IndexStream(usage, indices);
}
}
}
|
package aerys.minko.render.geometry.primitive
{
import aerys.minko.render.geometry.Geometry;
import aerys.minko.render.geometry.stream.IVertexStream;
import aerys.minko.render.geometry.stream.IndexStream;
import aerys.minko.render.geometry.stream.StreamUsage;
import aerys.minko.render.geometry.stream.VertexStream;
import aerys.minko.render.geometry.stream.format.VertexComponent;
import aerys.minko.render.geometry.stream.format.VertexFormat;
public class TorusGeometry extends Geometry
{
private static const EPSILON : Number = 0.00001;
private static const DTOR : Number = 0.01745329252;
private var _radius : Number;
private var _tube : Number;
private var _segmentsR : uint;
private var _segmentsT : uint;
private var _arc : Number;
public function TorusGeometry(radius : Number = .375,
tube : Number = .125,
segmentsR : uint = 14,
segmentsT : uint = 13,
arc : Number = Math.PI * 2.,
withUVs : Boolean = true,
withNormals : Boolean = true,
vertexStreamUsage : uint = StreamUsage.STATIC,
indexStreamUsage : uint = StreamUsage.STATIC)
{
_radius = radius;
_tube = tube;
_segmentsR = segmentsR;
_segmentsT = segmentsT;
_arc = arc;
super(
new <IVertexStream>[buildVertexStream(vertexStreamUsage, withUVs, withNormals)],
buildIndexStream(indexStreamUsage)
);
}
private function buildVertexStream(usage : uint, withUVs : Boolean, withNormals : Boolean) : VertexStream
{
var vertexData : Vector.<Number> = new <Number>[];
for (var j : uint = 0; j <= _segmentsR; ++j)
{
for (var i : uint = 0; i <= _segmentsT; ++i)
{
var u : Number = i / _segmentsT * _arc;
var v : Number = j / _segmentsR * _arc;
var cosU : Number = Math.cos(u);
var sinU : Number = Math.sin(u);
var cosV : Number = Math.cos(v);
var x : Number = (_radius + _tube * cosV) * cosU;
var y : Number = (_radius + _tube * cosV) * sinU;
var z : Number = _tube * Math.sin(v);
vertexData.push(x, y, z);
if (withUVs)
vertexData.push(i / _segmentsT, 1 - j / _segmentsR);
if (withNormals)
{
var normalX : Number = x - _radius * cosU;
var normalY : Number = y - _radius * sinU;
var normalZ : Number = z;
var mag : Number = normalX * normalX + normalY * normalY
+ normalZ * normalZ;
normalX /= mag;
normalY /= mag;
normalZ /= mag;
vertexData.push(normalX, normalY, normalZ);
}
}
}
var format : VertexFormat = new VertexFormat(VertexComponent.XYZ);
if (withUVs)
format.addComponent(VertexComponent.UV);
if (withNormals)
format.addComponent(VertexComponent.NORMAL);
return new VertexStream(usage, format, vertexData);
}
private function buildIndexStream(usage : uint) : IndexStream
{
var indices : Vector.<uint> = new <uint>[];
for (var j : uint = 1; j <= _segmentsR; ++j)
{
for (var i : uint = 1; i <= _segmentsT; ++i)
{
var a : uint = (_segmentsT + 1) * j + i - 1;
var b : uint = (_segmentsT + 1) * (j - 1) + i - 1;
var c : uint = (_segmentsT + 1) * (j - 1) + i;
var d : uint = (_segmentsT + 1) * j + i;
indices.push(a, c, b, a, d, c);
}
}
return new IndexStream(usage, indices);
}
}
}
|
remove useless imports in TorusGeometry
|
remove useless imports in TorusGeometry
|
ActionScript
|
mit
|
aerys/minko-as3
|
2fc60fad88c44021565468e55b5807276f71cf87
|
src/as/com/threerings/ezgame/client/EZGameConfigurator.as
|
src/as/com/threerings/ezgame/client/EZGameConfigurator.as
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.ezgame.client {
import mx.core.UIComponent;
import mx.controls.CheckBox;
import mx.controls.ComboBox;
import mx.controls.HSlider;
import mx.controls.Label;
import com.threerings.util.StringUtil;
import com.threerings.parlor.game.client.FlexGameConfigurator;
import com.threerings.ezgame.data.EZGameConfig;
/**
* Adds custom configuration of options specified in XML.
*/
public class EZGameConfigurator extends FlexGameConfigurator
{
/**
* Set a String of configData, which is hopefully XML formatted with
* some game configuration options.
*/
public function setXMLConfig (configData :String) :void
{
var log :Log = Log.getLog(this);
var config :XML = XML(configData);
for each (var param :XML in config..params.children()) {
if (StringUtil.isBlank(param.@ident)) {
log.warning("Bad configuration option: no 'ident' in " +
param + ", ignoring.");
continue;
}
switch (param.localName().toLowerCase()) {
case "range":
addRangeOption(param, log);
break;
case "choice":
addChoiceOption(param, log);
break;
case "toggle":
addToggleOption(param, log);
break;
default:
log.warning("Unknown XML configuration option: " + param +
", ignoring.");
break;
}
}
}
/**
* Add a control that came from parsing our custom option XML.
*/
protected function addXMLControl (ident :String, control :UIComponent) :void
{
var name :String = ident.replace("_", " ");
var lbl :Label = new Label();
lbl.text = name + ":";
addControl(lbl, control);
_customConfigs.push(ident, control);
}
/**
* Adds a 'range' option specified in XML
*/
protected function addRangeOption (spec :XML, log :Log) :void
{
var min :Number = Number(spec.@minimum);
var max :Number = Number(spec.@maximum);
var start :Number = Number(spec.@start);
if (isNaN(min) || isNaN(max) || isNaN(start)) {
log.warning("Unable to parse range specification. " +
"Required numeric values: minimum, maximum, start " +
"[xml=" + spec + "].");
return;
}
var slider :HSlider = new HSlider();
slider.minimum = min;
slider.maximum = max;
slider.value = start;
slider.liveDragging = true;
slider.snapInterval = 1;
addXMLControl(spec.@ident, slider);
}
/**
* Adds a 'choice' option specified in XML
*/
protected function addChoiceOption (spec :XML, log :Log) :void
{
if ([email protected] == 0 || [email protected] == 0) {
log.warning("Unable to parse choice specification. " +
"Required 'choices' or 'start' is missing. " +
"[xml=" + spec + "].");
return;
}
var choiceString :String = String(spec.@choices);
var start :String = String(spec.@start);
var choices :Array = choiceString.split(",");
var startDex :int = choices.indexOf(start);
if (startDex == -1) {
log.warning("Choice start value does not appear in list of choices "+
"[xml=" + spec + "].");
return;
}
var box :ComboBox = new ComboBox();
box.dataProvider = choices;
box.selectedIndex = startDex;
addXMLControl(spec.@ident, box);
}
/**
* Adds a 'toggle' option specified in XML
*/
protected function addToggleOption (spec :XML, log :Log) :void
{
if ([email protected] == 0) {
log.warning("Unable to parse toggle specification. " +
"Required 'start' is missing. " +
"[xml=" + spec + "].");
return;
}
var startStr :String = String(spec.@start).toLowerCase();
var box :CheckBox = new CheckBox();
box.selected = ("true" == startStr);
addXMLControl(spec.@ident, box);
}
override protected function flushGameConfig () :void
{
super.flushGameConfig();
// if there were any custom XML configs, flush those as well.
if (_customConfigs.length > 0) {
var options :Object = {};
for (var ii :int = 0; ii < _customConfigs.length; ii += 2) {
var ident :String = String(_customConfigs[ii]);
var control :UIComponent = (_customConfigs[ii + 1] as UIComponent);
if (control is HSlider) {
options[ident] = (control as HSlider).value;
} else if (control is CheckBox) {
options[ident] = (control as CheckBox).selected;
} else if (control is ComboBox) {
options[ident] = (control as ComboBox).value;
} else {
Log.getLog(this).warning("Unknow custom config type " + control);
}
}
(_config as EZGameConfig).customConfig = options;
}
}
/** Contains pairs of identString, control, identString, control.. */
protected var _customConfigs :Array = [];
}
}
|
//
// $Id$
//
// Vilya library - tools for developing networked games
// Copyright (C) 2002-2007 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/vilya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.ezgame.client {
import mx.core.UIComponent;
import mx.controls.CheckBox;
import mx.controls.ComboBox;
import mx.controls.HSlider;
import mx.controls.Label;
import com.threerings.util.StringUtil;
import com.threerings.flex.LabeledSlider;
import com.threerings.parlor.game.client.FlexGameConfigurator;
import com.threerings.ezgame.data.EZGameConfig;
/**
* Adds custom configuration of options specified in XML.
*/
public class EZGameConfigurator extends FlexGameConfigurator
{
/**
* Set a String of configData, which is hopefully XML formatted with
* some game configuration options.
*/
public function setXMLConfig (configData :String) :void
{
var log :Log = Log.getLog(this);
var config :XML = XML(configData);
for each (var param :XML in config..params.children()) {
if (StringUtil.isBlank(param.@ident)) {
log.warning("Bad configuration option: no 'ident' in " +
param + ", ignoring.");
continue;
}
switch (param.localName().toLowerCase()) {
case "range":
addRangeOption(param, log);
break;
case "choice":
addChoiceOption(param, log);
break;
case "toggle":
addToggleOption(param, log);
break;
default:
log.warning("Unknown XML configuration option: " + param +
", ignoring.");
break;
}
}
}
/**
* Add a control that came from parsing our custom option XML.
*/
protected function addXMLControl (ident :String, control :UIComponent) :void
{
var name :String = ident.replace("_", " ");
var lbl :Label = new Label();
lbl.text = name + ":";
addControl(lbl, control);
_customConfigs.push(ident, control);
}
/**
* Adds a 'range' option specified in XML
*/
protected function addRangeOption (spec :XML, log :Log) :void
{
var min :Number = Number(spec.@minimum);
var max :Number = Number(spec.@maximum);
var start :Number = Number(spec.@start);
if (isNaN(min) || isNaN(max) || isNaN(start)) {
log.warning("Unable to parse range specification. " +
"Required numeric values: minimum, maximum, start " +
"[xml=" + spec + "].");
return;
}
var slider :HSlider = new HSlider();
slider.minimum = min;
slider.maximum = max;
slider.value = start;
slider.liveDragging = true;
slider.snapInterval = 1;
addXMLControl(spec.@ident, new LabeledSlider(slider));
}
/**
* Adds a 'choice' option specified in XML
*/
protected function addChoiceOption (spec :XML, log :Log) :void
{
if ([email protected] == 0 || [email protected] == 0) {
log.warning("Unable to parse choice specification. " +
"Required 'choices' or 'start' is missing. " +
"[xml=" + spec + "].");
return;
}
var choiceString :String = String(spec.@choices);
var start :String = String(spec.@start);
var choices :Array = choiceString.split(",");
var startDex :int = choices.indexOf(start);
if (startDex == -1) {
log.warning("Choice start value does not appear in list of choices "+
"[xml=" + spec + "].");
return;
}
var box :ComboBox = new ComboBox();
box.dataProvider = choices;
box.selectedIndex = startDex;
addXMLControl(spec.@ident, box);
}
/**
* Adds a 'toggle' option specified in XML
*/
protected function addToggleOption (spec :XML, log :Log) :void
{
if ([email protected] == 0) {
log.warning("Unable to parse toggle specification. " +
"Required 'start' is missing. " +
"[xml=" + spec + "].");
return;
}
var startStr :String = String(spec.@start).toLowerCase();
var box :CheckBox = new CheckBox();
box.selected = ("true" == startStr);
addXMLControl(spec.@ident, box);
}
override protected function flushGameConfig () :void
{
super.flushGameConfig();
// if there were any custom XML configs, flush those as well.
if (_customConfigs.length > 0) {
var options :Object = {};
for (var ii :int = 0; ii < _customConfigs.length; ii += 2) {
var ident :String = String(_customConfigs[ii]);
var control :UIComponent = (_customConfigs[ii + 1] as UIComponent);
if (control is LabeledSlider) {
options[ident] = (control as LabeledSlider).slider.value;
} else if (control is CheckBox) {
options[ident] = (control as CheckBox).selected;
} else if (control is ComboBox) {
options[ident] = (control as ComboBox).value;
} else {
Log.getLog(this).warning("Unknow custom config type " + control);
}
}
(_config as EZGameConfig).customConfig = options;
}
}
/** Contains pairs of identString, control, identString, control.. */
protected var _customConfigs :Array = [];
}
}
|
Use a LabeledSlider for any range properties.
|
Use a LabeledSlider for any range properties.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@242 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
e7221c26ac02d7357b4f9d6968b74be7ba3090d4
|
src/aerys/minko/scene/node/light/PointLight.as
|
src/aerys/minko/scene/node/light/PointLight.as
|
package aerys.minko.scene.node.light
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.material.phong.PhongProperties;
import aerys.minko.scene.controller.light.PointLightController;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.type.math.Vector4;
use namespace minko_scene;
/**
*
* @author Romain Gilliotte
* @author Jean-Marc Le Roux
*
*/
public class PointLight extends AbstractLight
{
public static const LIGHT_TYPE : uint = 2;
private static const TMP_VECTOR : Vector4 = new Vector4();
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(v : Number) : void
{
lightData.setLightProperty('shininess', v);
}
public function get attenuationDistance() : Number
{
return lightData.getLightProperty('attenuationDistance') as Number;
}
public function set attenuationDistance(v : Number) : void
{
lightData.setLightProperty('attenuationDistance', v);
if (lightData.getLightProperty('attenuationEnabled') != (v != 0))
lightData.setLightProperty('attenuationEnabled', v != 0);
}
public function get attenuationPolynomial() : Vector4
{
return lightData.getLightProperty('attenuationPolynomial');
}
public function set attenuationPolynomial(value : Vector4) : void
{
lightData.setLightProperty('attenuationPolynomial', value);
var notEqual : Boolean = value.equals(Vector4.ZERO);
if (lightData.getLightProperty('attenuationEnabled') != notEqual)
lightData.setLightProperty('attenuationEnabled', notEqual);
}
public function get shadowMapSize() : uint
{
return lightData.getLightProperty('shadowMapSize');
}
public function set shadowMapSize(v : uint) : void
{
lightData.setLightProperty('shadowMapSize', v);
}
public function get shadowZNear() : Number
{
return lightData.getLightProperty('shadowZNear');
}
public function set shadowZNear(v : Number) : void
{
lightData.setLightProperty('shadowZNear', v);
}
public function get shadowZFar() : Number
{
return lightData.getLightProperty('shadowZFar');
}
public function set shadowZFar(v : Number) : void
{
lightData.setLightProperty('shadowZFar', v);
}
public function get shadowCastingType() : uint
{
return lightData.getProperty('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 PointLight(color : uint = 0xFFFFFFFF,
diffuse : Number = .6,
specular : Number = .8,
shininess : Number = 64,
attenuationDistance : Number = 0,
emissionMask : uint = 0x1,
shadowCastingType : uint = 0,
shadowMapSize : uint = 512,
shadowZNear : Number = 0.1,
shadowZFar : Number = 1000.,
shadowBias : Number = 1. / 256. / 256.)
{
super(
new PointLightController(),
LIGHT_TYPE,
color,
emissionMask
);
this.diffuse = diffuse;
this.specular = specular;
this.shininess = shininess;
this.attenuationDistance = attenuationDistance;
this.shadowCastingType = shadowCastingType;
this.shadowMapSize = shadowMapSize;
this.shadowZNear = shadowZNear;
this.shadowZFar = shadowZFar;
this.shadowBias = shadowBias;
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var light : PointLight = new PointLight(
color,
diffuse,
specular,
shininess,
attenuationDistance,
emissionMask,
shadowCastingType,
shadowMapSize,
shadowZFar,
shadowZNear,
shadowBias
);
light.name = this.name;
light.userData.setProperties(userData);
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.scene.controller.light.PointLightController;
import aerys.minko.scene.node.AbstractSceneNode;
import aerys.minko.type.math.Vector4;
use namespace minko_scene;
/**
*
* @author Romain Gilliotte
* @author Jean-Marc Le Roux
*
*/
public class PointLight extends AbstractLight
{
public static const LIGHT_TYPE : uint = 2;
private static const TMP_VECTOR : Vector4 = new Vector4();
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(v : Number) : void
{
lightData.setLightProperty('shininess', v);
}
public function get attenuationDistance() : Number
{
return lightData.getLightProperty('attenuationDistance') as Number;
}
public function set attenuationDistance(v : Number) : void
{
lightData.setLightProperty('attenuationDistance', v);
if (lightData.getLightProperty('attenuationEnabled') != (v != 0))
lightData.setLightProperty('attenuationEnabled', v != 0);
}
public function get attenuationPolynomial() : Vector4
{
return lightData.getLightProperty('attenuationPolynomial');
}
public function set attenuationPolynomial(value : Vector4) : void
{
lightData.setLightProperty('attenuationPolynomial', value);
var notEqual : Boolean = value.equals(Vector4.ZERO);
if (lightData.getLightProperty('attenuationEnabled') != notEqual)
lightData.setLightProperty('attenuationEnabled', notEqual);
}
public function get shadowMapSize() : uint
{
return lightData.getLightProperty('shadowMapSize');
}
public function set shadowMapSize(v : uint) : void
{
lightData.setLightProperty('shadowMapSize', v);
}
public function get shadowZNear() : Number
{
return lightData.getLightProperty('shadowZNear');
}
public function set shadowZNear(v : Number) : void
{
lightData.setLightProperty('shadowZNear', v);
}
public function get shadowZFar() : Number
{
return lightData.getLightProperty('shadowZFar');
}
public function set shadowZFar(v : Number) : void
{
lightData.setLightProperty('shadowZFar', 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 PointLight(color : uint = 0xFFFFFFFF,
diffuse : Number = .6,
specular : Number = .8,
shininess : Number = 64,
attenuationDistance : Number = 0,
emissionMask : uint = 0x1,
shadowCastingType : uint = 0,
shadowMapSize : uint = 512,
shadowZNear : Number = 0.1,
shadowZFar : Number = 1000.,
shadowBias : Number = 1. / 256. / 256.)
{
super(
new PointLightController(),
LIGHT_TYPE,
color,
emissionMask
);
this.diffuse = diffuse;
this.specular = specular;
this.shininess = shininess;
this.attenuationDistance = attenuationDistance;
this.shadowCastingType = shadowCastingType;
this.shadowMapSize = shadowMapSize;
this.shadowZNear = shadowZNear;
this.shadowZFar = shadowZFar;
this.shadowBias = shadowBias;
}
override minko_scene function cloneNode() : AbstractSceneNode
{
var light : PointLight = new PointLight(
color,
diffuse,
specular,
shininess,
attenuationDistance,
emissionMask,
shadowCastingType,
shadowMapSize,
shadowZFar,
shadowZNear,
shadowBias
);
light.name = this.name;
light.userData.setProperties(userData);
light.transform.copyFrom(this.transform);
return light;
}
}
}
|
Fix shadowmappingType accessor
|
Fix shadowmappingType accessor
|
ActionScript
|
mit
|
aerys/minko-as3
|
d6f85fa4bd7287527616c8a2561233b8cf1d88d4
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
flexEditor/src/org/arisgames/editor/util/AppConstants.as
|
package org.arisgames.editor.util
{
public class AppConstants
{
//public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://davembp.local/server/services/aris/uploadhandler.php"; //davembp
// public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server/services/aris/uploadhandler.php"; //dev
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://www.arisgames.org/stagingserver1/services/aris/uploadHandler.php"; //staging
// public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp
// public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev
public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging
// Dynamic Events
public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged";
public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette";
public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded";
public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch";
public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected";
public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion";
public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem";
public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor";
public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker";
public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor";
public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor";
public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap";
public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange";
public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap";
public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap";
public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor";
public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor";
public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor";
public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR";
public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR";
public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS";
// Placemark Content
public static const CONTENTTYPE_PAGE:String = "Plaque";
public static const CONTENTTYPE_CHARACTER:String = "Character";
public static const CONTENTTYPE_ITEM:String = "Item";
public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group";
public static const CONTENTTYPE_PAGE_VAL:Number = 0;
public static const CONTENTTYPE_CHARACTER_VAL:Number = 1;
public static const CONTENTTYPE_ITEM_VAL:Number = 2;
public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3;
public static const CONTENTTYPE_PAGE_DATABASE:String = "Node";
public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc";
public static const CONTENTTYPE_ITEM_DATABASE:String = "Item";
public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30;
// Label Constants
public static const BUTTON_LOGIN:String = "Login!";
public static const BUTTON_REGISTER:String = "Register!";
public static const RADIO_FORGOTPASSWORD:String = "Forgot Password";
public static const RADIO_FORGOTUSERNAME:String = "Forgot Username";
// Media Types
public static const MEDIATYPE:String = "Media Types";
public static const MEDIATYPE_IMAGE:String = "Image";
public static const MEDIATYPE_AUDIO:String = "Audio";
public static const MEDIATYPE_VIDEO:String = "Video";
public static const MEDIATYPE_ICON:String = "Icon";
public static const MEDIATYPE_UPLOADNEW:String = "Upload New";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item";
// Requirement Types
public static const REQUIREMENTTYPE_LOCATION:String = "Location";
public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay";
public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete";
public static const REQUIREMENTTYPE_NODE:String = "Node";
// Requirement Options
public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM";
public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least qty of an Item";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than qty of an Item";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST:String = "Player Has Completed Quest";
public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND";
public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All";
public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR";
public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one";
// Defaults
public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1;
public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2;
public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3;
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
package org.arisgames.editor.util
{
public class AppConstants
{
//public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://davembp.local/server/services/aris/uploadhandler.php"; //davembp
// public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://atsosxdev.doit.wisc.edu/aris/server/services/aris/uploadhandler.php"; //dev
public static const APPLICATION_ENVIRONMENT_UPLOAD_SERVER_URL:String = "http://www.arisgames.org/stagingserver1/services/aris/uploadHandler.php"; //staging
// public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAArdp0t4v0pcA_JogLZhjrjBTf4EykMftsP7dwAfDsLsFl_zB7rBTq5-3Hy0k3tU1tgyomozB1YmIfNg"; //davembp
// public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBQsvlSBtAWfm4N2P3iTGfWOp-UrmRRTU3pFPQwMJB92SZ3plLjvRpMIIw"; //dev
public static const APPLICATION_ENVIRONMENT_GOOGLEMAP_KEY:String = "ABQIAAAA-Z69V9McvCh02XYNV5UHBBRloMOfjiI7F4SM41AgXh_4cb6l9xTHRyPNO3mgDcJkTIE742EL8ZoQ_Q"; //staging
// Dynamic Events
public static const APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED:String = "ApplicationDynamicEventCurrentStateChanged";
public static const APPLICATIONDYNAMICEVENT_REDRAWOBJECTPALETTE:String = "ApplicationDynamicEventRedrawObjectPalette";
public static const APPLICATIONDYNAMICEVENT_GAMEPLACEMARKSLOADED:String = "ApplicationDynamicEventGamePlacemarksLoaded";
public static const DYNAMICEVENT_GEOSEARCH:String = "DynamicEventGeoSearch";
public static const DYNAMICEVENT_PLACEMARKSELECTED:String = "DynamicEventPlaceMarkSelected";
public static const DYNAMICEVENT_PLACEMARKREQUESTSDELETION:String = "DynamicEventPlaceMarkRequestsDeletion";
public static const DYNAMICEVENT_EDITOBJECTPALETTEITEM:String = "EditObjectPaletteItem";
public static const DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR:String = "CloseObjectPaletteItemEditor";
public static const DYNAMICEVENT_CLOSEMEDIAPICKER:String = "CloseMediaPicker";
public static const DYNAMICEVENT_CLOSEMEDIAUPLOADER:String = "CloseMediaUploader";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITOR:String = "CloseRequirementsEditor";
public static const DYNAMICEVENT_REFRESHDATAINREQUIREMENTSEDITOR:String = "RefreshDataInRequirementsEditor";
public static const DYNAMICEVENT_OPENREQUIREMENTSEDITORMAP:String = "OpenRequirementsEditorMap";
public static const DYNAMICEVENT_CLOSEREQUIREMENTSEDITORMAP:String = "CloseRequirementsEditorMap";
public static const DYNAMICEVENT_SAVEREQUIREMENTDUETOMAPDATACHANGE:String = "SaveRequirementDueToMapDataChange";
public static const DYNAMICEVENT_OPENQUESTSMAP:String = "OpenQuestsMap";
public static const DYNAMICEVENT_CLOSEQUESTSMAP:String = "CloseQuestsMap";
public static const DYNAMICEVENT_REFRESHDATAINQUESTSEDITOR:String = "RefreshDataInQuestsEditor";
public static const DYNAMICEVENT_OPENQUESTSEDITOR:String = "OpenQuestsEditor";
public static const DYNAMICEVENT_CLOSEQUESTSEDITOR:String = "CloseQuestsEditor";
public static const DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR:String = "DYNAMICEVENT_REFRESHDATAINPLAYERSTATECHANGESEDITOR";
public static const DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR:String = "DYNAMICEVENT_CLOSEPLAYERSTATECHANGEEDITOR";
public static const DYNAMICEVENT_REFRESHDATAINCONVERSATIONS:String = "DYNAMICEVENT_DYNAMICEVENT_REFRESHDATAINCONVERSATIONS";
// Placemark Content
public static const CONTENTTYPE_PAGE:String = "Plaque";
public static const CONTENTTYPE_CHARACTER:String = "Character";
public static const CONTENTTYPE_ITEM:String = "Item";
public static const CONTENTTYPE_QRCODEGROUP:String = "QR Code Group";
public static const CONTENTTYPE_PAGE_VAL:Number = 0;
public static const CONTENTTYPE_CHARACTER_VAL:Number = 1;
public static const CONTENTTYPE_ITEM_VAL:Number = 2;
public static const CONTENTTYPE_QRCODEGROUP_VAL:Number = 3;
public static const CONTENTTYPE_PAGE_DATABASE:String = "Node";
public static const CONTENTTYPE_CHARACTER_DATABASE:String = "Npc";
public static const CONTENTTYPE_ITEM_DATABASE:String = "Item";
public static const PLACEMARK_DEFAULT_ERROR_RANGE:Number = 30;
// Label Constants
public static const BUTTON_LOGIN:String = "Login!";
public static const BUTTON_REGISTER:String = "Register!";
public static const RADIO_FORGOTPASSWORD:String = "Forgot Password";
public static const RADIO_FORGOTUSERNAME:String = "Forgot Username";
// Media Types
public static const MEDIATYPE:String = "Media Types";
public static const MEDIATYPE_IMAGE:String = "Image";
public static const MEDIATYPE_AUDIO:String = "Audio";
public static const MEDIATYPE_VIDEO:String = "Video";
public static const MEDIATYPE_ICON:String = "Icon";
public static const MEDIATYPE_UPLOADNEW:String = "Upload New";
//Player State Changes
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_ITEM:String = "VIEW_ITEM";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NODE:String = "VIEW_NODE";
public static const PLAYERSTATECHANGE_EVENTTYPE_VIEW_NPC:String = "VIEW_NPC";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM:String = "GIVE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_GIVEITEM_HUMAN:String = "Give Item";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM:String = "TAKE_ITEM";
public static const PLAYERSTATECHANGE_ACTION_TAKEITEM_HUMAN:String = "Take Item";
// Requirement Types
public static const REQUIREMENTTYPE_LOCATION:String = "Location";
public static const REQUIREMENTTYPE_QUESTDISPLAY:String = "QuestDisplay";
public static const REQUIREMENTTYPE_QUESTCOMPLETE:String = "QuestComplete";
public static const REQUIREMENTTYPE_NODE:String = "Node";
// Requirement Options
public static const REQUIREMENT_PLAYER_HAS_ITEM_DATABASE:String = "PLAYER_HAS_ITEM";
public static const REQUIREMENT_PLAYER_HAS_ITEM_HUMAN:String = "Player Has At Least Qty of an Item";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_DATABASE:String = "PLAYER_DOES_NOT_HAVE_ITEM";
public static const REQUIREMENT_PLAYER_DOES_NOT_HAVE_ITEM_HUMAN:String = "Player Has Less Than Qty of an Item";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_DATABASE:String = "PLAYER_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_VIEWED_ITEM_HUMAN:String = "Player Viewed Item";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_ITEM";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_ITEM_HUMAN:String = "Player Never Viewed Item";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_DATABASE:String = "PLAYER_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_VIEWED_NODE_HUMAN:String = "Player Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NODE";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NODE_HUMAN:String = "Player Never Viewed Plaque/Script";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_DATABASE:String = "PLAYER_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_VIEWED_NPC_HUMAN:String = "Player Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_DATABASE:String = "PLAYER_HAS_NOT_VIEWED_NPC";
public static const REQUIREMENT_PLAYER_HAS_NOT_VIEWED_NPC_HUMAN:String = "Player Never Greeted By Character";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_DATABASE:String = "PLAYER_HAS_UPLOADED_MEDIA_ITEM";
public static const REQUIREMENT_PLAYER_HAS_UPLOADED_MEDIA_ITEM_HUMAN:String = "Player Has Uploaded Media Item";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST_DATABASE:String = "PLAYER_HAS_COMPLETED_QUEST";
public static const REQUIREMENT_PLAYER_HAS_COMPLETED_QUEST:String = "Player Has Completed Quest";
public static const REQUIREMENT_BOOLEAN_AND_DATABASE:String = "AND";
public static const REQUIREMENT_BOOLEAN_AND_HUMAN:String = "All";
public static const REQUIREMENT_BOOLEAN_OR_DATABASE:String = "OR";
public static const REQUIREMENT_BOOLEAN_OR_HUMAN:String = "Only this one";
// Defaults
public static const DEFAULT_ICON_MEDIA_ID_NPC:Number = 1;
public static const DEFAULT_ICON_MEDIA_ID_ITEM:Number = 2;
public static const DEFAULT_ICON_MEDIA_ID_PLAQUE:Number = 3;
/**
* Constructor
*/
public function AppConstants()
{
super();
}
}
}
|
rename requirement to plaque/script
|
rename requirement to plaque/script
|
ActionScript
|
mit
|
ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames
|
6e670f1ccf59e05f96271054262464b95dac5f6e
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/Util.as
|
snowplow-as3-tracker/src/com/snowplowanalytics/snowplow/tracker/Util.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
{
import com.snowplowanalytics.snowplow.tracker.util.UUID;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.external.ExternalInterface;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
import mx.utils.Base64Encoder;
public class Util
{
public static function isNullOrEmpty(str:*):Boolean
{
return str == null || (str is String && (str as String).length == 0);
}
public static function padZeroes (value:*, places:int = 2):String
{
var str:String = value.toString();
var zeroes:int = places - str.length;
if (zeroes > 0)
{
for (var i:int=0;i<zeroes;i++)
{
str = "0" + str;
}
}
return str;
}
private static function callCallback (dataFormat:String, loader:URLLoader, callback:Function):void
{
var result:*;
switch (dataFormat)
{
case URLLoaderDataFormat.TEXT:
case URLLoaderDataFormat.VARIABLES:
result = loader.data;
break;
case URLLoaderDataFormat.BINARY:
default:
result = ByteArray(loader.data);
break;
}
callback(result);
}
public static function getResponse (
url:String,
callback:Function,
errorCallback:Function,
method:String = "get",
postData:String = null,
dataFormat:String = "text"
):void
{
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest(url);
request.method = method;
if (postData != null && method == URLRequestMethod.POST)
{
request.data = postData;
request.contentType = "application/json; charset=utf-8";
}
loader.dataFormat = dataFormat;
loader.addEventListener
(
Event.COMPLETE,
function (event:Event):void
{
if (callback != null)
{
callCallback(dataFormat, loader, callback);
}
}
);
loader.addEventListener
(
IOErrorEvent.IO_ERROR,
function (event:IOErrorEvent):void
{
if (event.type == "201")
{
if (callback != null)
{
callCallback(dataFormat, loader, callback);
}
}
else
{
if (errorCallback != null)
{
errorCallback(event);
}
}
}
);
loader.addEventListener
(
SecurityErrorEvent.SECURITY_ERROR,
function (event:SecurityErrorEvent):void
{
if (errorCallback != null)
{
errorCallback(event);
}
}
);
loader.load(request);
}
public static function getEventId():String
{
return UUID.generateGuid();
}
public static function getTimestamp():String {
var date:Date = new Date();
return date.time.toString();
}
public static function copyObject (object:Object, returnEmptyObjectIfNull:Boolean = false):Object
{
if (object == null)
{
if (returnEmptyObjectIfNull)
return {}
else
return null;
}
var newObject:Object = {};
for (var key:String in object) {
newObject[key] = object[key];
}
return newObject;
}
/* Addition functions
* Used to add different sources of key=>value pairs to a map.
* Map is then used to build "Associative array for getter function.
* Some use Base64 encoding
*/
public static function base64Encode(str:String):String {
try {
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(str);
return encoder.flush();
} catch (e:Error) {
trace(e.getStackTrace());
}
return null;
}
public static function getTransactionId():int
{
return Math.round(Math.random() * 1000000);
}
public static function clearArray (a:Array):void
{
a.splice(0, a.length);
}
public static function findFirstItemInArray (array:Array, prop:String, val:*):*
{
for each(var item:* in array)
{
if (item[prop] == val)
{
return item;
}
}
return null;
}
/**
* Return value from name-value pair in querystring
*/
private static function fromQuerystring(field:String, url:String):String {
var match:RegExp = new RegExp('^[^#]*[?&]' + field + '=([^&#]*)').exec(url);
if (!match) {
return null;
}
return decodeURIComponent(match[1].replace(/\+/g, ' '));
};
/**
* Extract parameter from URL
*/
private static function getParameter(url:String, name:String):String {
// scheme : // [username [: password] @] hostname [: port] [/ [path] [? query] [# fragment]]
var e:RegExp = new RegExp('^(?:https?|ftp)(?::/*(?:[^?]+))([?][^#]+)');
var matches:* = e.exec(url);
var result:String = fromQuerystring(name, matches[1]);
return result;
}
/**
* Extract hostname from URL
*/
private static function getHostName(url:String):String {
// scheme : // [username [: password] @] hostname [: port] [/ [path] [? query] [# fragment]]
var e:RegExp = new RegExp('^(?:(?:https?|ftp):)/*(?:[^@]+@)?([^:/#]+)');
var matches:* = e.exec(url);
return matches ? matches[1] : url;
};
/**
* Test whether a string is an IP address
*/
private static function isIpAddress(str:String):Boolean {
var IPRegExp:RegExp = new RegExp('^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$');
return IPRegExp.test(str);
}
/**
* If the hostname is an IP address, look for text indicating
* that the page is cached by Yahoo
*/
private static function isYahooCachedPage(hostName:String):Boolean
{
return false;
var initialDivText:String;
var cachedIndicator:String;
if (isIpAddress(hostName)) {
try {
initialDivText = ExternalInterface.call("function getInitialDivText() { return document.body.children[0].children[0].children[0].children[0].children[0].children[0].innerHTML; }");
cachedIndicator = 'You have reached the cached page for';
return initialDivText.slice(0, cachedIndicator.length) === cachedIndicator;
} catch (e:Error) {
return false;
}
} else {
return false;
}
}
/**
* Fix-up domain
*/
public static function fixupDomain(domain:String):String {
var dl:int = domain.length;
// remove trailing '.'
if (domain.charAt(--dl) === '.') {
domain = domain.slice(0, dl);
}
// remove leading '*'
if (domain.slice(0, 2) === '*.') {
domain = domain.slice(1);
}
return domain;
};
/**
* Fix-up URL when page rendered from search engine cache or translated page.
* TODO: it would be nice to generalise this and/or move into the ETL phase.
*/
public static function fixupUrl(hostName:String, href:String, referrer:String):Array {
if (hostName === 'translate.googleusercontent.com') { // Google
if (referrer === '') {
referrer = href;
}
href = getParameter(href, 'u');
hostName = getHostName(href);
} else if (hostName === 'cc.bingj.com' || // Bing
hostName === 'webcache.googleusercontent.com' || // Google
isYahooCachedPage(hostName)) { // Yahoo (via Inktomi 74.6.0.0/16)
try {
href = ExternalInterface.call("function getLinkHref() { return document.links[0].href; }");
} catch (e:Error) {
href = '';
}
hostName = getHostName(href);
}
return [hostName, href, referrer];
};
public static var scriptAccessAllowed:int = -1; //-1 = not set. 0 = false. 1 = true.
public static function isScriptAccessAllowed ():Boolean
{
if (scriptAccessAllowed != -1)
{
return scriptAccessAllowed == 1;
}
if (!ExternalInterface.available)
{
scriptAccessAllowed = 0;
return false;
}
try
{
ExternalInterface.call("function isScriptAccessAllowed(){return true;}");
scriptAccessAllowed = 1;
}
catch (error:Error)
{
if (error is SecurityError)
{
scriptAccessAllowed = 0;
}
}
return scriptAccessAllowed == 1;
}
/**
* AS Implementation of MurmurHash3
*
* @param {string} key ASCII only
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
public static function murmurhash3_32_gc(key:String, seed:Number):Number {
var remainder:Number;
var bytes:Number;
var h1:Number;
var h1b:Number;
var c1:Number;
var c1b:Number;
var c2:Number;
var c2b:Number;
var k1:Number;
var i:Number;
remainder = key.length & 3; // key.length % 4
bytes = key.length - remainder;
h1 = seed;
c1 = 0xcc9e2d51;
c2 = 0x1b873593;
i = 0;
while (i < bytes) {
k1 =
((key.charCodeAt(i) & 0xff)) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;
h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));
}
k1 = 0;
switch (remainder) {
case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
case 1: k1 ^= (key.charCodeAt(i) & 0xff);
k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 13;
h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
h1 ^= h1 >>> 16;
return h1 >>> 0;
}
}
}
|
/*
* 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
{
import com.snowplowanalytics.snowplow.tracker.util.UUID;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.external.ExternalInterface;
import flash.net.URLLoader;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.utils.ByteArray;
import mx.utils.Base64Encoder;
public class Util
{
public static function isNullOrEmpty(str:*):Boolean
{
return str == null || (str is String && (str as String).length == 0);
}
public static function padZeroes (value:*, places:int = 2):String
{
var str:String = value.toString();
var zeroes:int = places - str.length;
if (zeroes > 0)
{
for (var i:int=0;i<zeroes;i++)
{
str = "0" + str;
}
}
return str;
}
private static function callCallback (dataFormat:String, loader:URLLoader, callback:Function):void
{
var result:*;
switch (dataFormat)
{
case URLLoaderDataFormat.TEXT:
case URLLoaderDataFormat.VARIABLES:
result = loader.data;
break;
case URLLoaderDataFormat.BINARY:
default:
result = ByteArray(loader.data);
break;
}
callback(result);
}
public static function getResponse (
url:String,
callback:Function,
errorCallback:Function,
method:String = "get",
postData:String = null,
dataFormat:String = "text"
):void
{
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest(url);
request.method = method;
if (postData != null && method == URLRequestMethod.POST)
{
request.data = postData;
request.contentType = "application/json; charset=utf-8";
}
loader.dataFormat = dataFormat;
loader.addEventListener
(
Event.COMPLETE,
function (event:Event):void
{
if (callback != null)
{
callCallback(dataFormat, loader, callback);
}
}
);
loader.addEventListener
(
IOErrorEvent.IO_ERROR,
function (event:IOErrorEvent):void
{
if (event.type == "201")
{
if (callback != null)
{
callCallback(dataFormat, loader, callback);
}
}
else
{
if (errorCallback != null)
{
errorCallback(event);
}
}
}
);
loader.addEventListener
(
SecurityErrorEvent.SECURITY_ERROR,
function (event:SecurityErrorEvent):void
{
if (errorCallback != null)
{
errorCallback(event);
}
}
);
loader.load(request);
}
public static function getEventId():String
{
return UUID.generateGuid();
}
public static function getTimestamp():String {
var date:Date = new Date();
return date.time.toString();
}
public static function copyObject (object:Object, returnEmptyObjectIfNull:Boolean = false):Object
{
if (object == null)
{
if (returnEmptyObjectIfNull)
return {}
else
return null;
}
var newObject:Object = {};
for (var key:String in object) {
newObject[key] = object[key];
}
return newObject;
}
/* Addition functions
* Used to add different sources of key=>value pairs to a map.
* Map is then used to build "Associative array for getter function.
* Some use Base64 encoding
*/
public static function base64Encode(str:String):String {
try {
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(str);
var base64:String = encoder.flush();
//make base64 url safe.
base64 = base64.replace(/\+/g, "-");
base64 = base64.replace(/\//g, "_");
base64 = base64.replace(/=/g, "");
base64 = base64.replace(/\n/g, "");
base64 = base64.replace(/\r/g, "");
base64 = base64.replace(/\t/g, "");
return base64;
} catch (e:Error) {
trace(e.getStackTrace());
}
return null;
}
public static function getTransactionId():int
{
return Math.round(Math.random() * 1000000);
}
public static function clearArray (a:Array):void
{
a.splice(0, a.length);
}
public static function findFirstItemInArray (array:Array, prop:String, val:*):*
{
for each(var item:* in array)
{
if (item[prop] == val)
{
return item;
}
}
return null;
}
/**
* Return value from name-value pair in querystring
*/
private static function fromQuerystring(field:String, url:String):String {
var match:RegExp = new RegExp('^[^#]*[?&]' + field + '=([^&#]*)').exec(url);
if (!match) {
return null;
}
return decodeURIComponent(match[1].replace(/\+/g, ' '));
};
/**
* Extract parameter from URL
*/
private static function getParameter(url:String, name:String):String {
// scheme : // [username [: password] @] hostname [: port] [/ [path] [? query] [# fragment]]
var e:RegExp = new RegExp('^(?:https?|ftp)(?::/*(?:[^?]+))([?][^#]+)');
var matches:* = e.exec(url);
var result:String = fromQuerystring(name, matches[1]);
return result;
}
/**
* Extract hostname from URL
*/
private static function getHostName(url:String):String {
// scheme : // [username [: password] @] hostname [: port] [/ [path] [? query] [# fragment]]
var e:RegExp = new RegExp('^(?:(?:https?|ftp):)/*(?:[^@]+@)?([^:/#]+)');
var matches:* = e.exec(url);
return matches ? matches[1] : url;
};
/**
* Test whether a string is an IP address
*/
private static function isIpAddress(str:String):Boolean {
var IPRegExp:RegExp = new RegExp('^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$');
return IPRegExp.test(str);
}
/**
* If the hostname is an IP address, look for text indicating
* that the page is cached by Yahoo
*/
private static function isYahooCachedPage(hostName:String):Boolean
{
return false;
var initialDivText:String;
var cachedIndicator:String;
if (isIpAddress(hostName)) {
try {
initialDivText = ExternalInterface.call("function getInitialDivText() { return document.body.children[0].children[0].children[0].children[0].children[0].children[0].innerHTML; }");
cachedIndicator = 'You have reached the cached page for';
return initialDivText.slice(0, cachedIndicator.length) === cachedIndicator;
} catch (e:Error) {
return false;
}
} else {
return false;
}
}
/**
* Fix-up domain
*/
public static function fixupDomain(domain:String):String {
var dl:int = domain.length;
// remove trailing '.'
if (domain.charAt(--dl) === '.') {
domain = domain.slice(0, dl);
}
// remove leading '*'
if (domain.slice(0, 2) === '*.') {
domain = domain.slice(1);
}
return domain;
};
/**
* Fix-up URL when page rendered from search engine cache or translated page.
* TODO: it would be nice to generalise this and/or move into the ETL phase.
*/
public static function fixupUrl(hostName:String, href:String, referrer:String):Array {
if (hostName === 'translate.googleusercontent.com') { // Google
if (referrer === '') {
referrer = href;
}
href = getParameter(href, 'u');
hostName = getHostName(href);
} else if (hostName === 'cc.bingj.com' || // Bing
hostName === 'webcache.googleusercontent.com' || // Google
isYahooCachedPage(hostName)) { // Yahoo (via Inktomi 74.6.0.0/16)
try {
href = ExternalInterface.call("function getLinkHref() { return document.links[0].href; }");
} catch (e:Error) {
href = '';
}
hostName = getHostName(href);
}
return [hostName, href, referrer];
};
public static var scriptAccessAllowed:int = -1; //-1 = not set. 0 = false. 1 = true.
public static function isScriptAccessAllowed ():Boolean
{
if (scriptAccessAllowed != -1)
{
return scriptAccessAllowed == 1;
}
if (!ExternalInterface.available)
{
scriptAccessAllowed = 0;
return false;
}
try
{
ExternalInterface.call("function isScriptAccessAllowed(){return true;}");
scriptAccessAllowed = 1;
}
catch (error:Error)
{
if (error is SecurityError)
{
scriptAccessAllowed = 0;
}
}
return scriptAccessAllowed == 1;
}
/**
* AS Implementation of MurmurHash3
*
* @param {string} key ASCII only
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
public static function murmurhash3_32_gc(key:String, seed:Number):Number {
var remainder:Number;
var bytes:Number;
var h1:Number;
var h1b:Number;
var c1:Number;
var c1b:Number;
var c2:Number;
var c2b:Number;
var k1:Number;
var i:Number;
remainder = key.length & 3; // key.length % 4
bytes = key.length - remainder;
h1 = seed;
c1 = 0xcc9e2d51;
c2 = 0x1b873593;
i = 0;
while (i < bytes) {
k1 =
((key.charCodeAt(i) & 0xff)) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;
h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));
}
k1 = 0;
switch (remainder) {
case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
case 1: k1 ^= (key.charCodeAt(i) & 0xff);
k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 13;
h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
h1 ^= h1 >>> 16;
return h1 >>> 0;
}
}
}
|
resolve #24 - Base64 encoding must be URL-safe, no padding, no wrapping
|
resolve #24 - Base64 encoding must be URL-safe, no padding, no wrapping
|
ActionScript
|
apache-2.0
|
snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker,snowplow/snowplow-actionscript3-tracker
|
6429e30e5fec1aa3b4ccb63a74ff15330be173a4
|
src/aerys/minko/render/resource/texture/TextureResource.as
|
src/aerys/minko/render/resource/texture/TextureResource.as
|
package aerys.minko.render.resource.texture
{
import flash.display.BitmapData;
import flash.display3D.Context3D;
import flash.display3D.Context3DTextureFormat;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Matrix;
import flash.utils.ByteArray;
/**
* @inheritdoc
* @author Jean-Marc Le Roux
*
*/
public final class TextureResource implements ITextureResource
{
private static const MAX_SIZE : uint = 2048;
private static const TMP_MATRIX : Matrix = new Matrix();
private static const FORMAT_BGRA : String = Context3DTextureFormat.BGRA
private static const FORMAT_COMPRESSED : String = Context3DTextureFormat.COMPRESSED;
private var _texture : Texture = null;
private var _mipmap : Boolean = false;
private var _bitmapData : BitmapData = null;
private var _atf : ByteArray = null;
private var _width : Number = 0;
private var _height : Number = 0;
private var _update : Boolean = false;
private var _resize : Boolean = false;
public function get width() : Number
{
return _width;
}
public function get height() : Number
{
return _height;
}
public function TextureResource(width : int = 0, height : int = 0)
{
if (width != 0 && height != 0)
setSize(width, height);
}
public function setSize(width : uint, height : uint) : void
{
//http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
if (!(width && !(width & (width - 1)))
|| !(height && !(height & (height - 1))))
{
throw new Error(
'The size must be a power of 2.'
);
}
_width = width;
_height = height;
_resize = true;
}
public function setContentFromBitmapData(bitmapData : BitmapData,
mipmap : Boolean,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = bitmapData.width;
var bitmapHeight : uint = bitmapData.height;
var w : int = 0;
var h : int = 0;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (w > MAX_SIZE)
w = MAX_SIZE;
if (h > MAX_SIZE)
h = MAX_SIZE;
_bitmapData = new BitmapData(w, h, bitmapData.transparent, 0);
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_bitmapData.draw(bitmapData, TMP_MATRIX);
}
else
{
_bitmapData.draw(bitmapData);
}
if (_texture
&& (mipmap != _mipmap
|| bitmapData.width != _width
|| bitmapData.height != _height))
{
_texture.dispose();
_texture = null;
}
_width = _bitmapData.width;
_height = _bitmapData.height;
_mipmap = mipmap;
_update = true;
}
public function setContentFromATF(atf : ByteArray) : void
{
_atf = atf;
}
public function getNativeTexture(context : Context3D) : TextureBase
{
if ((!_texture || _resize) && _width && _height)
{
_resize = false;
if (_texture)
_texture.dispose();
_texture = context.createTexture(
_width,
_height,
_atf ? FORMAT_COMPRESSED : FORMAT_BGRA,
_bitmapData == null && _atf == null
);
_update = true;
}
if (_update)
{
_update = false;
uploadTextureWithMipMaps();
}
_atf = null;
_bitmapData = null;
return _texture;
}
private function uploadTextureWithMipMaps() : void
{
if (_bitmapData)
{
if (_mipmap)
{
var level : int = 0;
var size : int = _width > _height ? _width : _height;
var transparent : Boolean = _bitmapData.transparent;
var transform : Matrix = new Matrix();
var tmp : BitmapData = new BitmapData(
size,
size,
transparent,
0
);
while (size >= 1)
{
tmp.draw(_bitmapData, transform, null, null, null, true);
_texture.uploadFromBitmapData(tmp, level);
transform.scale(.5, .5);
level++;
size >>= 1;
if (tmp.transparent)
tmp.fillRect(tmp.rect, 0);
}
tmp.dispose();
}
else
{
_texture.uploadFromBitmapData(_bitmapData, 0);
}
_bitmapData.dispose();
}
else if (_atf)
{
_texture.uploadCompressedTextureFromByteArray(_atf, 0, false);
}
}
public function dispose() : void
{
_texture.dispose();
_texture = null;
}
}
}
|
package aerys.minko.render.resource.texture
{
import flash.display.BitmapData;
import flash.display3D.Context3D;
import flash.display3D.Context3DTextureFormat;
import flash.display3D.textures.Texture;
import flash.display3D.textures.TextureBase;
import flash.geom.Matrix;
import flash.utils.ByteArray;
/**
* @inheritdoc
* @author Jean-Marc Le Roux
*
*/
public final class TextureResource implements ITextureResource
{
private static const MAX_SIZE : uint = 2048;
private static const TMP_MATRIX : Matrix = new Matrix();
private static const FORMAT_BGRA : String = Context3DTextureFormat.BGRA
private static const FORMAT_COMPRESSED : String = Context3DTextureFormat.COMPRESSED;
private var _texture : Texture = null;
private var _mipmap : Boolean = false;
private var _bitmapData : BitmapData = null;
private var _atf : ByteArray = null;
private var _atfFormat : uint = 0;
private var _width : Number = 0;
private var _height : Number = 0;
private var _update : Boolean = false;
private var _resize : Boolean = false;
public function get width() : Number
{
return _width;
}
public function get height() : Number
{
return _height;
}
public function TextureResource(width : int = 0, height : int = 0)
{
if (width != 0 && height != 0)
setSize(width, height);
}
public function setSize(width : uint, height : uint) : void
{
//http://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
if (!(width && !(width & (width - 1)))
|| !(height && !(height & (height - 1))))
{
throw new Error(
'The size must be a power of 2.'
);
}
_width = width;
_height = height;
_resize = true;
}
public function setContentFromBitmapData(bitmapData : BitmapData,
mipmap : Boolean,
downSample : Boolean = false) : void
{
var bitmapWidth : uint = bitmapData.width;
var bitmapHeight : uint = bitmapData.height;
var w : int = 0;
var h : int = 0;
if (downSample)
{
w = 1 << Math.floor(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.floor(Math.log(bitmapHeight) * Math.LOG2E);
}
else
{
w = 1 << Math.ceil(Math.log(bitmapWidth) * Math.LOG2E);
h = 1 << Math.ceil(Math.log(bitmapHeight) * Math.LOG2E);
}
if (w > MAX_SIZE)
w = MAX_SIZE;
if (h > MAX_SIZE)
h = MAX_SIZE;
_bitmapData = new BitmapData(w, h, bitmapData.transparent, 0);
if (w != bitmapWidth || h != bitmapHeight)
{
TMP_MATRIX.identity();
TMP_MATRIX.scale(w / bitmapWidth, h / bitmapHeight);
_bitmapData.draw(bitmapData, TMP_MATRIX);
}
else
{
_bitmapData.draw(bitmapData);
}
if (_texture
&& (mipmap != _mipmap
|| bitmapData.width != _width
|| bitmapData.height != _height))
{
_texture.dispose();
_texture = null;
}
_width = _bitmapData.width;
_height = _bitmapData.height;
_mipmap = mipmap;
_update = true;
}
public function setContentFromATF(atf : ByteArray) : void
{
_atf = atf;
_update = true;
atf.position = 6;
_atfFormat = atf.readUnsignedByte() & 3;
_width = 1 << atf.readUnsignedByte();
_height = 1 << atf.readUnsignedByte();
_mipmap = atf.readUnsignedByte() > 1;
atf.position = 0;
}
public function getNativeTexture(context : Context3D) : TextureBase
{
if ((!_texture || _resize) && _width && _height)
{
_resize = false;
if (_texture)
_texture.dispose();
_texture = context.createTexture(
_width,
_height,
_atf && _atfFormat == 2 ? FORMAT_COMPRESSED : FORMAT_BGRA,
_bitmapData == null && _atf == null
);
_update = true;
}
if (_update)
{
_update = false;
uploadTextureWithMipMaps();
}
_atf = null;
_bitmapData = null;
return _texture;
}
private function uploadTextureWithMipMaps() : void
{
if (_bitmapData)
{
if (_mipmap)
{
var level : int = 0;
var size : int = _width > _height ? _width : _height;
var transparent : Boolean = _bitmapData.transparent;
var transform : Matrix = new Matrix();
var tmp : BitmapData = new BitmapData(
size,
size,
transparent,
0
);
while (size >= 1)
{
tmp.draw(_bitmapData, transform, null, null, null, true);
_texture.uploadFromBitmapData(tmp, level);
transform.scale(.5, .5);
level++;
size >>= 1;
if (tmp.transparent)
tmp.fillRect(tmp.rect, 0);
}
tmp.dispose();
}
else
{
_texture.uploadFromBitmapData(_bitmapData, 0);
}
_bitmapData.dispose();
}
else if (_atf)
{
_texture.uploadCompressedTextureFromByteArray(_atf, 0, false);
}
}
public function dispose() : void
{
_texture.dispose();
_texture = null;
}
}
}
|
Fix bugs in ATF texture support: - Proper initialization in setContentFromATF() - Proper texture format
|
Fix bugs in ATF texture support:
- Proper initialization in setContentFromATF()
- Proper texture format
|
ActionScript
|
mit
|
aerys/minko-as3
|
869a4a6030ed47db6af1df39ef50aa62f5b79e8c
|
src/aerys/minko/render/shader/node/operation/manipulation/VariadicExtract.as
|
src/aerys/minko/render/shader/node/operation/manipulation/VariadicExtract.as
|
package aerys.minko.render.shader.node.operation.manipulation
{
import aerys.minko.render.shader.node.INode;
import aerys.minko.render.shader.node.leaf.AbstractConstant;
import aerys.minko.render.shader.node.leaf.Constant;
import aerys.minko.render.shader.node.operation.AbstractOperation;
import aerys.minko.render.shader.node.operation.builtin.Multiply;
public class VariadicExtract extends AbstractOperation
{
private var _cellSize : uint;
override public function get instructionName() : String
{
throw new Error('This is a virtual operand');
}
override public function get opCode() : uint
{
throw new Error('This is a virtual operand');
}
override public function get size() : uint
{
return _cellSize;
}
public function VariadicExtract(index : INode,
table : AbstractConstant,
cellSize : uint)
{
_cellSize = cellSize;
var leftOperand : INode = index;
if (cellSize != 4)
leftOperand = new Multiply(
leftOperand,
new Constant(cellSize / 4)
);
var rightOperand : INode = table;
super(leftOperand, rightOperand);
if (cellSize % 4 != 0) throw new Error();
if (index.size != 1) throw new Error();
}
override public function isSame(node : INode) : Boolean
{
var castedNode : VariadicExtract = node as VariadicExtract;
return castedNode != null &&
castedNode._arg1.isSame(_arg1) &&
castedNode._arg2.isSame(_arg2) &&
castedNode._cellSize == _cellSize;
}
}
}
|
package aerys.minko.render.shader.node.operation.manipulation
{
import aerys.minko.render.shader.node.Components;
import aerys.minko.render.shader.node.INode;
import aerys.minko.render.shader.node.leaf.AbstractConstant;
import aerys.minko.render.shader.node.leaf.Constant;
import aerys.minko.render.shader.node.operation.AbstractOperation;
import aerys.minko.render.shader.node.operation.builtin.Multiply;
public class VariadicExtract extends AbstractOperation
{
private var _cellSize : uint;
override public function get instructionName() : String
{
throw new Error('This is a virtual operand');
}
override public function get opCode() : uint
{
throw new Error('This is a virtual operand');
}
override public function get size() : uint
{
return _cellSize;
}
public function VariadicExtract(index : INode,
table : AbstractConstant,
cellSize : uint)
{
_cellSize = cellSize;
var leftOperand : INode = index;
if (cellSize != 4)
{
leftOperand = new Multiply(leftOperand, new Constant(cellSize / 4));
// the following is a patch to adobe's agal validator.
// we have to fill a complete register for the index to work
leftOperand = new RootWrapper(new Extract(leftOperand, Components.XXXX));
}
var rightOperand : INode = table;
super(leftOperand, rightOperand);
if (cellSize % 4 != 0) throw new Error();
if (index.size != 1) throw new Error();
}
override public function isSame(node : INode) : Boolean
{
var castedNode : VariadicExtract = node as VariadicExtract;
return castedNode != null &&
castedNode._arg1.isSame(_arg1) &&
castedNode._arg2.isSame(_arg2) &&
castedNode._cellSize == _cellSize;
}
}
}
|
add a workaround for a bug from adobe during shader validation to do vc[ft0.x], ft0.yzw must be set, which makes no sense...
|
add a workaround for a bug from adobe during shader validation
to do vc[ft0.x], ft0.yzw must be set, which makes no sense...
|
ActionScript
|
mit
|
aerys/minko-as3
|
b8d44372c8d717df6b1f7b242e49fbb6181d91e7
|
src/aerys/minko/scene/node/Scene.as
|
src/aerys/minko/scene/node/Scene.as
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Effect;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.scene.RenderingController;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.loader.AssetsLibrary;
import flash.display.BitmapData;
import flash.utils.Dictionary;
import flash.utils.getTimer;
/**
* Scene objects are the root of any 3D scene.
*
* @author Jean-Marc Le Roux
*
*/
public final class Scene extends Group
{
use namespace minko_scene;
minko_scene var _camera : AbstractCamera;
private var _renderingCtrl : RenderingController;
private var _properties : DataProvider;
private var _bindings : DataBindings;
private var _numTriangles : uint;
private var _enterFrame : Signal;
private var _renderingBegin : Signal;
private var _renderingEnd : Signal;
private var _exitFrame : Signal;
private var _assets : AssetsLibrary;
public function get assets():AssetsLibrary
{
return _assets;
}
public function get activeCamera() : AbstractCamera
{
return _camera;
}
public function get numPasses() : uint
{
return _renderingCtrl.numPasses;
}
public function get numEnabledPasses() : uint
{
return _renderingCtrl.numEnabledPasses;
}
public function get numTriangles() : uint
{
return _numTriangles;
}
public function get postProcessingEffect() : Effect
{
return _renderingCtrl.postProcessingEffect;
}
public function set postProcessingEffect(value : Effect) : void
{
_renderingCtrl.postProcessingEffect = value;
}
public function get postProcessingProperties() : DataProvider
{
return _renderingCtrl.postProcessingProperties;
}
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The signal executed when the viewport is about to start rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who starts rendering the frame</li>
* </ul>
* @return
*
*/
public function get enterFrame() : Signal
{
return _enterFrame;
}
/**
* The signal executed when the viewport is done rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who just finished rendering the frame</li>
* </ul>
* @return
*
*/
public function get exitFrame() : Signal
{
return _exitFrame;
}
public function get renderingBegin() : Signal
{
return _renderingBegin;
}
public function get renderingEnd() : Signal
{
return _renderingEnd;
}
public function Scene(...children)
{
super(children);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
_assets = new AssetsLibrary();
this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_enterFrame = new Signal('Scene.enterFrame');
_renderingBegin = new Signal('Scene.renderingBegin');
_renderingEnd = new Signal('Scene.renderingEnd');
_exitFrame = new Signal('Scene.exitFrame');
}
override protected function initializeSignalHandlers() : void
{
super.initializeSignalHandlers();
added.add(addedHandler);
}
override protected function initializeContollers() : void
{
_renderingCtrl = new RenderingController();
addController(_renderingCtrl);
super.initializeContollers();
}
public function render(viewport : Viewport, destination : BitmapData = null) : void
{
_enterFrame.execute(this, viewport, destination, getTimer());
if (viewport.ready && viewport.visible)
{
_renderingBegin.execute(this, viewport, destination, getTimer());
_numTriangles = _renderingCtrl.render(viewport, destination);
_renderingEnd.execute(this, viewport, destination, getTimer());
}
_exitFrame.execute(this, viewport, destination, getTimer());
}
private function addedHandler(child : ISceneNode, parent : Group) : void
{
throw new Error();
}
}
}
|
package aerys.minko.scene.node
{
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Effect;
import aerys.minko.render.Viewport;
import aerys.minko.scene.controller.scene.RenderingController;
import aerys.minko.scene.node.camera.AbstractCamera;
import aerys.minko.type.Signal;
import aerys.minko.type.binding.DataBindings;
import aerys.minko.type.binding.DataProvider;
import aerys.minko.type.enum.DataProviderUsage;
import aerys.minko.type.loader.AssetsLibrary;
import flash.display.BitmapData;
import flash.utils.Dictionary;
import flash.utils.getTimer;
/**
* Scene objects are the root of any 3D scene.
*
* @author Jean-Marc Le Roux
*
*/
public final class Scene extends Group
{
use namespace minko_scene;
minko_scene var _camera : AbstractCamera;
private var _renderingCtrl : RenderingController;
private var _properties : DataProvider;
private var _bindings : DataBindings;
private var _numTriangles : uint;
private var _enterFrame : Signal;
private var _renderingBegin : Signal;
private var _renderingEnd : Signal;
private var _exitFrame : Signal;
private var _assets : AssetsLibrary;
public function get assets() : AssetsLibrary
{
return _assets;
}
public function get activeCamera() : AbstractCamera
{
return _camera;
}
public function get numPasses() : uint
{
return _renderingCtrl.numPasses;
}
public function get numEnabledPasses() : uint
{
return _renderingCtrl.numEnabledPasses;
}
public function get numTriangles() : uint
{
return _numTriangles;
}
public function get postProcessingEffect() : Effect
{
return _renderingCtrl.postProcessingEffect;
}
public function set postProcessingEffect(value : Effect) : void
{
_renderingCtrl.postProcessingEffect = value;
}
public function get postProcessingProperties() : DataProvider
{
return _renderingCtrl.postProcessingProperties;
}
public function get properties() : DataProvider
{
return _properties;
}
public function set properties(value : DataProvider) : void
{
if (_properties != value)
{
if (_properties)
_bindings.removeProvider(_properties);
_properties = value;
if (value)
_bindings.addProvider(value);
}
}
public function get bindings() : DataBindings
{
return _bindings;
}
/**
* The signal executed when the viewport is about to start rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who starts rendering the frame</li>
* </ul>
* @return
*
*/
public function get enterFrame() : Signal
{
return _enterFrame;
}
/**
* The signal executed when the viewport is done rendering a frame.
* Callback functions for this signal should accept the following arguments:
* <ul>
* <li>viewport : Viewport, the viewport who just finished rendering the frame</li>
* </ul>
* @return
*
*/
public function get exitFrame() : Signal
{
return _exitFrame;
}
public function get renderingBegin() : Signal
{
return _renderingBegin;
}
public function get renderingEnd() : Signal
{
return _renderingEnd;
}
public function Scene(...children)
{
super(children);
}
override protected function initialize() : void
{
_bindings = new DataBindings(this);
_assets = new AssetsLibrary();
this.properties = new DataProvider(DataProviderUsage.EXCLUSIVE);
super.initialize();
}
override protected function initializeSignals() : void
{
super.initializeSignals();
_enterFrame = new Signal('Scene.enterFrame');
_renderingBegin = new Signal('Scene.renderingBegin');
_renderingEnd = new Signal('Scene.renderingEnd');
_exitFrame = new Signal('Scene.exitFrame');
}
override protected function initializeSignalHandlers() : void
{
super.initializeSignalHandlers();
added.add(addedHandler);
}
override protected function initializeContollers() : void
{
_renderingCtrl = new RenderingController();
addController(_renderingCtrl);
super.initializeContollers();
}
public function render(viewport : Viewport, destination : BitmapData = null) : void
{
_enterFrame.execute(this, viewport, destination, getTimer());
if (viewport.ready && viewport.visible)
{
_renderingBegin.execute(this, viewport, destination, getTimer());
_numTriangles = _renderingCtrl.render(viewport, destination);
_renderingEnd.execute(this, viewport, destination, getTimer());
}
_exitFrame.execute(this, viewport, destination, getTimer());
}
private function addedHandler(child : ISceneNode, parent : Group) : void
{
throw new Error();
}
}
}
|
fix coding style
|
fix coding style
|
ActionScript
|
mit
|
aerys/minko-as3
|
02c3efbf2c87ce243ac1dd4ba1bd72ab9e8c257f
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/layouts/HorizontalLayout.as
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/layouts/HorizontalLayout.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IBeadModel;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.geom.Rectangle;
import org.apache.flex.utils.dbg.DOMPathUtil;
import org.apache.flex.utils.CSSContainerUtils;
/**
* The HorizontalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* horizontally in one row, separating them according to
* CSS layout rules for margin and vertical-align styles.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class HorizontalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function HorizontalLayout()
{
}
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
host = value as ILayoutChild;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
//trace(DOMPathUtil.getPath(host), event ? event.type : "fixed size");
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent.contentView;
var padding:Rectangle = CSSContainerUtils.getPaddingMetrics(host);
var n:int = contentView.numElements;
var hostSizedToContent:Boolean = host.isHeightSizedToContent();
var ilc:ILayoutChild;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var maxHeight:Number = 0;
// asking for contentView.width can result in infinite loop if host isn't sized already
var h:Number = hostSizedToContent ? 0 : contentView.height;
var verticalMargins:Array = [];
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
var top:Number = ValuesManager.valuesImpl.getValue(child, "top");
var bottom:Number = ValuesManager.valuesImpl.getValue(child, "bottom");
ilc = child as ILayoutChild;
margin = ValuesManager.valuesImpl.getValue(child, "margin");
if (margin is Array)
{
if (margin.length == 1)
marginLeft = marginTop = marginRight = marginBottom = margin[0];
else if (margin.length <= 3)
{
marginLeft = marginRight = margin[1];
marginTop = marginBottom = margin[0];
}
else if (margin.length == 4)
{
marginLeft = margin[3];
marginBottom = margin[2];
marginRight = margin[1];
marginTop = margin[0];
}
}
else if (margin == null)
{
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
}
else
{
marginLeft = marginTop = marginBottom = marginRight = margin;
}
var ml:Number;
var mr:Number;
var mt:Number;
var mb:Number;
var lastmr:Number;
if (marginLeft == "auto")
ml = 0;
else
{
ml = Number(marginLeft);
if (isNaN(ml))
ml = 0;
}
if (marginRight == "auto")
mr = 0;
else
{
mr = Number(marginRight);
if (isNaN(mr))
mr = 0;
}
mt = Number(marginTop);
if (isNaN(mt))
mt = 0;
mb = Number(marginBottom);
if (isNaN(mb))
mb = 0;
var xx:Number;
if (i == 0)
{
if (ilc)
ilc.setX(ml + padding.left);
else
child.x = ml + padding.left;
}
else
{
if (ilc)
ilc.setX(xx + ml + lastmr);
else
child.x = xx + ml + lastmr;
}
if (ilc)
{
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100, !isNaN(ilc.percentHeight));
}
lastmr = mr;
var marginObject:Object = {};
verticalMargins[i] = marginObject;
if (!hostSizedToContent)
{
// if host is sized by parent,
// we can position and size children horizontally now
setPositionAndHeight(child, top, mt, padding.top, bottom, mb, padding.bottom, h);
maxHeight = Math.max(maxHeight, mt + child.height + mb);
}
else
{
if (!isNaN(top))
{
mt = top;
marginObject.top = mt;
}
if (!isNaN(bottom))
{
mb = bottom;
marginObject.bottom = mb;
}
maxHeight = Math.max(maxHeight, mt + child.height + mb);
}
xx = child.x + child.width;
var valign:* = ValuesManager.valuesImpl.getValue(child, "vertical-align");
marginObject.valign = valign;
}
if (hostSizedToContent)
{
ILayoutChild(contentView).setHeight(maxHeight, true);
if (host.isWidthSizedToContent())
ILayoutChild(contentView).setWidth(xx, true);
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
var obj:Object = verticalMargins[i];
setPositionAndHeight(child, obj.top, obj.marginTop, padding.top,
obj.bottom, obj.marginBottom, padding.bottom, maxHeight);
}
}
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
ilc = child as ILayoutChild;
if (child == null || !child.visible) continue;
obj = verticalMargins[i];
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, !isNaN(ilc.percentHeight));
}
if (ilc)
{
if (obj.valign == "top")
ilc.setY(obj.marginTop + padding.top);
else if (valign == "bottom")
ilc.setY(maxHeight - child.height - obj.marginBottom);
else // TODO: aharui - baseline
ilc.setY((maxHeight - child.height) / 2);
}
else
{
if (obj.valign == "top")
child.y = obj.marginTop + padding.top;
else if (valign == "bottom")
child.y = maxHeight - child.height - obj.marginBottom;
else // TODO: aharui - baseline
child.y = (maxHeight - child.height) / 2;
}
}
// Only return true if the contentView needs to be larger; that new
// size is stored in the model.
var sizeChanged:Boolean = true;
host.dispatchEvent( new Event("layoutComplete") );
return sizeChanged;
}
private function setPositionAndHeight(child:IUIBase, top:Number, mt:Number, pt:Number,
bottom:Number, mb:Number, pb:Number, h:Number):void
{
var heightSet:Boolean = false;
var hh:Number = h;
var ilc:ILayoutChild = child as ILayoutChild;
if (!isNaN(top))
{
if (ilc)
ilc.setY(top + mt);
else
child.y = top + mt;
hh -= top + mt;
}
else
{
if (ilc)
ilc.setY(mt + pt);
else
child.y = mt + pt;
hh -= mt + pt;
}
if (!isNaN(bottom))
{
if (!isNaN(top))
{
if (ilc)
ilc.setHeight(hh - bottom - mb, true);
else
{
child.height = hh - bottom - mb;
heightSet = true;
}
}
else
{
if (ilc)
ilc.setY(h - bottom - mb - child.height);
else
child.y = h - bottom - mb - child.height;
}
}
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(h * ilc.percentHeight / 100, true);
}
if (!heightSet)
child.dispatchEvent(new Event("sizeChanged"));
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads.layouts
{
import org.apache.flex.core.IBeadLayout;
import org.apache.flex.core.IBeadModel;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.ILayoutParent;
import org.apache.flex.core.IParentIUIBase;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.geom.Rectangle;
import org.apache.flex.utils.dbg.DOMPathUtil;
import org.apache.flex.utils.CSSUtils;
import org.apache.flex.utils.CSSContainerUtils;
/**
* The HorizontalLayout class is a simple layout
* bead. It takes the set of children and lays them out
* horizontally in one row, separating them according to
* CSS layout rules for margin and vertical-align styles.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class HorizontalLayout implements IBeadLayout
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function HorizontalLayout()
{
}
// the strand/host container is also an ILayoutChild because
// can have its size dictated by the host's parent which is
// important to know for layout optimization
private var host:ILayoutChild;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
host = value as ILayoutChild;
}
/**
* @copy org.apache.flex.core.IBeadLayout#layout
*/
public function layout():Boolean
{
//trace(DOMPathUtil.getPath(host), event ? event.type : "fixed size");
var layoutParent:ILayoutParent = host.getBeadByType(ILayoutParent) as ILayoutParent;
var contentView:IParentIUIBase = layoutParent.contentView;
var padding:Rectangle = CSSContainerUtils.getPaddingMetrics(host);
var n:int = contentView.numElements;
var hostSizedToContent:Boolean = host.isHeightSizedToContent();
var ilc:ILayoutChild;
var marginLeft:Object;
var marginRight:Object;
var marginTop:Object;
var marginBottom:Object;
var margin:Object;
var maxHeight:Number = 0;
// asking for contentView.height can result in infinite loop if host isn't sized already
var h:Number = hostSizedToContent ? 0 : contentView.height;
var w:Number = contentView.width;
var verticalMargins:Array = [];
for (var i:int = 0; i < n; i++)
{
var child:IUIBase = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
var top:Number = ValuesManager.valuesImpl.getValue(child, "top");
var bottom:Number = ValuesManager.valuesImpl.getValue(child, "bottom");
margin = ValuesManager.valuesImpl.getValue(child, "margin");
marginLeft = ValuesManager.valuesImpl.getValue(child, "margin-left");
marginTop = ValuesManager.valuesImpl.getValue(child, "margin-top");
marginRight = ValuesManager.valuesImpl.getValue(child, "margin-right");
marginBottom = ValuesManager.valuesImpl.getValue(child, "margin-bottom");
var ml:Number = CSSUtils.getLeftValue(marginLeft, margin, w);
var mr:Number = CSSUtils.getRightValue(marginRight, margin, w);
var mt:Number = CSSUtils.getTopValue(marginTop, margin, h);
var mb:Number = CSSUtils.getBottomValue(marginBottom, margin, h);
ilc = child as ILayoutChild;
var lastmr:Number;
if (marginLeft == "auto")
ml = 0;
if (marginRight == "auto")
mr = 0;
var xx:Number;
if (i == 0)
{
if (ilc)
ilc.setX(ml + padding.left);
else
child.x = ml + padding.left;
}
else
{
if (ilc)
ilc.setX(xx + ml + lastmr);
else
child.x = xx + ml + lastmr;
}
if (ilc)
{
if (!isNaN(ilc.percentWidth))
ilc.setWidth(contentView.width * ilc.percentWidth / 100, !isNaN(ilc.percentHeight));
}
lastmr = mr;
var marginObject:Object = {};
verticalMargins[i] = marginObject;
if (!hostSizedToContent)
{
// if host is sized by parent,
// we can position and size children horizontally now
setPositionAndHeight(child, top, mt, padding.top, bottom, mb, padding.bottom, h);
maxHeight = Math.max(maxHeight, mt + child.height + mb);
}
else
{
if (!isNaN(top))
{
mt = top;
marginObject.top = mt;
}
if (!isNaN(bottom))
{
mb = bottom;
marginObject.bottom = mb;
}
maxHeight = Math.max(maxHeight, mt + child.height + mb);
}
xx = child.x + child.width;
var valign:* = ValuesManager.valuesImpl.getValue(child, "vertical-align");
marginObject.valign = valign;
}
if (hostSizedToContent)
{
ILayoutChild(contentView).setHeight(maxHeight, true);
if (host.isWidthSizedToContent())
ILayoutChild(contentView).setWidth(xx, true);
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
if (child == null || !child.visible) continue;
var obj:Object = verticalMargins[i];
setPositionAndHeight(child, obj.top, obj.marginTop, padding.top,
obj.bottom, obj.marginBottom, padding.bottom, maxHeight);
}
}
for (i = 0; i < n; i++)
{
child = contentView.getElementAt(i) as IUIBase;
ilc = child as ILayoutChild;
if (child == null || !child.visible) continue;
obj = verticalMargins[i];
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(contentView.height * ilc.percentHeight / 100, !isNaN(ilc.percentHeight));
}
if (ilc)
{
if (obj.valign == "top")
ilc.setY(obj.marginTop + padding.top);
else if (valign == "bottom")
ilc.setY(maxHeight - child.height - obj.marginBottom);
else // TODO: aharui - baseline
ilc.setY((maxHeight - child.height) / 2);
}
else
{
if (obj.valign == "top")
child.y = obj.marginTop + padding.top;
else if (valign == "bottom")
child.y = maxHeight - child.height - obj.marginBottom;
else // TODO: aharui - baseline
child.y = (maxHeight - child.height) / 2;
}
}
// Only return true if the contentView needs to be larger; that new
// size is stored in the model.
var sizeChanged:Boolean = true;
host.dispatchEvent( new Event("layoutComplete") );
return sizeChanged;
}
private function setPositionAndHeight(child:IUIBase, top:Number, mt:Number, pt:Number,
bottom:Number, mb:Number, pb:Number, h:Number):void
{
var heightSet:Boolean = false;
var hh:Number = h;
var ilc:ILayoutChild = child as ILayoutChild;
if (!isNaN(top))
{
if (ilc)
ilc.setY(top + mt);
else
child.y = top + mt;
hh -= top + mt;
}
else
{
if (ilc)
ilc.setY(mt + pt);
else
child.y = mt + pt;
hh -= mt + pt;
}
if (!isNaN(bottom))
{
if (!isNaN(top))
{
if (ilc)
ilc.setHeight(hh - bottom - mb, true);
else
{
child.height = hh - bottom - mb;
heightSet = true;
}
}
else
{
if (ilc)
ilc.setY(h - bottom - mb - child.height);
else
child.y = h - bottom - mb - child.height;
}
}
if (ilc)
{
if (!isNaN(ilc.percentHeight))
ilc.setHeight(h * ilc.percentHeight / 100, true);
}
if (!heightSet)
child.dispatchEvent(new Event("sizeChanged"));
}
}
}
|
fix margin handling
|
fix margin handling
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
ff90d821b4031e96ce702557b874d71584968a6d
|
swfcat.as
|
swfcat.as
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
private var output_text:TextField;
// Socket to facilitator.
private var s_f:Socket;
private var fac_addr:Object;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
var tor_spec:String;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
go();
}
private function go():void
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.net.Socket;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.utils.ByteArray;
public class swfcat extends Sprite
{
/* David's relay (nickname 3VXRyxz67OeRoqHn) that also serves a
crossdomain policy. */
private const DEFAULT_TOR_ADDR:Object = {
host: "173.255.221.44",
port: 9001
};
private var output_text:TextField;
// Socket to facilitator.
private var s_f:Socket;
private var fac_addr:Object;
public function puts(s:String):void
{
output_text.appendText(s + "\n");
output_text.scrollV = output_text.maxScrollV;
}
public function swfcat()
{
output_text = new TextField();
output_text.width = 400;
output_text.height = 300;
output_text.background = true;
output_text.backgroundColor = 0x001f0f;
output_text.textColor = 0x44CC44;
addChild(output_text);
puts("Starting.");
// Wait until the query string parameters are loaded.
this.loaderInfo.addEventListener(Event.COMPLETE, loaderinfo_complete);
}
private function loaderinfo_complete(e:Event):void
{
var fac_spec:String;
var tor_spec:String;
puts("Parameters loaded.");
fac_spec = this.loaderInfo.parameters["facilitator"];
if (!fac_spec) {
puts("Error: no \"facilitator\" specification provided.");
return;
}
puts("Facilitator spec: \"" + fac_spec + "\"");
fac_addr = parse_addr_spec(fac_spec);
if (!fac_addr) {
puts("Error: Facilitator spec must be in the form \"host:port\".");
return;
}
main();
}
/* The main logic begins here, after start-up issues are taken care of. */
private function main():void
{
s_f = new Socket();
s_f.addEventListener(Event.CONNECT, fac_connected);
s_f.addEventListener(Event.CLOSE, function (e:Event):void {
puts("Facilitator: closed connection.");
});
s_f.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
puts("Facilitator: I/O error: " + e.text + ".");
});
s_f.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
puts("Facilitator: security error: " + e.text + ".");
});
puts("Facilitator: connecting to " + fac_addr.host + ":" + fac_addr.port + ".");
s_f.connect(fac_addr.host, fac_addr.port);
}
private function fac_connected(e:Event):void
{
puts("Facilitator: connected.");
s_f.addEventListener(ProgressEvent.SOCKET_DATA, fac_data);
s_f.writeUTFBytes("GET / HTTP/1.0\r\n\r\n");
}
private function fac_data(e:ProgressEvent):void
{
var client_spec:String;
var client_addr:Object;
var proxy_pair:Object;
client_spec = s_f.readMultiByte(e.bytesLoaded, "utf-8");
puts("Facilitator: got \"" + client_spec + "\"");
client_addr = parse_addr_spec(client_spec);
if (!client_addr) {
puts("Error: Client spec must be in the form \"host:port\".");
return;
}
if (client_addr.host == "0.0.0.0" && client_addr.port == 0) {
puts("Error: Facilitator has no clients.");
return;
}
proxy_pair = new ProxyPair(this, client_addr, DEFAULT_TOR_ADDR);
}
/* Parse an address in the form "host:port". Returns an Object with
keys "host" (String) and "port" (int). Returns null on error. */
private static function parse_addr_spec(spec:String):Object
{
var parts:Array;
var addr:Object;
parts = spec.split(":", 2);
if (parts.length != 2 || !parseInt(parts[1]))
return null;
addr = {}
addr.host = parts[0];
addr.port = parseInt(parts[1]);
return addr;
}
}
}
import flash.display.Sprite;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import flash.utils.ByteArray;
/* An instance of a client-relay connection. */
class ProxyPair
{
// Address ({host, port}) of client.
private var addr_c:Object;
// Address ({host, port}) of relay.
private var addr_r:Object;
// Socket to client.
private var s_c:Socket;
// Socket to relay.
private var s_r:Socket;
// Parent swfcat, for UI updates.
private var ui:swfcat;
private function log(msg:String):void
{
ui.puts(id() + ": " + msg)
}
// String describing this pair for output.
private function id():String
{
return "<" + this.addr_c.host + ":" + this.addr_c.port +
"," + this.addr_r.host + ":" + this.addr_r.port + ">";
}
public function ProxyPair(ui:swfcat, addr_c:Object, addr_r:Object)
{
this.ui = ui;
this.addr_c = addr_c;
this.addr_r = addr_r;
}
public function connect():void
{
s_r = new Socket();
s_r.addEventListener(Event.CONNECT, tor_connected);
s_r.addEventListener(Event.CLOSE, function (e:Event):void {
log("Tor: closed.");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Tor: I/O error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
s_r.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Tor: security error: " + e.text + ".");
if (s_c.connected)
s_c.close();
});
log("Tor: connecting to " + addr_r.host + ":" + addr_r.port + ".");
s_r.connect(addr_r.host, addr_r.port);
}
private function tor_connected(e:Event):void
{
log("Tor: connected.");
s_c = new Socket();
s_c.addEventListener(Event.CONNECT, client_connected);
s_c.addEventListener(Event.CLOSE, function (e:Event):void {
log("Client: closed.");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void {
log("Client: I/O error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
s_c.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function (e:SecurityErrorEvent):void {
log("Client: security error: " + e.text + ".");
if (s_r.connected)
s_r.close();
});
log("Client: connecting to " + addr_c.host + ":" + addr_c.port + ".");
s_c.connect(addr_c.host, addr_c.port);
}
private function client_connected(e:Event):void
{
log("Client: connected.");
s_r.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_r.readBytes(bytes, 0, e.bytesLoaded);
log("Tor: read " + bytes.length + ".");
s_c.writeBytes(bytes);
});
s_c.addEventListener(ProgressEvent.SOCKET_DATA, function (e:ProgressEvent):void {
var bytes:ByteArray = new ByteArray();
s_c.readBytes(bytes, 0, e.bytesLoaded);
log("Client: read " + bytes.length + ".");
s_r.writeBytes(bytes);
});
}
}
|
Change the name of function "go" to "main".
|
Change the name of function "go" to "main".
|
ActionScript
|
mit
|
arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,infinity0/flashproxy,infinity0/flashproxy,arlolra/flashproxy,infinity0/flashproxy,glamrock/flashproxy,glamrock/flashproxy,glamrock/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy,arlolra/flashproxy,arlolra/flashproxy,glamrock/flashproxy,infinity0/flashproxy,arlolra/flashproxy
|
8c126333047e103691490bdd03cfc9f97e9a6bbb
|
src/aerys/minko/render/material/realistic/RealisticMaterial.as
|
src/aerys/minko/render/material/realistic/RealisticMaterial.as
|
package aerys.minko.render.material.realistic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.environment.EnvironmentMappingProperties;
import aerys.minko.render.material.phong.PhongMaterial;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.IDataProvider;
import flash.utils.Dictionary;
public class RealisticMaterial extends PhongMaterial
{
private static const DEFAULT_NAME : String = 'RealisticMaterial';
private static const SCENE_TO_EFFECT : Dictionary = new Dictionary(true);
public function get environmentMap() : ITextureResource
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP) as ITextureResource;
}
public function set environmentMap(value : ITextureResource) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP, value);
}
public function get reflectivity() : Number
{
return getProperty(EnvironmentMappingProperties.REFLECTIVITY) as Number;
}
public function set reflectivity(value : Number) : void
{
setProperty(EnvironmentMappingProperties.REFLECTIVITY, value);
}
public function get environmentMappingType() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE) as uint;
}
public function set environmentMappingType(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE, value);
}
public function get environmentBlending() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING) as uint;
}
public function set environmentBlending(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, value);
}
public function RealisticMaterial(scene : Scene,
properties : Object = null,
effect : Effect = null,
name : String = DEFAULT_NAME)
{
effect ||= SCENE_TO_EFFECT[scene] || (SCENE_TO_EFFECT[scene] = new RealisticEffect(scene));
super(scene, properties, effect, name);
}
override public function clone() : IDataProvider
{
return new RealisticMaterial((effect as RealisticEffect).scene, this, effect, name);
}
}
}
|
package aerys.minko.render.material.realistic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.environment.EnvironmentMappingProperties;
import aerys.minko.render.material.phong.PhongMaterial;
import aerys.minko.render.resource.texture.ITextureResource;
import aerys.minko.scene.node.Scene;
import aerys.minko.type.binding.IDataProvider;
import flash.utils.Dictionary;
public class RealisticMaterial extends PhongMaterial
{
private static const DEFAULT_NAME : String = 'RealisticMaterial';
private static const SCENE_TO_EFFECT : Dictionary = new Dictionary(true);
public function get environmentMap() : ITextureResource
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP) as ITextureResource;
}
public function set environmentMap(value : ITextureResource) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP, value);
}
public function get environmentMapFiltering() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING);
}
public function set environmentMapFiltering(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FILTERING, value);
}
public function get environmentMapMipMapping() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING);
}
public function set environmentMapMipMapping(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_MIPMAPPING, value);
}
public function get environmentMapWrapping() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING);
}
public function set environmentMapWrapping(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_WRAPPING, value);
}
public function get environmentMapFormat() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT);
}
public function set environmentMapFormat(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAP_FORMAT, value);
}
public function get reflectivity() : Number
{
return getProperty(EnvironmentMappingProperties.REFLECTIVITY) as Number;
}
public function set reflectivity(value : Number) : void
{
setProperty(EnvironmentMappingProperties.REFLECTIVITY, value);
}
public function get environmentMappingType() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE) as uint;
}
public function set environmentMappingType(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_MAPPING_TYPE, value);
}
public function get environmentBlending() : uint
{
return getProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING) as uint;
}
public function set environmentBlending(value : uint) : void
{
setProperty(EnvironmentMappingProperties.ENVIRONMENT_BLENDING, value);
}
public function RealisticMaterial(scene : Scene,
properties : Object = null,
effect : Effect = null,
name : String = DEFAULT_NAME)
{
effect ||= SCENE_TO_EFFECT[scene] || (SCENE_TO_EFFECT[scene] = new RealisticEffect(scene));
super(scene, properties, effect, name);
}
override public function clone() : IDataProvider
{
return new RealisticMaterial((effect as RealisticEffect).scene, this, effect, name);
}
}
}
|
add filtering, mipMapping, wrapping and format properties for the environment map to RealisticMaterial
|
add filtering, mipMapping, wrapping and format properties for the environment map to RealisticMaterial
|
ActionScript
|
mit
|
aerys/minko-as3
|
eecfc4cf0dcea108009f9efce899b9c512a69539
|
src/aerys/minko/scene/controller/debug/BonesDebugController.as
|
src/aerys/minko/scene/controller/debug/BonesDebugController.as
|
package aerys.minko.scene.controller.debug
{
import aerys.minko.render.geometry.primitive.CubeGeometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.mesh.skinning.SkinningController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.Mesh;
import aerys.minko.type.enum.DepthTest;
import aerys.minko.type.math.Vector4;
import flash.utils.Dictionary;
public final class BonesDebugController extends AbstractController
{
private var _bonesThickness : Number;
private var _material : Material;
private var _targetToBonesMesh : Dictionary = new Dictionary();
public function BonesDebugController(bonesThickness : Number = 0.02,
bonesMaterial : Material = null)
{
super(Mesh);
initialize(bonesThickness, bonesMaterial);
}
private function initialize(bonesThickness : Number, bonesMaterial : Material) : void
{
_bonesThickness = bonesThickness;
_material = bonesMaterial;
if (!_material)
{
var bonesBasicMaterial : BasicMaterial = new BasicMaterial();
bonesBasicMaterial.diffuseColor = 0x00ff00ff;
bonesBasicMaterial.depthWriteEnabled = false;
bonesBasicMaterial.depthTest = DepthTest.ALWAYS;
_material = bonesBasicMaterial;
}
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : AbstractController,
target : Mesh) : void
{
var skinningCtrl : SkinningController = target.getControllersByType(SkinningController)[0]
as SkinningController;
_targetToBonesMesh[target] = [];
for each (var joint : Group in skinningCtrl.joints)
addBonesMeshes(joint, target);
}
private function targetRemovedHandler(ctrl : AbstractController,
target : Mesh) : void
{
var skinningCtrl : SkinningController = target.getControllersByType(SkinningController)[0]
as SkinningController;
for each (var boneMesh : Mesh in _targetToBonesMesh[target])
boneMesh.parent = null;
delete _targetToBonesMesh[target];
}
private function addBonesMeshes(joint : Group,
target : Mesh) : void
{
if (joint.getChildByName('__bone__'))
return ;
var numChildren : uint = joint.numChildren;
for (var i : uint = 0; i < numChildren; ++i)
{
var child : Group = joint.getChildAt(i) as Group;
if (child != null)
{
var nextJointPosition : Vector4 = child.transform.transformVector(
Vector4.ZERO
);
var boneLength : Number = nextJointPosition.length;
if (boneLength != 0.)
{
var boneMesh : Mesh = new Mesh(
CubeGeometry.cubeGeometry, _material, '__bone__'
);
boneMesh.transform
.lookAt(nextJointPosition)
.prependTranslation(0, 0, boneLength * .5)
.prependScale(_bonesThickness, _bonesThickness, boneLength);
joint.addChild(boneMesh);
_targetToBonesMesh[target].push(boneMesh);
}
}
}
}
}
}
|
package aerys.minko.scene.controller.debug
{
import flash.utils.Dictionary;
import aerys.minko.ns.minko_scene;
import aerys.minko.render.Effect;
import aerys.minko.render.geometry.primitive.CubeGeometry;
import aerys.minko.render.geometry.primitive.LineGeometry;
import aerys.minko.render.material.Material;
import aerys.minko.render.material.basic.BasicMaterial;
import aerys.minko.render.material.line.LineMaterial;
import aerys.minko.render.material.line.LineShader;
import aerys.minko.scene.controller.AbstractController;
import aerys.minko.scene.controller.mesh.skinning.SkinningController;
import aerys.minko.scene.node.Group;
import aerys.minko.scene.node.ISceneNode;
import aerys.minko.scene.node.Mesh;
import aerys.minko.type.enum.DepthTest;
import aerys.minko.type.enum.TriangleCulling;
import aerys.minko.type.math.Vector4;
public final class BonesDebugController extends AbstractController
{
private var _bonesThickness : Number;
private var _material : LineMaterial;
private var _targetToBonesMesh : Dictionary = new Dictionary();
private var _numExtraDescendant : uint = 0;
public function BonesDebugController(bonesThickness : Number = 0.02,
bonesMaterial : LineMaterial = null,
numExtraDescendant : uint = 0)
{
super(Mesh);
_numExtraDescendant = numExtraDescendant;
initialize(bonesThickness, bonesMaterial);
}
private function initialize(bonesThickness : Number, bonesMaterial : LineMaterial) : void
{
_bonesThickness = bonesThickness;
_material = bonesMaterial;
if (!_material)
{
var bonesBasicMaterial : LineMaterial = new LineMaterial();
bonesBasicMaterial.effect = new Effect(new LineShader(null, -Number.MAX_VALUE));
bonesBasicMaterial.diffuseColor = 0xffe400ff;
bonesBasicMaterial.setProperty('depthWriteEnabled', false);
bonesBasicMaterial.setProperty('depthTest', DepthTest.ALWAYS);
bonesBasicMaterial.setProperty('triangleCulling', TriangleCulling.NONE);
_material = bonesBasicMaterial;
}
targetAdded.add(targetAddedHandler);
targetRemoved.add(targetRemovedHandler);
}
private function targetAddedHandler(ctrl : AbstractController,
target : Mesh) : void
{
var skinningCtrl : SkinningController = target.getControllersByType(SkinningController)[0]
as SkinningController;
_targetToBonesMesh[target] = [];
for each (var joint : Group in skinningCtrl.joints)
addBonesMeshes(joint, target);
}
private function targetRemovedHandler(ctrl : AbstractController,
target : Mesh) : void
{
var skinningCtrl : SkinningController = target.getControllersByType(SkinningController)[0]
as SkinningController;
for each (var boneMesh : Mesh in _targetToBonesMesh[target])
boneMesh.parent = null;
delete _targetToBonesMesh[target];
}
private function addBonesMeshes(joint : Group,
target : Mesh) : void
{
if (joint.getChildByName('__bone__'))
return ;
var numChildren : uint = joint.numChildren;
for (var i : uint = 0; i < numChildren; ++i)
{
var child : ISceneNode = joint.getChildAt(i);
if (child != null)
{
for (var extraDescendantCount : uint = 0; extraDescendantCount < _numExtraDescendant && child is Group; ++extraDescendantCount)
child = Group(child).minko_scene::_children[0] as ISceneNode;
var nextJointPosition : Vector4 = child.transform.transformVector(
Vector4.ZERO
);
var boneLength : Number = nextJointPosition.length;
if (boneLength != 0.)
{
var lineGeometry : LineGeometry = new LineGeometry();
var boneMesh : Mesh = new Mesh(
lineGeometry, _material, '__bone__'
);
// boneMesh.transform
// .lookAt(nextJointPosition)
// .prependTranslation(0, 0, boneLength * .5)
// .prependScale(_bonesThickness, _bonesThickness, boneLength);
//
lineGeometry.moveTo(0, 0, 0).lineTo(nextJointPosition.x, nextJointPosition.y, nextJointPosition.z);
joint.addChild(boneMesh);
_targetToBonesMesh[target].push(boneMesh);
}
}
}
}
}
}
|
Use LineShader to display bones
|
Use LineShader to display bones
|
ActionScript
|
mit
|
aerys/minko-as3
|
20004f34244861b017f8e1324e4151ce5d70b032
|
frameworks/as/src/org/apache/flex/core/UIBase.as
|
frameworks/as/src/org/apache/flex/core/UIBase.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
public class UIBase extends Sprite implements IInitModel, IStrand
{
public function UIBase()
{
super();
}
private var _width:Number;
override public function get width():Number
{
return _width;
}
override public function set width(value:Number):void
{
if (_width != value)
{
_width = value;
dispatchEvent(new Event("widthChanged"));
}
}
protected function get $width():Number
{
return super.width;
}
private var _height:Number;
override public function get height():Number
{
return _height;
}
override public function set height(value:Number):void
{
if (_height != value)
{
_height = value;
dispatchEvent(new Event("heightChanged"));
}
}
protected function get $height():Number
{
return super.height;
}
private var _model:IBeadModel;
public function get model():IBeadModel
{
return _model;
}
public function set model(value:IBeadModel):void
{
if (_model != value)
{
addBead(value as IBead);
dispatchEvent(new Event("modelChanged"));
}
}
private var _id:String;
public function get id():String
{
return _id;
}
public function set id(value:String):void
{
if (_id != value)
{
_id = value;
dispatchEvent(new Event("idChanged"));
}
}
// beads declared in MXML are added to the strand.
// from AS, just call addBead()
public var beads:Array;
private var strand:Vector.<IBead>;
public function addBead(bead:IBead):void
{
if (!strand)
strand = new Vector.<IBead>;
strand.push(bead);
if (bead is IBeadModel)
_model = bead as IBeadModel;
bead.strand = this;
}
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in strand)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
public function removeBead(value:IBead):IBead
{
var n:int = strand.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = strand[i];
if (bead == value)
{
strand.splice(i, 1);
return bead;
}
}
return null;
}
public function initModel():void
{
}
public function addToParent(p:DisplayObjectContainer):void
{
p.addChild(this);
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
public class UIBase extends Sprite implements IInitModel, IStrand
{
public function UIBase()
{
super();
}
private var _width:Number;
override public function get width():Number
{
return _width;
}
override public function set width(value:Number):void
{
if (_width != value)
{
_width = value;
dispatchEvent(new Event("widthChanged"));
}
}
protected function get $width():Number
{
return super.width;
}
private var _height:Number;
override public function get height():Number
{
return _height;
}
override public function set height(value:Number):void
{
if (_height != value)
{
_height = value;
dispatchEvent(new Event("heightChanged"));
}
}
protected function get $height():Number
{
return super.height;
}
private var _model:IBeadModel;
public function get model():IBeadModel
{
return _model;
}
public function set model(value:IBeadModel):void
{
if (_model != value)
{
addBead(value as IBead);
dispatchEvent(new Event("modelChanged"));
}
}
private var _id:String;
public function get id():String
{
return _id;
}
public function set id(value:String):void
{
if (_id != value)
{
_id = value;
dispatchEvent(new Event("idChanged"));
}
}
// beads declared in MXML are added to the strand.
// from AS, just call addBead()
public var beads:Array;
private var _beads:Vector.<IBead>;
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
if (bead is IBeadModel)
_model = bead as IBeadModel;
bead.strand = this;
}
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
public function removeBead(value:IBead):IBead
{
var n:int = _beads.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = _beads[i];
if (bead == value)
{
_beads.splice(i, 1);
return bead;
}
}
return null;
}
public function initModel():void
{
}
public function addToParent(p:DisplayObjectContainer):void
{
p.addChild(this);
}
}
}
|
Change internal storage name so that beads can host other beads.
|
Change internal storage name so that beads can host other beads.
git-svn-id: 00225d326fbeb9978ee2ea3564602c0fe18eb5d2@1440062 13f79535-47bb-0310-9956-ffa450edef68
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
d112b9ddf44f912b35b12e9a8c081addc0dfdd70
|
src/org/flintparticles/twoD/actions/TweenToZone.as
|
src/org/flintparticles/twoD/actions/TweenToZone.as
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2011
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.twoD.actions
{
import org.flintparticles.common.actions.ActionBase;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.twoD.particles.Particle2D;
import org.flintparticles.twoD.zones.Zone2D;
import flash.geom.Point;
[DefaultProperty("zone")]
/**
* The TweenToZone action adjusts the particle's position between two
* locations as it ages. The start location is wherever the particle starts
* from, depending on the emitter and the initializers. The end position is
* a random point within the specified zone. The current position is relative
* to the particle's energy,
* which changes as the particle ages in accordance with the energy easing
* function used. This action should be used in conjunction with the Age action.
*/
public class TweenToZone extends ActionBase
{
private var _zone:Zone2D;
/**
* The constructor creates a TweenToZone action for use by an emitter.
* To add a TweenToZone to all particles created by an emitter, use the
* emitter's addAction method.
*
* @see org.flintparticles.common.emitters.Emitter#addAction()
*
* @param zone The zone for the particle's position when its energy is 0.
*/
public function TweenToZone( zone:Zone2D )
{
_zone = zone;
}
/**
* The zone for the particle's position when its energy is 0.
*/
public function get zone():Zone2D
{
return _zone;
}
public function set zone( value:Zone2D ):void
{
_zone = value;
}
/**
* Calculates the current position of the particle based on it's energy.
*
* <p>This method is called by the emitter and need not be called by the
* user.</p>
*
* @param emitter The Emitter that created the particle.
* @param particle The particle to be updated.
* @param time The duration of the frame - used for time based updates.
*
* @see org.flintparticles.common.actions.Action#update()
*/
override public function update( emitter:Emitter, particle:Particle, time:Number ):void
{
var p:Particle2D = Particle2D( particle );
var data:TweenToZoneData;
if( ! p.dictionary[this] )
{
var pt:Point = _zone.getLocation();
data = new TweenToZoneData( p.x, p.y, pt.x, pt.y );
p.dictionary[this] = data;
}
else
{
data = p.dictionary[this];
}
p.x = data.endX + data.diffX * p.energy;
p.y = data.endY + data.diffY * p.energy;
}
}
}
class TweenToZoneData
{
public var diffX:Number;
public var diffY:Number;
public var endX:Number;
public var endY:Number;
public function TweenToZoneData( startX:Number, startY:Number, endX:Number, endY:Number )
{
this.diffX = startX - endX;
this.diffY = startY - endY;
this.endX = endX;
this.endY = endY;
}
}
|
/*
* FLINT PARTICLE SYSTEM
* .....................
*
* Author: Richard Lord
* Copyright (c) Richard Lord 2008-2011
* http://flintparticles.org
*
*
* Licence Agreement
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.flintparticles.twoD.actions
{
import org.flintparticles.common.actions.ActionBase;
import org.flintparticles.common.emitters.Emitter;
import org.flintparticles.common.initializers.Initializer;
import org.flintparticles.common.particles.Particle;
import org.flintparticles.twoD.particles.Particle2D;
import org.flintparticles.twoD.zones.Zone2D;
import flash.geom.Point;
[DefaultProperty("zone")]
/**
* The TweenToZone action adjusts the particle's position between two
* locations as it ages. The start location is wherever the particle starts
* from, depending on the emitter and the initializers. The end position is
* a random point within the specified zone. The current position is relative
* to the particle's energy,
* which changes as the particle ages in accordance with the energy easing
* function used. This action should be used in conjunction with the Age action.
*/
public class TweenToZone extends ActionBase implements Initializer
{
private var _zone:Zone2D;
/**
* The constructor creates a TweenToZone action for use by an emitter.
* To add a TweenToZone to all particles created by an emitter, use the
* emitter's addAction method.
*
* @see org.flintparticles.common.emitters.Emitter#addAction()
*
* @param zone The zone for the particle's position when its energy is 0.
*/
public function TweenToZone( zone:Zone2D )
{
_zone = zone;
priority = -10;
}
/**
* The zone for the particle's position when its energy is 0.
*/
public function get zone():Zone2D
{
return _zone;
}
public function set zone( value:Zone2D ):void
{
_zone = value;
}
/**
*
*/
override public function addedToEmitter( emitter:Emitter ):void
{
if( ! emitter.hasInitializer( this ) )
{
emitter.addInitializer( this );
}
}
override public function removedFromEmitter( emitter:Emitter ):void
{
emitter.removeInitializer( this );
}
/**
*
*/
public function initialize( emitter:Emitter, particle:Particle ):void
{
var p:Particle2D = Particle2D( particle );
var pt:Point = _zone.getLocation();
var data:TweenToZoneData = new TweenToZoneData( p.x, p.y, pt.x, pt.y );
p.dictionary[this] = data;
}
/**
* Calculates the current position of the particle based on it's energy.
*
* <p>This method is called by the emitter and need not be called by the
* user.</p>
*
* @param emitter The Emitter that created the particle.
* @param particle The particle to be updated.
* @param time The duration of the frame - used for time based updates.
*
* @see org.flintparticles.common.actions.Action#update()
*/
override public function update( emitter:Emitter, particle:Particle, time:Number ):void
{
var p:Particle2D = Particle2D( particle );
if( ! p.dictionary[this] )
{
initialize( emitter, particle );
}
var data:TweenToZoneData = p.dictionary[this];
p.x = data.endX + data.diffX * p.energy;
p.y = data.endY + data.diffY * p.energy;
}
}
}
class TweenToZoneData
{
public var diffX:Number;
public var diffY:Number;
public var endX:Number;
public var endY:Number;
public function TweenToZoneData( startX:Number, startY:Number, endX:Number, endY:Number )
{
this.diffX = startX - endX;
this.diffY = startY - endY;
this.endX = endX;
this.endY = endY;
}
}
|
Modify TweenToZone to ensure it restarts each time
|
Modify TweenToZone to ensure it restarts each time
|
ActionScript
|
mit
|
richardlord/Flint
|
51e604f16e1b8d1530ea265e016425c187f8e93f
|
WEB-INF/lps/lfc/kernel/swf9/LzKeyboardKernel.as
|
WEB-INF/lps/lfc/kernel/swf9/LzKeyboardKernel.as
|
/**
* LzKeyboardKernel.lzs
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
// Receives keyboard events from the runtime
class LzKeyboardKernelClass
{
function __keyboardEvent ( e, t ){
var delta = {};
var s, k = e.keyCode;
var keyisdown = t == 'onkeydown';
s = String.fromCharCode(k).toLowerCase();
if (keyisdown) {
// prevent duplicate onkeydown events - see LPP-7432
if (k == __lastkeydown) return;
__lastkeydown = k;
} else {
__lastkeydown = null;
}
delta[s] = keyisdown;
if (this.__callback) this.__scope[this.__callback](delta, k, t);
}
var __callback = null;
var __scope = null;
var __lastkeydown = null;
function setCallback (scope, funcname) {
this.__scope = scope;
this.__callback = funcname;
}
// Called by lz.Keys when the last focusable element was reached.
function gotLastFocus() {
}
} // End of LzKeyboardKernelClass
var LzKeyboardKernel = new LzKeyboardKernelClass ();
|
/**
* LzKeyboardKernel.lzs
*
* @copyright Copyright 2001-2008 Laszlo Systems, Inc. All Rights Reserved.
* Use is subject to license terms.
*
* @topic Kernel
* @subtopic AS2
*/
// Receives keyboard events from the runtime
class LzKeyboardKernelClass
{
function __keyboardEvent ( e, t ){
var delta = {};
var s, k = e.keyCode;
var keyisdown = t == 'onkeydown';
s = String.fromCharCode(k).toLowerCase();
// prevent duplicate onkeydown events - see LPP-7432
if (__keyState[k] == keyisdown) return;
__keyState[k] = keyisdown;
delta[s] = keyisdown;
if (this.__callback) this.__scope[this.__callback](delta, k, t);
}
var __callback = null;
var __scope = null;
var __keyState:Object = {};
function setCallback (scope, funcname) {
this.__scope = scope;
this.__callback = funcname;
}
// Called by lz.Keys when the last focusable element was reached.
function gotLastFocus() {
}
} // End of LzKeyboardKernelClass
var LzKeyboardKernel = new LzKeyboardKernelClass ();
|
Change 20081218-maxcarlson-N by [email protected] on 2008-12-18 18:19:24 PST in /Users/maxcarlson/openlaszlo/trunk-clean for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20081218-maxcarlson-N by [email protected] on 2008-12-18 18:19:24 PST
in /Users/maxcarlson/openlaszlo/trunk-clean
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: Better prevention of duplicate key events in swf9
Bugs Fixed: LPP-7432 - onkeydown event keep firing
Technical Reviewer: [email protected]
QA Reviewer: promanik
Details: Use a hash to track keyboard state, to handle modifier keys accurately.
Tests: See LPP-7432
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@12194 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
a215954aa64ee11f31598ac92e002ee442f67942
|
HLSPlugin/src/com/kaltura/hls/m2ts/FLVTranscoder.as
|
HLSPlugin/src/com/kaltura/hls/m2ts/FLVTranscoder.as
|
package com.kaltura.hls.m2ts
{
import flash.utils.ByteArray;
import flash.net.ObjectEncoding;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
/**
* Responsible for emitting FLV data. Also handles AAC conversion
* config and buffering.
*/
public class FLVTranscoder
{
public const MIN_FILE_HEADER_BYTE_COUNT:int = 9;
public var callback:Function;
private var lastTagSize:uint = 0;
private var _aacConfig:ByteArray;
private var _aacRemainder:ByteArray;
private var _aacTimestamp:Number = 0;
public function clear(clearAACConfig:Boolean = false):void
{
if(clearAACConfig)
_aacConfig = null;
_aacRemainder = null;
_aacTimestamp = 0;
}
private function sendFLVTag(flvts:uint, type:uint, codec:int, mode:int, bytes:ByteArray, offset:uint, length:uint):void
{
var tag:ByteArray = new ByteArray();
tag.position = 0;
var msgLength:uint = length + ((codec >= 0) ? 1 : 0) + ((mode >= 0) ? 1 : 0);
var cursor:uint = 0;
if(msgLength > 0xffffff)
return; // too big for the length field
tag.length = FLVTags.HEADER_LENGTH + msgLength;
tag[cursor++] = type;
tag[cursor++] = (msgLength >> 16) & 0xff;
tag[cursor++] = (msgLength >> 8) & 0xff;
tag[cursor++] = (msgLength ) & 0xff;
tag[cursor++] = (flvts >> 16) & 0xff;
tag[cursor++] = (flvts >> 8) & 0xff;
tag[cursor++] = (flvts ) & 0xff;
tag[cursor++] = (flvts >> 24) & 0xff;
tag[cursor++] = 0x00; // stream ID
tag[cursor++] = 0x00;
tag[cursor++] = 0x00;
if(codec >= 0)
tag[cursor++] = codec;
if(mode >= 0)
tag[cursor++] = mode;
tag.position = cursor;
tag.writeBytes(bytes, offset, length);
cursor += length;
msgLength += 11; // account for message header in back pointer
tag.writeUnsignedInt(lastTagSize);
lastTagSize = tag.length;
// Dispatch tag.
if(callback != null)
callback(flvts, tag);
}
public function convertFLVTimestamp(pts:Number):Number
{
return pts / 90.0;
}
private static var flvGenerationBuffer:ByteArray = new ByteArray();
private static var keyFrame:Boolean = false;
private static var totalAppended:int = 0;
private function naluConverter(bytes:ByteArray, cursor:uint, length:uint):void
{
// Check for a NALU that is keyframe type.
var naluType:uint = bytes[cursor] & 0x1f;
trace(naluType + " length=" + length);
switch(naluType)
{
case 0x09: // "access unit delimiter"
switch((bytes[cursor + 1] >> 5) & 0x07) // access unit type
{
case 0:
case 3:
case 5:
keyFrame = true;
break;
default:
keyFrame = false;
break;
}
break;
default:
// Infer keyframe state.
if(naluType == 5)
keyFrame = true;
else if(naluType == 1)
keyFrame = false;
}
// Append.
flvGenerationBuffer.writeUnsignedInt(length);
flvGenerationBuffer.writeBytes(bytes, cursor, length);
totalAppended += length;
}
/**
* Convert and amit AVC NALU data.
*/
public function convert(unit:NALU):void
{
// Accumulate NALUs into buffer.
flvGenerationBuffer.length = 3;
flvGenerationBuffer[0] = (tsu >> 16) & 0xff;
flvGenerationBuffer[1] = (tsu >> 8) & 0xff;
flvGenerationBuffer[2] = (tsu ) & 0xff;
flvGenerationBuffer.position = 3;
totalAppended = 0;
keyFrame = false;
// Emit an AVCC and walk the NALUs.
var avcc:ByteArray = NALUProcessor.extractAVCC(unit, naluConverter);
if(avcc)
sendFLVTag(convertFLVTimestamp(unit.pts), FLVTags.TYPE_VIDEO, FLVTags.VIDEO_CODEC_AVC_KEYFRAME, FLVTags.AVC_MODE_AVCC, avcc, 0, avcc.length);
trace("Appended " + totalAppended + " bytes");
// Finish writing and sending packet.
var flvts:uint = convertFLVTimestamp(unit.pts);
var tsu:uint = convertFLVTimestamp(unit.pts - unit.dts);
var codec:uint;
if(keyFrame)
codec = FLVTags.VIDEO_CODEC_AVC_KEYFRAME;
else
codec = FLVTags.VIDEO_CODEC_AVC_PREDICTIVEFRAME;
//trace("ts=" + flvts + " tsu=" + tsu + " keyframe = " + keyFrame);
sendFLVTag(flvts, FLVTags.TYPE_VIDEO, codec, FLVTags.AVC_MODE_PICTURE, flvGenerationBuffer, 0, flvGenerationBuffer.length);
}
private function compareBytesHelper(b1:ByteArray, b2:ByteArray):Boolean
{
var curPos:uint;
if(b1.length != b2.length)
return false;
for(curPos = 0; curPos < b1.length; curPos++)
{
if(b1[curPos] != b2[curPos])
return false;
}
return true;
}
private function sendAACConfigFLVTag(flvts:uint, profile:uint, sampleRateIndex:uint, channelConfig:uint):void
{
var isNewConfig:Boolean = true;
var audioSpecificConfig:ByteArray = new ByteArray();
var audioObjectType:uint;
audioSpecificConfig.length = 2;
switch(profile)
{
case 0x00:
audioObjectType = 0x01;
break;
case 0x01:
audioObjectType = 0x02;
break;
case 0x02:
audioObjectType = 0x03;
break;
default:
return;
}
audioSpecificConfig[0] = ((audioObjectType << 3) & 0xf8) + ((sampleRateIndex >> 1) & 0x07);
audioSpecificConfig[1] = ((sampleRateIndex << 7) & 0x80) + ((channelConfig << 3) & 0x78);
if(_aacConfig && compareBytesHelper(_aacConfig, audioSpecificConfig))
isNewConfig = false;
if(!isNewConfig)
return;
_aacConfig = audioSpecificConfig;
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_CONFIG, _aacConfig, 0, _aacConfig.length);
}
/**
* Convert and amit AAC data.
*/
public function convertAAC(pes:PESPacket):void
{
var timeAccumulation:Number = 0.0;
var limit:uint;
var stream:ByteArray;
var hadRemainder:Boolean = false;
var cursor:int = 0;
var length:int = pes.buffer.length;
var bytes:ByteArray = pes.buffer;
var timestamp:Number = pes.pts;
if(_aacRemainder)
{
stream = _aacRemainder;
stream.writeBytes(bytes, cursor, length);
cursor = 0;
length = stream.length;
_aacRemainder = null;
hadRemainder = true;
timeAccumulation = _aacTimestamp - timestamp;
}
else
stream = bytes;
limit = cursor + length;
// an AAC PES packet can contain multiple ADTS frames
while(cursor < limit)
{
var remaining:uint = limit - cursor;
var sampleRateIndex:uint;
var sampleRate:Number = undefined;
var profile:uint;
var channelConfig:uint;
var frameLength:uint;
if(remaining < FLVTags.ADTS_FRAME_HEADER_LENGTH)
break;
// search for syncword
if(stream[cursor] != 0xff || (stream[cursor + 1] & 0xf0) != 0xf0)
{
cursor++;
continue;
}
frameLength = (stream[cursor + 3] & 0x03) << 11;
frameLength += (stream[cursor + 4]) << 3;
frameLength += (stream[cursor + 5] >> 5) & 0x07;
// Check for an invalid ADTS header; if so look for next syncword.
if(frameLength < FLVTags.ADTS_FRAME_HEADER_LENGTH)
{
cursor++;
continue;
}
// Skip it till next PES packet.
if(frameLength > remaining)
break;
profile = (stream[cursor + 2] >> 6) & 0x03;
sampleRateIndex = (stream[cursor + 2] >> 2) & 0x0f;
switch(sampleRateIndex)
{
case 0x00:
sampleRate = 96000.0;
break;
case 0x01:
sampleRate = 88200.0;
break;
case 0x02:
sampleRate = 64000.0;
break;
case 0x03:
sampleRate = 48000.0;
break;
case 0x04:
sampleRate = 44100.0;
break;
case 0x05:
sampleRate = 32000.0;
break;
case 0x06:
sampleRate = 24000.0;
break;
case 0x07:
sampleRate = 22050.0;
break;
case 0x08:
sampleRate = 16000.0;
break;
case 0x09:
sampleRate = 12000.0;
break;
case 0x0a:
sampleRate = 11025.0;
break;
case 0x0b:
sampleRate = 8000.0;
break;
case 0x0c:
sampleRate = 7350.0;
break;
}
channelConfig = ((stream[cursor + 2] & 0x01) << 2) + ((stream[cursor + 3] >> 6) & 0x03);
if(sampleRate)
{
var flvts:uint = convertFLVTimestamp(timestamp + timeAccumulation);
sendAACConfigFLVTag(flvts, profile, sampleRateIndex, channelConfig);
//trace("Sending AAC");
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_FRAME, stream, cursor + FLVTags.ADTS_FRAME_HEADER_LENGTH, frameLength - FLVTags.ADTS_FRAME_HEADER_LENGTH);
timeAccumulation += (1024.0 / sampleRate) * 90000.0; // account for the duration of this frame
if(hadRemainder)
{
timeAccumulation = 0.0;
hadRemainder = false;
}
}
cursor += frameLength;
}
if(cursor < limit)
{
//trace("AAC timestamp was " + _aacTimestamp);
_aacRemainder = new ByteArray();
_aacRemainder.writeBytes(stream, cursor, limit - cursor);
_aacTimestamp = timestamp + timeAccumulation;
//trace("AAC timestamp now " + _aacTimestamp);
}
}
/**
* Convert and amit MP3 data.
*/
public function convertMP3(pes:PESPacket):void
{
sendFLVTag(convertFLVTimestamp(pes.pts), FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_MP3, -1, pes.buffer, 0, pes.buffer.length);
}
private function generateScriptData(values:Array):ByteArray
{
var bytes:ByteArray = new ByteArray();
bytes.objectEncoding = ObjectEncoding.AMF0;
for each (var object:Object in values)
bytes.writeObject(object);
return bytes;
}
private function sendScriptDataFLVTag(flvts:uint, values:Array):void
{
var bytes:ByteArray = generateScriptData(values);
sendFLVTag(flvts, FLVTags.TYPE_SCRIPTDATA, -1, -1, bytes, 0, bytes.length);
}
/**
* Fire off a subtitle caption.
*/
public function createAndSendCaptionMessage( timeStamp:Number, captionBuffer:String, lang:String="", textid:Number=99):void
{
//var captionObject:Array = ["onCaptionInfo", { type:"WebVTT", data:captionBuffer }];
//sendScriptDataFLVTag( timeStamp * 1000, captionObject);
// We need to strip the timestamp off of the text data
captionBuffer = captionBuffer.slice(captionBuffer.indexOf('\n') + 1);
var subtitleObject:Array = ["onTextData", { text:captionBuffer, language:lang, trackid:textid }];
sendScriptDataFLVTag( timeStamp * 1000, subtitleObject);
}
}
}
|
package com.kaltura.hls.m2ts
{
import flash.utils.ByteArray;
import flash.net.ObjectEncoding;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
/**
* Responsible for emitting FLV data. Also handles AAC conversion
* config and buffering.
*/
public class FLVTranscoder
{
public const MIN_FILE_HEADER_BYTE_COUNT:int = 9;
public var callback:Function;
private var lastTagSize:uint = 0;
private var _aacConfig:ByteArray;
private var _aacRemainder:ByteArray;
private var _aacTimestamp:Number = 0;
public function clear(clearAACConfig:Boolean = false):void
{
if(clearAACConfig)
_aacConfig = null;
_aacRemainder = null;
_aacTimestamp = 0;
}
private function sendFLVTag(flvts:uint, type:uint, codec:int, mode:int, bytes:ByteArray, offset:uint, length:uint):void
{
var tag:ByteArray = new ByteArray();
tag.position = 0;
var msgLength:uint = length + ((codec >= 0) ? 1 : 0) + ((mode >= 0) ? 1 : 0);
var cursor:uint = 0;
if(msgLength > 0xffffff)
return; // too big for the length field
tag.length = FLVTags.HEADER_LENGTH + msgLength;
tag[cursor++] = type;
tag[cursor++] = (msgLength >> 16) & 0xff;
tag[cursor++] = (msgLength >> 8) & 0xff;
tag[cursor++] = (msgLength ) & 0xff;
tag[cursor++] = (flvts >> 16) & 0xff;
tag[cursor++] = (flvts >> 8) & 0xff;
tag[cursor++] = (flvts ) & 0xff;
tag[cursor++] = (flvts >> 24) & 0xff;
tag[cursor++] = 0x00; // stream ID
tag[cursor++] = 0x00;
tag[cursor++] = 0x00;
if(codec >= 0)
tag[cursor++] = codec;
if(mode >= 0)
tag[cursor++] = mode;
tag.position = cursor;
tag.writeBytes(bytes, offset, length);
cursor += length;
msgLength += 11; // account for message header in back pointer
tag.writeUnsignedInt(lastTagSize);
lastTagSize = tag.length;
// Dispatch tag.
if(callback != null)
callback(flvts, tag);
}
public function convertFLVTimestamp(pts:Number):Number
{
return pts / 90.0;
}
private static var flvGenerationBuffer:ByteArray = new ByteArray();
private static var keyFrame:Boolean = false;
private static var totalAppended:int = 0;
private function naluConverter(bytes:ByteArray, cursor:uint, length:uint):void
{
// Check for a NALU that is keyframe type.
var naluType:uint = bytes[cursor] & 0x1f;
//trace(naluType + " length=" + length);
switch(naluType)
{
case 0x09: // "access unit delimiter"
switch((bytes[cursor + 1] >> 5) & 0x07) // access unit type
{
case 0:
case 3:
case 5:
keyFrame = true;
break;
default:
keyFrame = false;
break;
}
break;
default:
// Infer keyframe state.
if(naluType == 5)
keyFrame = true;
else if(naluType == 1)
keyFrame = false;
}
// Append.
flvGenerationBuffer.writeUnsignedInt(length);
flvGenerationBuffer.writeBytes(bytes, cursor, length);
totalAppended += length;
}
/**
* Convert and amit AVC NALU data.
*/
public function convert(unit:NALU):void
{
// Accumulate NALUs into buffer.
flvGenerationBuffer.length = 3;
flvGenerationBuffer[0] = (tsu >> 16) & 0xff;
flvGenerationBuffer[1] = (tsu >> 8) & 0xff;
flvGenerationBuffer[2] = (tsu ) & 0xff;
flvGenerationBuffer.position = 3;
totalAppended = 0;
keyFrame = false;
// Emit an AVCC and walk the NALUs.
var avcc:ByteArray = NALUProcessor.extractAVCC(unit, naluConverter);
if(avcc)
sendFLVTag(convertFLVTimestamp(unit.pts), FLVTags.TYPE_VIDEO, FLVTags.VIDEO_CODEC_AVC_KEYFRAME, FLVTags.AVC_MODE_AVCC, avcc, 0, avcc.length);
// trace("Appended " + totalAppended + " bytes");
// Finish writing and sending packet.
var flvts:uint = convertFLVTimestamp(unit.pts);
var tsu:uint = convertFLVTimestamp(unit.pts - unit.dts);
var codec:uint;
if(keyFrame)
codec = FLVTags.VIDEO_CODEC_AVC_KEYFRAME;
else
codec = FLVTags.VIDEO_CODEC_AVC_PREDICTIVEFRAME;
//trace("ts=" + flvts + " tsu=" + tsu + " keyframe = " + keyFrame);
sendFLVTag(flvts, FLVTags.TYPE_VIDEO, codec, FLVTags.AVC_MODE_PICTURE, flvGenerationBuffer, 0, flvGenerationBuffer.length);
}
private function compareBytesHelper(b1:ByteArray, b2:ByteArray):Boolean
{
var curPos:uint;
if(b1.length != b2.length)
return false;
for(curPos = 0; curPos < b1.length; curPos++)
{
if(b1[curPos] != b2[curPos])
return false;
}
return true;
}
private function sendAACConfigFLVTag(flvts:uint, profile:uint, sampleRateIndex:uint, channelConfig:uint):void
{
var isNewConfig:Boolean = true;
var audioSpecificConfig:ByteArray = new ByteArray();
var audioObjectType:uint;
audioSpecificConfig.length = 2;
switch(profile)
{
case 0x00:
audioObjectType = 0x01;
break;
case 0x01:
audioObjectType = 0x02;
break;
case 0x02:
audioObjectType = 0x03;
break;
default:
return;
}
audioSpecificConfig[0] = ((audioObjectType << 3) & 0xf8) + ((sampleRateIndex >> 1) & 0x07);
audioSpecificConfig[1] = ((sampleRateIndex << 7) & 0x80) + ((channelConfig << 3) & 0x78);
if(_aacConfig && compareBytesHelper(_aacConfig, audioSpecificConfig))
isNewConfig = false;
if(!isNewConfig)
return;
_aacConfig = audioSpecificConfig;
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_CONFIG, _aacConfig, 0, _aacConfig.length);
}
/**
* Convert and amit AAC data.
*/
public function convertAAC(pes:PESPacket):void
{
var timeAccumulation:Number = 0.0;
var limit:uint;
var stream:ByteArray;
var hadRemainder:Boolean = false;
var cursor:int = 0;
var length:int = pes.buffer.length;
var bytes:ByteArray = pes.buffer;
var timestamp:Number = pes.pts;
if(_aacRemainder)
{
stream = _aacRemainder;
stream.writeBytes(bytes, cursor, length);
cursor = 0;
length = stream.length;
_aacRemainder = null;
hadRemainder = true;
timeAccumulation = _aacTimestamp - timestamp;
}
else
stream = bytes;
limit = cursor + length;
// an AAC PES packet can contain multiple ADTS frames
while(cursor < limit)
{
var remaining:uint = limit - cursor;
var sampleRateIndex:uint;
var sampleRate:Number = undefined;
var profile:uint;
var channelConfig:uint;
var frameLength:uint;
if(remaining < FLVTags.ADTS_FRAME_HEADER_LENGTH)
break;
// search for syncword
if(stream[cursor] != 0xff || (stream[cursor + 1] & 0xf0) != 0xf0)
{
cursor++;
continue;
}
frameLength = (stream[cursor + 3] & 0x03) << 11;
frameLength += (stream[cursor + 4]) << 3;
frameLength += (stream[cursor + 5] >> 5) & 0x07;
// Check for an invalid ADTS header; if so look for next syncword.
if(frameLength < FLVTags.ADTS_FRAME_HEADER_LENGTH)
{
cursor++;
continue;
}
// Skip it till next PES packet.
if(frameLength > remaining)
break;
profile = (stream[cursor + 2] >> 6) & 0x03;
sampleRateIndex = (stream[cursor + 2] >> 2) & 0x0f;
switch(sampleRateIndex)
{
case 0x00:
sampleRate = 96000.0;
break;
case 0x01:
sampleRate = 88200.0;
break;
case 0x02:
sampleRate = 64000.0;
break;
case 0x03:
sampleRate = 48000.0;
break;
case 0x04:
sampleRate = 44100.0;
break;
case 0x05:
sampleRate = 32000.0;
break;
case 0x06:
sampleRate = 24000.0;
break;
case 0x07:
sampleRate = 22050.0;
break;
case 0x08:
sampleRate = 16000.0;
break;
case 0x09:
sampleRate = 12000.0;
break;
case 0x0a:
sampleRate = 11025.0;
break;
case 0x0b:
sampleRate = 8000.0;
break;
case 0x0c:
sampleRate = 7350.0;
break;
}
channelConfig = ((stream[cursor + 2] & 0x01) << 2) + ((stream[cursor + 3] >> 6) & 0x03);
if(sampleRate)
{
var flvts:uint = convertFLVTimestamp(timestamp + timeAccumulation);
sendAACConfigFLVTag(flvts, profile, sampleRateIndex, channelConfig);
//trace("Sending AAC");
sendFLVTag(flvts, FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_AAC, FLVTags.AAC_MODE_FRAME, stream, cursor + FLVTags.ADTS_FRAME_HEADER_LENGTH, frameLength - FLVTags.ADTS_FRAME_HEADER_LENGTH);
timeAccumulation += (1024.0 / sampleRate) * 90000.0; // account for the duration of this frame
if(hadRemainder)
{
timeAccumulation = 0.0;
hadRemainder = false;
}
}
cursor += frameLength;
}
if(cursor < limit)
{
//trace("AAC timestamp was " + _aacTimestamp);
_aacRemainder = new ByteArray();
_aacRemainder.writeBytes(stream, cursor, limit - cursor);
_aacTimestamp = timestamp + timeAccumulation;
//trace("AAC timestamp now " + _aacTimestamp);
}
}
/**
* Convert and amit MP3 data.
*/
public function convertMP3(pes:PESPacket):void
{
sendFLVTag(convertFLVTimestamp(pes.pts), FLVTags.TYPE_AUDIO, FLVTags.AUDIO_CODEC_MP3, -1, pes.buffer, 0, pes.buffer.length);
}
private function generateScriptData(values:Array):ByteArray
{
var bytes:ByteArray = new ByteArray();
bytes.objectEncoding = ObjectEncoding.AMF0;
for each (var object:Object in values)
bytes.writeObject(object);
return bytes;
}
private function sendScriptDataFLVTag(flvts:uint, values:Array):void
{
var bytes:ByteArray = generateScriptData(values);
sendFLVTag(flvts, FLVTags.TYPE_SCRIPTDATA, -1, -1, bytes, 0, bytes.length);
}
/**
* Fire off a subtitle caption.
*/
public function createAndSendCaptionMessage( timeStamp:Number, captionBuffer:String, lang:String="", textid:Number=99):void
{
//var captionObject:Array = ["onCaptionInfo", { type:"WebVTT", data:captionBuffer }];
//sendScriptDataFLVTag( timeStamp * 1000, captionObject);
// We need to strip the timestamp off of the text data
captionBuffer = captionBuffer.slice(captionBuffer.indexOf('\n') + 1);
var subtitleObject:Array = ["onTextData", { text:captionBuffer, language:lang, trackid:textid }];
sendScriptDataFLVTag( timeStamp * 1000, subtitleObject);
}
}
}
|
Disable some spam.
|
Disable some spam.
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
6537ef90bbaecb493736f7a22bc92628c9fbf360
|
src/aerys/minko/render/shader/Shader.as
|
src/aerys/minko/render/shader/Shader.as
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko;
import aerys.minko.render.renderer.state.RendererState;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.Texture3DResource;
import aerys.minko.render.shader.compiler.Compiler;
import aerys.minko.render.shader.compiler.allocator.ParameterAllocation;
import aerys.minko.render.shader.node.INode;
import aerys.minko.render.shader.node.leaf.AbstractParameter;
import aerys.minko.render.shader.node.leaf.StyleParameter;
import aerys.minko.render.shader.node.leaf.TransformParameter;
import aerys.minko.render.shader.node.leaf.WorldParameter;
import aerys.minko.scene.data.StyleStack;
import aerys.minko.scene.data.TransformData;
import aerys.minko.scene.data.ViewportData;
import aerys.minko.type.math.Matrix3D;
import aerys.minko.type.math.Vector4;
import aerys.minko.type.stream.format.VertexComponent;
import flash.geom.Vector3D;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
import flash.utils.getTimer;
public class Shader
{
use namespace minko;
protected var _resource : Program3DResource;
protected var _lastFrameId : uint;
protected var _lastStyleStackVersion : uint;
protected var _lastTransformVersion : uint;
protected var _vsConstData : Vector.<Number>;
protected var _fsConstData : Vector.<Number>;
protected var _vsParams : Vector.<ParameterAllocation>;
protected var _fsParams : Vector.<ParameterAllocation>;
protected var _samplers : Vector.<int>;
public function get resource() : Program3DResource
{
return _resource;
}
public static function create(outputPosition : INode,
outputColor : INode) : Shader
{
var compiler : Compiler = new Compiler();
compiler.load(outputPosition, outputColor);
return compiler.compileShader();
}
public function Shader(vertexShader : ByteArray,
fragmentShader : ByteArray,
vertexInputComponents : Vector.<VertexComponent>,
vertexInputIndices : Vector.<uint>,
samplers : Vector.<int>,
vertexConstantData : Vector.<Number>,
fragmentConstantData : Vector.<Number>,
vertexParameters : Vector.<ParameterAllocation>,
fragmentParameters : Vector.<ParameterAllocation>)
{
_lastFrameId = uint.MAX_VALUE;
_lastStyleStackVersion = uint.MAX_VALUE;
_lastTransformVersion = uint.MAX_VALUE;
_vsConstData = vertexConstantData;
_fsConstData = fragmentConstantData;
_vsParams = vertexParameters;
_fsParams = fragmentParameters;
_samplers = samplers;
_resource = new Program3DResource(vertexShader, fragmentShader, vertexInputComponents, vertexInputIndices);
}
public function fillRenderState(state : RendererState,
styleStack : StyleStack,
local : TransformData,
world : Dictionary) : Boolean
{
if (_lastFrameId != world[ViewportData].frameId)
{
_lastFrameId = world[ViewportData].frameId;
_lastStyleStackVersion = uint.MAX_VALUE;
_lastTransformVersion = uint.MAX_VALUE;
}
setTextures(state, styleStack, local, world);
setConstants(state, styleStack, local, world);
state.shader = _resource;
_lastStyleStackVersion = styleStack.version;
_lastTransformVersion = local.version;
return true;
}
protected function setTextures(state : RendererState,
styleStack : StyleStack,
transformData : TransformData,
worldData : Object) : void
{
var texture : Texture3DResource = null;
var samplerStyleId : int = 0;
var samplerCount : uint = _samplers.length;
for (var i : int = 0; i < samplerCount; ++i)
{
samplerStyleId = _samplers[i];
texture = styleStack.get(samplerStyleId) as Texture3DResource;
state.setTextureAt(i, texture);
}
}
protected function setConstants(state : RendererState,
styleStack : StyleStack,
local : TransformData,
world : Dictionary) : void
{
updateConstData(_vsConstData, _vsParams, styleStack, local, world);
updateConstData(_fsConstData, _fsParams, styleStack, local, world);
state.setVertexConstants(_vsConstData);
state.setFragmentConstants(_fsConstData);
}
protected function updateConstData(constData : Vector.<Number>,
paramsAllocs : Vector.<ParameterAllocation>,
styleStack : StyleStack,
local : TransformData,
world : Dictionary) : void
{
var paramLength : int = paramsAllocs.length;
for (var i : int = 0; i < paramLength; ++i)
{
var paramAlloc : ParameterAllocation = paramsAllocs[i];
var param : AbstractParameter = paramAlloc._parameter;
if ((param is StyleParameter && styleStack.version == _lastStyleStackVersion) ||
(param is TransformParameter && local.version == _lastTransformVersion))
continue;
var data : Object = getParameterData(param, styleStack, local, world);
loadParameterData(paramAlloc, constData, data);
}
}
private function getParameterData(param : AbstractParameter,
styleStack : StyleStack,
local : TransformData,
world : Dictionary) : Object
{
if (param is StyleParameter)
{
if (param._index != -1)
return styleStack.get(param._key as int).getItem(param._index)[param._field];
else if (param._field != null)
return styleStack.get(param._key as int)[param._field];
else
return styleStack.get(param._key as int, null);
}
else if (param is WorldParameter)
{
var paramClass : Class = WorldParameter(param)._class;
if (param._index != -1)
return world[paramClass].getItem(param._index)[param._field];
else if (param._field != null)
return world[paramClass][param._field];
else
return world[paramClass];
}
else if (param is TransformParameter)
{
return local[param._key];
}
else
throw new Error('Unknown parameter type');
}
private function loadParameterData(paramAlloc : ParameterAllocation,
constData : Vector.<Number>,
data : Object) : void
{
var offset : uint = paramAlloc._offset;
var size : uint = paramAlloc._parameter._size;
// if (data is int)
if (data is Number)
{
//var intData : int = data as int;
var intData : Number = data as Number;
if (size == 1)
{
constData[offset] = intData;
}
else if (size == 2)
{
constData[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff);
constData[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff);
}
else if (size == 3)
{
constData[offset] = ((intData & 0xFF0000) >>> 16) / 255.;
constData[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.;
constData[int(offset + 2)] = (intData & 0x0000FF) / 255.;
}
else if (size == 4)
{
constData[offset] = ((intData & 0xFF000000) >>> 24) / 255.;
constData[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.;
constData[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.;
constData[int(offset + 3)] = ((intData & 0x000000FF)) / 255.;
}
}
/*else if (data is uint)
{
var uintData : uint = data as uint;
if (size == 1)
{
constData[offset] = uintData;
}
else if (size == 2)
{
constData[offset] = ((uintData & 0xFFFF0000) >>> 16) / Number(0xffff);
constData[int(offset + 2)] = (uintData & 0x0000FFFF) / Number(0xffff);
}
else if (size == 3)
{
constData[offset] = ((uintData & 0xFF0000) >>> 16) / 255.;
constData[int(offset + 1)] = ((uintData & 0x00FF00) >>> 8) / 255.;
constData[int(offset + 2)] = (uintData & 0x0000FF) / 255.;
}
else if (size == 4)
{
constData[offset] = ((uintData & 0xFF000000) >>> 24) / 255.;
constData[int(offset + 1)] = ((uintData & 0x00FF0000) >>> 16) / 255.;
constData[int(offset + 2)] = ((uintData & 0x0000FF00) >>> 8) / 255.;
constData[int(offset + 3)] = ((uintData & 0x000000FF)) / 255.;
}
}*/
/*else if (data is Number)
{
if (size != 1)
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'defined as size=' + size + ' but only a Number was found');
constData[offset] = data as Number;
}*/
else if (data is Vector4)
{
var vectorData : Vector3D = (data as Vector4)._vector;
constData[offset] = vectorData.x;
size >= 2 && (constData[int(offset + 1)] = vectorData.y);
size >= 3 && (constData[int(offset + 2)] = vectorData.z);
size >= 4 && (constData[int(offset + 3)] = vectorData.w);
}
else if (data is Matrix3D)
{
(data as Matrix3D).getRawData(constData, offset, true);
}
else if (data is Vector.<Vector4>)
{
var vectorVectorData : Vector.<Vector4> = data as Vector.<Vector4>;
var vectorVectorDataLength : uint = vectorVectorData.length;
for (var j : uint = 0; j < vectorVectorDataLength; ++j)
{
vectorData = vectorVectorData[j]._vector;
constData[offset + 4 * j] = vectorData.x;
constData[int(offset + 4 * j + 1)] = vectorData.y;
constData[int(offset + 4 * j + 2)] = vectorData.z;
constData[int(offset + 4 * j + 3)] = vectorData.w;
}
}
else if (data is Vector.<Matrix3D>)
{
var matrixVectorData : Vector.<Matrix3D> = data as Vector.<Matrix3D>;
var matrixVectorDataLength : uint = matrixVectorData.length;
for (var i : uint = 0; i < matrixVectorDataLength; ++i)
matrixVectorData[i].getRawData(constData, offset + i * 16, true);
}
else if (data == null)
{
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'null and required by automatic shader');
}
else
{
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'neither a int, a Number, a Vector4 or a Matrix3D. Unable to ' +
'map it to a shader constant.');
}
}
}
}
|
package aerys.minko.render.shader
{
import aerys.minko.ns.minko;
import aerys.minko.render.renderer.state.RendererState;
import aerys.minko.render.resource.Program3DResource;
import aerys.minko.render.resource.Texture3DResource;
import aerys.minko.render.shader.compiler.Compiler;
import aerys.minko.render.shader.compiler.allocator.ParameterAllocation;
import aerys.minko.render.shader.node.INode;
import aerys.minko.render.shader.node.leaf.AbstractParameter;
import aerys.minko.render.shader.node.leaf.StyleParameter;
import aerys.minko.render.shader.node.leaf.TransformParameter;
import aerys.minko.render.shader.node.leaf.WorldParameter;
import aerys.minko.scene.data.StyleStack;
import aerys.minko.scene.data.TransformData;
import aerys.minko.scene.data.ViewportData;
import aerys.minko.type.math.Matrix3D;
import aerys.minko.type.math.Vector4;
import aerys.minko.type.stream.format.VertexComponent;
import flash.geom.Vector3D;
import flash.utils.ByteArray;
import flash.utils.Dictionary;
public class Shader
{
use namespace minko;
protected var _resource : Program3DResource;
protected var _lastFrameId : uint;
protected var _lastStyleStackVersion : uint;
protected var _lastTransformVersion : uint;
protected var _vsConstData : Vector.<Number>;
protected var _fsConstData : Vector.<Number>;
protected var _vsParams : Vector.<ParameterAllocation>;
protected var _fsParams : Vector.<ParameterAllocation>;
protected var _samplers : Vector.<int>;
public function get resource() : Program3DResource
{
return _resource;
}
public static function create(outputPosition : INode,
outputColor : INode) : Shader
{
var compiler : Compiler = new Compiler();
compiler.load(outputPosition, outputColor);
return compiler.compileShader();
}
public function Shader(vertexShader : ByteArray,
fragmentShader : ByteArray,
vertexInputComponents : Vector.<VertexComponent>,
vertexInputIndices : Vector.<uint>,
samplers : Vector.<int>,
vertexConstantData : Vector.<Number>,
fragmentConstantData : Vector.<Number>,
vertexParameters : Vector.<ParameterAllocation>,
fragmentParameters : Vector.<ParameterAllocation>)
{
_lastFrameId = uint.MAX_VALUE;
_lastStyleStackVersion = uint.MAX_VALUE;
_lastTransformVersion = uint.MAX_VALUE;
_vsConstData = vertexConstantData;
_fsConstData = fragmentConstantData;
_vsParams = vertexParameters;
_fsParams = fragmentParameters;
_samplers = samplers;
_resource = new Program3DResource(vertexShader, fragmentShader, vertexInputComponents, vertexInputIndices);
}
public function fillRenderState(state : RendererState,
styleStack : StyleStack,
local : TransformData,
world : Dictionary) : Boolean
{
if (_lastFrameId != world[ViewportData].frameId)
{
_lastFrameId = world[ViewportData].frameId;
_lastStyleStackVersion = uint.MAX_VALUE;
_lastTransformVersion = uint.MAX_VALUE;
}
setTextures(state, styleStack, local, world);
setConstants(state, styleStack, local, world);
state.shader = _resource;
_lastStyleStackVersion = styleStack.version;
_lastTransformVersion = local.version;
return true;
}
protected function setTextures(state : RendererState,
styleStack : StyleStack,
transformData : TransformData,
worldData : Object) : void
{
var texture : Texture3DResource = null;
var samplerStyleId : int = 0;
var samplerCount : uint = _samplers.length;
for (var i : int = 0; i < samplerCount; ++i)
{
samplerStyleId = _samplers[i];
texture = styleStack.get(samplerStyleId) as Texture3DResource;
state.setTextureAt(i, texture);
}
}
protected function setConstants(state : RendererState,
styleStack : StyleStack,
local : TransformData,
world : Dictionary) : void
{
updateConstData(_vsConstData, _vsParams, styleStack, local, world);
updateConstData(_fsConstData, _fsParams, styleStack, local, world);
state.setVertexConstants(_vsConstData);
state.setFragmentConstants(_fsConstData);
}
protected function updateConstData(constData : Vector.<Number>,
paramsAllocs : Vector.<ParameterAllocation>,
styleStack : StyleStack,
local : TransformData,
world : Dictionary) : void
{
var paramLength : int = paramsAllocs.length;
for (var i : int = 0; i < paramLength; ++i)
{
var paramAlloc : ParameterAllocation = paramsAllocs[i];
var param : AbstractParameter = paramAlloc._parameter;
if ((param is StyleParameter && styleStack.version == _lastStyleStackVersion) ||
(param is TransformParameter && local.version == _lastTransformVersion))
continue;
var data : Object = getParameterData(param, styleStack, local, world);
loadParameterData(paramAlloc, constData, data);
}
}
private function getParameterData(param : AbstractParameter,
styleStack : StyleStack,
local : TransformData,
world : Dictionary) : Object
{
if (param is StyleParameter)
{
if (param._index != -1)
return styleStack.get(param._key as int).getItem(param._index)[param._field];
else if (param._field != null)
return styleStack.get(param._key as int)[param._field];
else
return styleStack.get(param._key as int, null);
}
else if (param is WorldParameter)
{
var paramClass : Class = WorldParameter(param)._class;
if (param._index != -1)
return world[paramClass].getItem(param._index)[param._field];
else if (param._field != null)
return world[paramClass][param._field];
else
return world[paramClass];
}
else if (param is TransformParameter)
{
return local[param._key];
}
else
throw new Error('Unknown parameter type');
}
private function loadParameterData(paramAlloc : ParameterAllocation,
constData : Vector.<Number>,
data : Object) : void
{
var offset : uint = paramAlloc._offset;
var size : uint = paramAlloc._parameter._size;
// if (data is int)
if (data is Number)
{
//var intData : int = data as int;
var intData : Number = data as Number;
if (size == 1)
{
constData[offset] = intData;
}
else if (size == 2)
{
constData[offset] = ((intData & 0xFFFF0000) >>> 16) / Number(0xffff);
constData[int(offset + 2)] = (intData & 0x0000FFFF) / Number(0xffff);
}
else if (size == 3)
{
constData[offset] = ((intData & 0xFF0000) >>> 16) / 255.;
constData[int(offset + 1)] = ((intData & 0x00FF00) >>> 8) / 255.;
constData[int(offset + 2)] = (intData & 0x0000FF) / 255.;
}
else if (size == 4)
{
constData[offset] = ((intData & 0xFF000000) >>> 24) / 255.;
constData[int(offset + 1)] = ((intData & 0x00FF0000) >>> 16) / 255.;
constData[int(offset + 2)] = ((intData & 0x0000FF00) >>> 8) / 255.;
constData[int(offset + 3)] = ((intData & 0x000000FF)) / 255.;
}
}
/*else if (data is uint)
{
var uintData : uint = data as uint;
if (size == 1)
{
constData[offset] = uintData;
}
else if (size == 2)
{
constData[offset] = ((uintData & 0xFFFF0000) >>> 16) / Number(0xffff);
constData[int(offset + 2)] = (uintData & 0x0000FFFF) / Number(0xffff);
}
else if (size == 3)
{
constData[offset] = ((uintData & 0xFF0000) >>> 16) / 255.;
constData[int(offset + 1)] = ((uintData & 0x00FF00) >>> 8) / 255.;
constData[int(offset + 2)] = (uintData & 0x0000FF) / 255.;
}
else if (size == 4)
{
constData[offset] = ((uintData & 0xFF000000) >>> 24) / 255.;
constData[int(offset + 1)] = ((uintData & 0x00FF0000) >>> 16) / 255.;
constData[int(offset + 2)] = ((uintData & 0x0000FF00) >>> 8) / 255.;
constData[int(offset + 3)] = ((uintData & 0x000000FF)) / 255.;
}
}*/
/*else if (data is Number)
{
if (size != 1)
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'defined as size=' + size + ' but only a Number was found');
constData[offset] = data as Number;
}*/
else if (data is Vector4)
{
var vectorData : Vector3D = (data as Vector4)._vector;
constData[offset] = vectorData.x;
size >= 2 && (constData[int(offset + 1)] = vectorData.y);
size >= 3 && (constData[int(offset + 2)] = vectorData.z);
size >= 4 && (constData[int(offset + 3)] = vectorData.w);
}
else if (data is Matrix3D)
{
(data as Matrix3D).getRawData(constData, offset, true);
}
else if (data is Vector.<Vector4>)
{
var vectorVectorData : Vector.<Vector4> = data as Vector.<Vector4>;
var vectorVectorDataLength : uint = vectorVectorData.length;
for (var j : uint = 0; j < vectorVectorDataLength; ++j)
{
vectorData = vectorVectorData[j]._vector;
constData[offset + 4 * j] = vectorData.x;
constData[int(offset + 4 * j + 1)] = vectorData.y;
constData[int(offset + 4 * j + 2)] = vectorData.z;
constData[int(offset + 4 * j + 3)] = vectorData.w;
}
}
else if (data is Vector.<Matrix3D>)
{
var matrixVectorData : Vector.<Matrix3D> = data as Vector.<Matrix3D>;
var matrixVectorDataLength : uint = matrixVectorData.length;
for (var i : uint = 0; i < matrixVectorDataLength; ++i)
matrixVectorData[i].getRawData(constData, offset + i * 16, true);
}
else if (data == null)
{
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'null and required by automatic shader');
}
else
{
throw new Error('Parameter ' + paramAlloc.toString() + ' is ' +
'neither a int, a Number, a Vector4 or a Matrix3D. Unable to ' +
'map it to a shader constant.');
}
}
}
}
|
Remove useless import.
|
Remove useless import.
|
ActionScript
|
mit
|
aerys/minko-as3
|
74dca41e004668f1914b1dc494a9d454f7205e61
|
frameworks/projects/framework/src/mx/core/RuntimeDPIProvider.as
|
frameworks/projects/framework/src/mx/core/RuntimeDPIProvider.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 mx.core
{
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.system.Capabilities;
import mx.core.mx_internal;
import mx.managers.SystemManager;
import mx.utils.Platform;
use namespace mx_internal;
/**
* The RuntimeDPIProvider class provides the default mapping of
* similar device DPI values into predefined DPI classes.
* An Application may have its runtimeDPIProvider property set to a
* subclass of RuntimeDPIProvider to override Flex's default mappings.
* Overriding Flex's default mappings will cause changes in the Application's
* automatic scaling behavior.
*
* <p>Overriding Flex's default mappings is usually only necessary for devices
* that incorrectly report their screenDPI and for devices that may scale better
* in a different DPI class.</p>
*
* <p>Flex's default mappings are:
* <table class="innertable">
* <tr><td>160 DPI</td><td><140 DPI</td></tr>
* <tr><td>160 DPI</td><td>>=140 DPI and <=200 DPI</td></tr>
* <tr><td>240 DPI</td><td>>=200 DPI and <=280 DPI</td></tr>
* <tr><td>320 DPI</td><td>>=280 DPI and <=400 DPI</td></tr>
* <tr><td>480 DPI</td><td>>=400 DPI and <=560 DPI</td></tr>
* <tr><td>640 DPI</td><td>>=640 DPI</td></tr>
* </table>
* </p>
*
*
*
* <p>Subclasses of RuntimeDPIProvider should only depend on runtime APIs
* and should not depend on any classes specific to the Flex framework except
* <code>mx.core.DPIClassification</code>.</p>
*
* @includeExample examples/RuntimeDPIProviderApp.mxml -noswf
* @includeExample examples/RuntimeDPIProviderExample.as -noswf
* @includeExample examples/views/RuntimeDPIProviderAppView.mxml -noswf
*
* @see mx.core.DPIClassification
* @see spark.components.Application#applicationDPI
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class RuntimeDPIProvider
{
mx_internal static const IPAD_MAX_EXTENT:int = 1024;
mx_internal static const IPAD_RETINA_MAX_EXTENT: int = 2048;
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function RuntimeDPIProvider()
{
}
/**
* Returns the runtime DPI of the current device by mapping its
* <code>flash.system.Capabilities.screenDPI</code> to one of several DPI
* values in <code>mx.core.DPIClassification</code>.
*
* A number of devices can have slightly different DPI values and Flex maps these
* into the several DPI classes.
*
* Flex uses this method to calculate the current DPI value when an Application
* authored for a specific DPI is adapted to the current one through scaling.
*
* <p> Exceptions: </p>
* <ul>
* <li>All non-retina iPads receive 160 DPI </li>
* <li>All retina iPads receive 320 DPI </li>
* </ul>
*
* @param dpi The DPI value.
* @return The corresponding <code>DPIClassification</code> value.
* isI
* @see flash.system.Capabilities
* @see mx.core.DPIClassification
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function get runtimeDPI():Number
{
var isIOS:Boolean = Platform.isIOS;
var screenDPI:Number = Capabilities.screenDPI;
if (isIOS) // as isIPad returns false in the simulator
{
var root:DisplayObject = SystemManager.getSWFRoot(this);
if (root != null ) {
var stage:Stage = root.stage;
if (stage != null){
var scX:Number = stage.fullScreenWidth;
var scY:Number = stage.fullScreenHeight;
/* as of Dec 2013, iPad (resp. iPad retina) are the only iOS devices to have 1024 (resp. 2048) screen width or height
cf http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density#Apple
* */
if ((scX == IPAD_RETINA_MAX_EXTENT || scY == IPAD_RETINA_MAX_EXTENT))
return DPIClassification.DPI_320;
else if (scX == IPAD_MAX_EXTENT || scY == IPAD_MAX_EXTENT)
return DPIClassification.DPI_160;
}
}
}
return classifyDPI(screenDPI);
}
/**
* @private
* Matches the specified DPI to a <code>DPIClassification</code> value.
* A number of devices can have slightly different DPI values and classifyDPI
* maps these into the several DPI classes.
*
* This method is specifically kept for Design View. Flex uses RuntimeDPIProvider
* to calculate DPI classes.
*
* @param dpi The DPI value.
* @return The corresponding <code>DPIClassification</code> value.
*/
mx_internal static function classifyDPI(dpi:Number):Number
{
if (dpi <= 140)
return DPIClassification.DPI_120;
if (dpi <= 200)
return DPIClassification.DPI_160;
if (dpi <= 280)
return DPIClassification.DPI_240;
if (dpi <= 400)
return DPIClassification.DPI_320;
if (dpi <= 560)
return DPIClassification.DPI_480;
return DPIClassification.DPI_640;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package mx.core
{
import flash.display.DisplayObject;
import flash.display.Stage;
import flash.system.Capabilities;
import mx.core.mx_internal;
import mx.managers.SystemManager;
import mx.utils.Platform;
use namespace mx_internal;
/**
* The RuntimeDPIProvider class provides the default mapping of
* similar device DPI values into predefined DPI classes.
* An Application may have its runtimeDPIProvider property set to a
* subclass of RuntimeDPIProvider to override Flex's default mappings.
* Overriding Flex's default mappings will cause changes in the Application's
* automatic scaling behavior.
*
* <p>Overriding Flex's default mappings is usually only necessary for devices
* that incorrectly report their screenDPI and for devices that may scale better
* in a different DPI class.</p>
*
* <p>Flex's default mappings are:
* <table class="innertable">
* <tr><td>160 DPI</td><td><140 DPI</td></tr>
* <tr><td>160 DPI</td><td>>=140 DPI and <=200 DPI</td></tr>
* <tr><td>240 DPI</td><td>>=200 DPI and <=280 DPI</td></tr>
* <tr><td>320 DPI</td><td>>=280 DPI and <=400 DPI</td></tr>
* <tr><td>480 DPI</td><td>>=400 DPI and <=560 DPI</td></tr>
* <tr><td>640 DPI</td><td>>=640 DPI</td></tr>
* </table>
* </p>
*
*
*
* <p>Subclasses of RuntimeDPIProvider should only depend on runtime APIs
* and should not depend on any classes specific to the Flex framework except
* <code>mx.core.DPIClassification</code>.</p>
*
* @includeExample examples/RuntimeDPIProviderApp.mxml -noswf
* @includeExample examples/RuntimeDPIProviderExample.as -noswf
* @includeExample examples/views/RuntimeDPIProviderAppView.mxml -noswf
*
* @see mx.core.DPIClassification
* @see spark.components.Application#applicationDPI
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public class RuntimeDPIProvider
{
mx_internal static const IPAD_MAX_EXTENT:int = 1024;
mx_internal static const IPAD_RETINA_MAX_EXTENT: int = 2048;
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function RuntimeDPIProvider()
{
}
/**
* Returns the runtime DPI of the current device by mapping its
* <code>flash.system.Capabilities.screenDPI</code> to one of several DPI
* values in <code>mx.core.DPIClassification</code>.
*
* A number of devices can have slightly different DPI values and Flex maps these
* into the several DPI classes.
*
* Flex uses this method to calculate the current DPI value when an Application
* authored for a specific DPI is adapted to the current one through scaling.
*
* <p> Exceptions: </p>
* <ul>
* <li>All non-retina iPads receive 160 DPI </li>
* <li>All retina iPads receive 320 DPI </li>
* </ul>
*
* @param dpi The DPI value.
* @return The corresponding <code>DPIClassification</code> value.
* isI
* @see flash.system.Capabilities
* @see mx.core.DPIClassification
*
* @langversion 3.0
* @playerversion Flash 10
* @playerversion AIR 2.5
* @productversion Flex 4.5
*/
public function get runtimeDPI():Number
{
if (Platform.isIOS) // as isIPad returns false in the simulator
{
var scX:Number = Capabilities.screenResolutionX;
var scY:Number = Capabilities.screenResolutionY;
// Use the stage width/height only when debugging, because Capabilities reports the computer resolution
if (Capabilities.isDebugger)
{
var root:DisplayObject = SystemManager.getSWFRoot(this);
if (root && root.stage)
{
scX = root.stage.fullScreenWidth;
scY = root.stage.fullScreenHeight;
}
}
/* as of Dec 2013, iPad (resp. iPad retina) are the only iOS devices to have 1024 (resp. 2048) screen width or height
cf http://en.wikipedia.org/wiki/List_of_displays_by_pixel_density#Apple
* */
if (scX == IPAD_MAX_EXTENT || scY == IPAD_MAX_EXTENT)
return DPIClassification.DPI_160;
else if ((scX == IPAD_RETINA_MAX_EXTENT || scY == IPAD_RETINA_MAX_EXTENT))
return DPIClassification.DPI_320;
}
return classifyDPI(Capabilities.screenDPI);
}
/**
* @private
* Matches the specified DPI to a <code>DPIClassification</code> value.
* A number of devices can have slightly different DPI values and classifyDPI
* maps these into the several DPI classes.
*
* This method is specifically kept for Design View. Flex uses RuntimeDPIProvider
* to calculate DPI classes.
*
* @param dpi The DPI value.
* @return The corresponding <code>DPIClassification</code> value.
*/
mx_internal static function classifyDPI(dpi:Number):Number
{
if (dpi <= 140)
return DPIClassification.DPI_120;
if (dpi <= 200)
return DPIClassification.DPI_160;
if (dpi <= 280)
return DPIClassification.DPI_240;
if (dpi <= 400)
return DPIClassification.DPI_320;
if (dpi <= 560)
return DPIClassification.DPI_480;
return DPIClassification.DPI_640;
}
}
}
|
Fix for https://issues.apache.org/jira/browse/FLEX-34556 (thanks to Jorn Nolles)
|
Fix for https://issues.apache.org/jira/browse/FLEX-34556 (thanks to Jorn Nolles)
|
ActionScript
|
apache-2.0
|
danteinforno/flex-sdk,shyamalschandra/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,apache/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,danteinforno/flex-sdk,adufilie/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,SlavaRa/flex-sdk,apache/flex-sdk,adufilie/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,danteinforno/flex-sdk,SlavaRa/flex-sdk,adufilie/flex-sdk,shyamalschandra/flex-sdk,apache/flex-sdk
|
42a2fe25620ffa2f57eaeb15c947297d791d9bed
|
src/com/axis/http/request.as
|
src/com/axis/http/request.as
|
package com.axis.http {
import com.axis.rtspclient.ByteArrayUtils;
import com.axis.Logger;
import flash.utils.ByteArray;
public class request {
public static function readHeaders(dataInput:*, buffer:ByteArray):* {
dataInput.readBytes(buffer, buffer.length);
var index:int = ByteArrayUtils.indexOf(buffer, "\r\n\r\n");
if (index === -1) {
/* Not a full request yet */
return false;
}
var dummy:ByteArray = new ByteArray();
buffer.readBytes(dummy, 0, index + 4);
var parsed:Object = parse(dummy.toString());
if (parsed.headers['content-length'] &&
int(parsed.headers['content-length']) > buffer.bytesAvailable) {
/* Headers parsed fine, but full body is not here yet. */
buffer.position = 0;
return false;
}
return parsed;
}
public static function parse(data:String):Object {
var ret:Object = {};
var lines:Array = data.split('\r\n');
var statusRegex:RegExp = /^(?P<proto>[^\/]+)\/(?P<version>[^ ]+) (?P<code>[0-9]+) (?P<message>.*)$/;
var status:Array = statusRegex.exec(lines.shift());
if (status) {
/* statusRegex will fail if this is multipart block (in which case these parameters are not valid) */
ret.proto = status.proto;
ret.version = status.version;
ret.code = uint(status.code);
ret.message = status.message;
}
ret.headers = {};
for each (var header:String in lines) {
if (header.length === 0) continue;
var t:Array = header.split(':');
var key:String = t.shift().replace(/^[\s]*(.*)[\s]*$/, '$1').toLowerCase();
var val:String = t.join(':').replace(/^[\s]*(.*)[\s]*$/, '$1');
parseMiddleware(key, val, ret.headers);
}
return ret;
}
private static function parseMiddleware(key:String, val:String, hdr:Object):void {
switch (key) {
case 'www-authenticate':
if (!hdr['www-authenticate'])
hdr['www-authenticate'] = {};
if (/^basic/i.test(val)) {
var basicRealm:RegExp = /realm=\"([^\"]+)\"/i;
hdr['www-authenticate'].basicRealm = basicRealm.exec(val)[1];
}
if (/^digest/i.test(val)) {
var params:Array = val.substr(7).split(/,\s*/);
for each (var p:String in params) {
var kv:Array = p.split('=');
if (2 !== kv.length) continue;
if (kv[0].toLowerCase() === 'realm') kv[0] = 'digestRealm';
hdr['www-authenticate'][kv[0]] = kv[1].replace(/^"(.*)"$/, '$1');
}
}
break;
default:
/* In the default case, just take the value as-is */
hdr[key] = val;
}
}
}
}
|
package com.axis.http {
import com.axis.rtspclient.ByteArrayUtils;
import com.axis.Logger;
import flash.utils.ByteArray;
public class request {
public static function readHeaders(dataInput:*, buffer:ByteArray):* {
dataInput.readBytes(buffer, buffer.length);
var index:int = ByteArrayUtils.indexOf(buffer, "\r\n\r\n");
if (index === -1) {
/* Not a full request yet */
return false;
}
var dummy:ByteArray = new ByteArray();
buffer.readBytes(dummy, 0, index + 4);
var parsed:Object = parse(dummy.toString());
if (parsed.headers['content-length'] &&
int(parsed.headers['content-length']) > buffer.bytesAvailable) {
/* Headers parsed fine, but full body is not here yet. */
buffer.position = 0;
return false;
}
return parsed;
}
public static function parse(data:String):Object {
var ret:Object = {};
var lines:Array = data.split('\r\n');
var statusRegex:RegExp = /^(?P<proto>[^\/]+)\/(?P<version>[^ ]+) (?P<code>[0-9]+) (?P<message>.*)$/;
var status:Array = statusRegex.exec(lines.shift());
if (status) {
/* statusRegex will fail if this is multipart block (in which case these parameters are not valid) */
ret.proto = status.proto;
ret.version = status.version;
ret.code = uint(status.code);
ret.message = status.message;
}
ret.headers = {};
for each (var header:String in lines) {
if (header.length === 0) continue;
var t:Array = header.split(':');
var key:String = t.shift().replace(/^[\s]*(.*)[\s]*$/, '$1').toLowerCase();
var val:String = t.join(':').replace(/^[\s]*(.*)[\s]*$/, '$1');
parseMiddleware(key, val, ret.headers);
}
return ret;
}
private static function parseMiddleware(key:String, val:String, hdr:Object):void {
switch (key) {
case 'www-authenticate':
if (!hdr['www-authenticate'])
hdr['www-authenticate'] = {};
if (/^basic/i.test(val)) {
var basicRealm:RegExp = /realm="([^"]*)"/i;
hdr['www-authenticate'].basicRealm = basicRealm.exec(val)[1];
}
if (/^digest/i.test(val)) {
var params:Array = val.substr(7).split(/,\s*/);
for each (var p:String in params) {
var kv:Array = p.split('=');
if (2 !== kv.length) continue;
if (kv[0].toLowerCase() === 'realm') kv[0] = 'digestRealm';
hdr['www-authenticate'][kv[0]] = kv[1].replace(/^"(.*)"$/, '$1');
}
}
break;
default:
/* In the default case, just take the value as-is */
hdr[key] = val;
}
}
}
}
|
Correct regex. Also value might be empty
|
Correct regex. Also value might be empty
|
ActionScript
|
bsd-3-clause
|
gaetancollaud/locomote-video-player,AxisCommunications/locomote-video-player
|
28e52f915436831988bbe31433e8fe23b34f3585
|
src/aerys/minko/type/MouseManager.as
|
src/aerys/minko/type/MouseManager.as
|
package aerys.minko.type
{
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.ui.Mouse;
public final class MouseManager
{
private var _x : Number = 0.;
private var _y : Number = 0.;
private var _leftButtonDown : Boolean = false;
private var _middleButtonDown : Boolean = false;
private var _rightButtonDown : Boolean = false;
private var _mouseDown : Signal = new Signal("mouseDown");
private var _mouseUp : Signal = new Signal("mouseUp");
private var _cursors : Vector.<String> = new <String>[];
public function get x() : Number
{
return _x;
}
public function get y() : Number
{
return _y;
}
public function get leftButtonDown() : Boolean
{
return _leftButtonDown;
}
public function get middleButtonDown() : Boolean
{
return _middleButtonDown;
}
public function get rightButtonDown() : Boolean
{
return _rightButtonDown;
}
public function get cursor() : String
{
return Mouse.cursor;
}
public function get mouseDown() : Signal
{
return _mouseDown;
}
public function get mouseUp() : Signal
{
return _mouseUp;
}
public function bind(dispatcher : IEventDispatcher) : void
{
dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
dispatcher.addEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
dispatcher.addEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);
if (MouseEvent.RIGHT_CLICK != null)
{
dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
}
if (MouseEvent.MIDDLE_CLICK != null)
{
dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
}
}
public function unbind(dispatcher : IEventDispatcher) : void
{
dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
dispatcher.removeEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
dispatcher.removeEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);
if (MouseEvent.RIGHT_CLICK != null)
{
dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
}
if (MouseEvent.MIDDLE_CLICK != null)
{
dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
}
}
private function mouseMoveHandler(event : MouseEvent) : void
{
_x = event.localX;
_y = event.localY;
}
private function mouseLeftDownHandler(event : MouseEvent) : void
{
_leftButtonDown = true;
_mouseDown.execute();
}
private function mouseLeftUpHandler(event : MouseEvent) : void
{
_leftButtonDown = false;
_mouseUp.execute();
}
private function mouseMiddleDownHandler(event : MouseEvent) : void
{
_rightButtonDown = true;
}
private function mouseMiddleUpHandler(event : MouseEvent) : void
{
_rightButtonDown = false;
}
private function mouseRightDownHandler(event : MouseEvent) : void
{
_rightButtonDown = true;
}
private function mouseRightUpHandler(event : MouseEvent) : void
{
_rightButtonDown = false;
}
public function pushCursor(cursor : String) : MouseManager
{
_cursors.push(Mouse.cursor);
Mouse.cursor = cursor;
return this;
}
public function popCursor() : MouseManager
{
Mouse.cursor = _cursors.pop();
return this;
}
}
}
|
package aerys.minko.type
{
import flash.events.IEventDispatcher;
import flash.events.MouseEvent;
import flash.ui.Mouse;
public final class MouseManager
{
private var _x : Number = 0.;
private var _y : Number = 0.;
private var _leftButtonDown : Boolean = false;
private var _middleButtonDown : Boolean = false;
private var _rightButtonDown : Boolean = false;
private var _mouseDown : Signal = new Signal("mouseDown");
private var _mouseUp : Signal = new Signal("mouseUp");
private var _cursors : Vector.<String> = new <String>[];
public function get x() : Number
{
return _x;
}
public function get y() : Number
{
return _y;
}
public function get leftButtonDown() : Boolean
{
return _leftButtonDown;
}
public function get middleButtonDown() : Boolean
{
return _middleButtonDown;
}
public function get rightButtonDown() : Boolean
{
return _rightButtonDown;
}
public function get cursor() : String
{
return Mouse.cursor;
}
public function get mouseDown() : Signal
{
return _mouseDown;
}
public function get mouseUp() : Signal
{
return _mouseUp;
}
public function bind(dispatcher : IEventDispatcher) : void
{
dispatcher.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
dispatcher.addEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
dispatcher.addEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);
if (MouseEvent.RIGHT_CLICK != null)
{
dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
dispatcher.addEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
}
if (MouseEvent.MIDDLE_CLICK != null)
{
dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
dispatcher.addEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
}
}
public function unbind(dispatcher : IEventDispatcher) : void
{
dispatcher.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
dispatcher.removeEventListener(MouseEvent.MOUSE_DOWN, mouseLeftDownHandler);
dispatcher.removeEventListener(MouseEvent.MOUSE_UP, mouseLeftUpHandler);
if (MouseEvent.RIGHT_CLICK != null)
{
dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_DOWN, mouseRightDownHandler);
dispatcher.removeEventListener(MouseEvent.RIGHT_MOUSE_UP, mouseRightUpHandler);
}
if (MouseEvent.MIDDLE_CLICK != null)
{
dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_DOWN, mouseMiddleDownHandler);
dispatcher.removeEventListener(MouseEvent.MIDDLE_MOUSE_UP, mouseMiddleUpHandler);
}
}
private function mouseMoveHandler(event : MouseEvent) : void
{
_x = event.localX;
_y = event.localY;
}
private function mouseLeftDownHandler(event : MouseEvent) : void
{
_leftButtonDown = true;
_mouseDown.execute();
}
private function mouseLeftUpHandler(event : MouseEvent) : void
{
_leftButtonDown = false;
_mouseUp.execute();
}
private function mouseMiddleDownHandler(event : MouseEvent) : void
{
_middleButtonDown = true;
}
private function mouseMiddleUpHandler(event : MouseEvent) : void
{
_middleButtonDown = false;
}
private function mouseRightDownHandler(event : MouseEvent) : void
{
_rightButtonDown = true;
}
private function mouseRightUpHandler(event : MouseEvent) : void
{
_rightButtonDown = false;
}
public function pushCursor(cursor : String) : MouseManager
{
_cursors.push(Mouse.cursor);
Mouse.cursor = cursor;
return this;
}
public function popCursor() : MouseManager
{
Mouse.cursor = _cursors.pop();
return this;
}
}
}
|
Update src/aerys/minko/type/MouseManager.as
|
Update src/aerys/minko/type/MouseManager.as
Fixed bug in middle mouse button handler.
|
ActionScript
|
mit
|
aerys/minko-as3
|
5df0391fb551a88e987fc2eeb7f9ffa5a1cc86b5
|
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
|
src/com/esri/builder/controllers/supportClasses/WidgetTypeLoader.as
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2016 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers.supportClasses
{
import com.esri.builder.model.CustomWidgetType;
import com.esri.builder.model.WidgetType;
import com.esri.builder.supportClasses.FileUtil;
import com.esri.builder.supportClasses.LogUtil;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
import modules.IBuilderModule;
import modules.supportClasses.CustomXMLModule;
import mx.core.FlexGlobals;
import mx.events.ModuleEvent;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.modules.IModuleInfo;
import mx.modules.ModuleManager;
public class WidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader);
internal static var loadedModuleInfos:Array = [];
private var swf:File;
private var config:File;
//need reference when loading to avoid being garbage collected before load completes
private var moduleInfo:IModuleInfo;
//requires either swf or config
public function WidgetTypeLoader(swf:File = null, config:File = null)
{
this.swf = swf;
this.config = config;
}
public function get name():String
{
var fileName:String;
if (swf && swf.exists)
{
fileName = FileUtil.getFileName(swf);
}
else if (config && config.exists)
{
fileName = FileUtil.getFileName(config);
}
return fileName;
}
public function load():void
{
if (swf && swf.exists)
{
loadModule();
}
else if (config && config.exists)
{
loadConfigModule();
}
else
{
dispatchError();
}
}
private function loadConfigModule():void
{
if (Log.isInfo())
{
LOG.info('Loading XML module: {0}', config.url);
}
var moduleConfig:XML = readModuleConfig(config);
if (moduleConfig)
{
var customWidgetType:CustomWidgetType = parseCustomWidgetType(moduleConfig);
if (customWidgetType)
{
dispatchComplete(customWidgetType);
return;
}
}
dispatchError();
}
private function loadModule():void
{
if (Log.isInfo())
{
LOG.info('Loading SWF module: {0}', swf.url);
}
moduleInfo = ModuleManager.getModule(swf.url);
if (moduleInfo.ready)
{
if (Log.isInfo())
{
LOG.info('Unloading module: {0}', swf.url);
}
moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
moduleInfo.release();
moduleInfo.unload();
}
else
{
if (Log.isInfo())
{
LOG.info('Loading module: {0}', swf.url);
}
var fileBytes:ByteArray = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(swf, FileMode.READ);
fileStream.readBytes(fileBytes);
fileStream.close();
moduleInfo.addEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.load(null, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory);
}
}
private function moduleInfo_unloadHandler(event:ModuleEvent):void
{
if (Log.isInfo())
{
LOG.info('Module unloaded: {0}', swf.url);
}
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
var moduleInfoIndex:int = loadedModuleInfos.indexOf(moduleInfo);
if (moduleInfoIndex > -1)
{
loadedModuleInfos.splice(moduleInfoIndex, 1);
}
this.moduleInfo = null;
FlexGlobals.topLevelApplication.callLater(loadModule);
}
private function moduleInfo_readyHandler(event:ModuleEvent):void
{
if (Log.isInfo())
{
LOG.info('Module loaded: {0}', swf.url);
}
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
if (config && config.exists)
{
if (Log.isInfo())
{
LOG.info('Reading module config: {0}', config.url);
}
var moduleConfig:XML = readModuleConfig(config);
}
const builderModule:IBuilderModule = event.module.factory.create() as IBuilderModule;
if (builderModule)
{
if (Log.isInfo())
{
LOG.info('Widget type created for module: {0}', swf.url);
}
var widgetType:WidgetType = getWidgetType(moduleInfo, builderModule, moduleConfig);
}
loadedModuleInfos.push(moduleInfo);
this.moduleInfo = null;
dispatchComplete(widgetType);
}
private function dispatchComplete(widgetType:WidgetType):void
{
if (Log.isInfo())
{
LOG.info('Module load complete: {0}', name);
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_COMPLETE, widgetType));
}
private function getWidgetType(moduleInfo:IModuleInfo, builderModule:IBuilderModule, moduleConfig:XML):WidgetType
{
var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url;
var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1);
if (moduleConfig)
{
var configXML:XML = moduleConfig.configuration[0];
var version:String = moduleConfig.widgetversion[0];
}
return isCustomModule ?
new CustomWidgetType(builderModule, version, configXML) :
new WidgetType(builderModule);
}
private function readModuleConfig(configFile:File):XML
{
var configXML:XML;
var fileStream:FileStream = new FileStream();
try
{
fileStream.open(configFile, FileMode.READ);
configXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
}
catch (e:Error)
{
//ignore
if (Log.isInfo())
{
LOG.info('Could not read module config: {0}', e.toString());
}
}
finally
{
fileStream.close();
}
return configXML;
}
private function moduleInfo_errorHandler(event:ModuleEvent):void
{
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.removeEventListener(ModuleEvent.READY, moduleInfo_readyHandler);
this.moduleInfo = null;
dispatchError();
}
private function dispatchError():void
{
if (Log.isInfo())
{
LOG.info('Module load failed: {0}', name);
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_ERROR));
}
private function parseCustomWidgetType(configXML:XML):CustomWidgetType
{
if (Log.isInfo())
{
LOG.info('Creating widget type from XML: {0}', configXML);
}
var customModule:CustomXMLModule = new CustomXMLModule();
customModule.widgetName = configXML.name;
customModule.isOpenByDefault = (configXML.openbydefault == 'true');
var widgetLabel:String = configXML.label[0];
var widgetDescription:String = configXML.description[0];
var widgetHelpURL:String = configXML.helpurl[0];
var widgetConfiguration:XML = configXML.configuration[0] ? configXML.configuration[0] : <configuration/>;
var widgetVersion:String = configXML.widgetversion[0];
customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName);
customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName;
customModule.widgetDescription = widgetDescription ? widgetDescription : "";
customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : "";
return new CustomWidgetType(customModule, widgetVersion, widgetConfiguration);
}
private function createWidgetIconPath(iconPath:String, widgetName:String):String
{
var widgetIconPath:String;
if (iconPath)
{
widgetIconPath = "widgets/" + widgetName + "/" + iconPath;
}
else
{
widgetIconPath = "assets/images/i_widget.png";
}
return widgetIconPath;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2016 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
////////////////////////////////////////////////////////////////////////////////
package com.esri.builder.controllers.supportClasses
{
import com.esri.builder.model.CustomWidgetType;
import com.esri.builder.model.WidgetType;
import com.esri.builder.supportClasses.FileUtil;
import com.esri.builder.supportClasses.LogUtil;
import flash.events.EventDispatcher;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
import modules.IBuilderModule;
import modules.supportClasses.CustomXMLModule;
import mx.core.FlexGlobals;
import mx.events.ModuleEvent;
import mx.logging.ILogger;
import mx.logging.Log;
import mx.modules.IModuleInfo;
import mx.modules.ModuleManager;
public class WidgetTypeLoader extends EventDispatcher
{
private static const LOG:ILogger = LogUtil.createLogger(WidgetTypeLoader);
internal static var loadedModuleInfos:Array = [];
private var swf:File;
private var config:File;
//need reference when loading to avoid being garbage collected before load completes
private var moduleInfo:IModuleInfo;
//requires either swf or config
public function WidgetTypeLoader(swf:File = null, config:File = null)
{
this.swf = swf;
this.config = config;
}
public function get name():String
{
var fileName:String;
if (swf && swf.exists)
{
fileName = FileUtil.getFileName(swf);
}
else if (config && config.exists)
{
fileName = FileUtil.getFileName(config);
}
return fileName;
}
public function load():void
{
if (swf && swf.exists)
{
loadModule();
}
else if (config && config.exists)
{
loadConfigModule();
}
else
{
dispatchError();
}
}
private function loadConfigModule():void
{
if (Log.isInfo())
{
LOG.info('Loading XML module: {0}', config.url);
}
var moduleConfig:XML = readModuleConfig(config);
if (moduleConfig)
{
var customWidgetType:CustomWidgetType = parseCustomWidgetType(moduleConfig);
if (customWidgetType)
{
dispatchComplete(customWidgetType);
return;
}
}
dispatchError();
}
private function loadModule():void
{
if (Log.isInfo())
{
LOG.info('Loading SWF module: {0}', swf.url);
}
moduleInfo = ModuleManager.getModule(swf.url);
if (moduleInfo.ready)
{
if (Log.isInfo())
{
LOG.info('Unloading module: {0}', swf.url);
}
moduleInfo.addEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
moduleInfo.release();
moduleInfo.unload();
}
else
{
if (Log.isInfo())
{
LOG.info('Loading module: {0}', swf.url);
}
var fileBytes:ByteArray = new ByteArray();
var fileStream:FileStream = new FileStream();
fileStream.open(swf, FileMode.READ);
fileStream.readBytes(fileBytes);
fileStream.close();
//Use ModuleEvent.PROGRESS instead of ModuleEvent.READY to avoid the case where the latter is never dispatched.
moduleInfo.addEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler);
moduleInfo.addEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.load(null, null, fileBytes, FlexGlobals.topLevelApplication.moduleFactory);
}
}
private function moduleInfo_progressHandler(event:ModuleEvent):void
{
if (event.bytesLoaded == event.bytesTotal)
{
var moduleInfo:IModuleInfo = event.currentTarget as IModuleInfo;
moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler);
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
FlexGlobals.topLevelApplication.callLater(processModuleInfo, [ moduleInfo ]);
}
}
private function moduleInfo_unloadHandler(event:ModuleEvent):void
{
if (Log.isInfo())
{
LOG.info('Module unloaded: {0}', swf.url);
}
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.UNLOAD, moduleInfo_unloadHandler);
var moduleInfoIndex:int = loadedModuleInfos.indexOf(moduleInfo);
if (moduleInfoIndex > -1)
{
loadedModuleInfos.splice(moduleInfoIndex, 1);
}
this.moduleInfo = null;
FlexGlobals.topLevelApplication.callLater(loadModule);
}
private function processModuleInfo(moduleInfo:IModuleInfo):void
{
if (Log.isInfo())
{
LOG.info('Module loaded: {0}', swf.url);
}
if (config && config.exists)
{
if (Log.isInfo())
{
LOG.info('Reading module config: {0}', config.url);
}
var moduleConfig:XML = readModuleConfig(config);
}
const builderModule:IBuilderModule = moduleInfo.factory.create() as IBuilderModule;
if (builderModule)
{
if (Log.isInfo())
{
LOG.info('Widget type created for module: {0}', swf.url);
}
var widgetType:WidgetType = getWidgetType(moduleInfo, builderModule, moduleConfig);
}
loadedModuleInfos.push(moduleInfo);
this.moduleInfo = null;
dispatchComplete(widgetType);
}
private function dispatchComplete(widgetType:WidgetType):void
{
if (Log.isInfo())
{
LOG.info('Module load complete: {0}', name);
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_COMPLETE, widgetType));
}
private function getWidgetType(moduleInfo:IModuleInfo, builderModule:IBuilderModule, moduleConfig:XML):WidgetType
{
var customModulesDirectoryURL:String = WellKnownDirectories.getInstance().customModules.url;
var isCustomModule:Boolean = (moduleInfo.url.indexOf(customModulesDirectoryURL) > -1);
if (moduleConfig)
{
var configXML:XML = moduleConfig.configuration[0];
var version:String = moduleConfig.widgetversion[0];
}
return isCustomModule ?
new CustomWidgetType(builderModule, version, configXML) :
new WidgetType(builderModule);
}
private function readModuleConfig(configFile:File):XML
{
var configXML:XML;
var fileStream:FileStream = new FileStream();
try
{
fileStream.open(configFile, FileMode.READ);
configXML = XML(fileStream.readUTFBytes(fileStream.bytesAvailable));
}
catch (e:Error)
{
//ignore
if (Log.isInfo())
{
LOG.info('Could not read module config: {0}', e.toString());
}
}
finally
{
fileStream.close();
}
return configXML;
}
private function moduleInfo_errorHandler(event:ModuleEvent):void
{
var moduleInfo:IModuleInfo = event.module;
moduleInfo.removeEventListener(ModuleEvent.ERROR, moduleInfo_errorHandler);
moduleInfo.removeEventListener(ModuleEvent.PROGRESS, moduleInfo_progressHandler);
this.moduleInfo = null;
dispatchError();
}
private function dispatchError():void
{
if (Log.isInfo())
{
LOG.info('Module load failed: {0}', name);
}
dispatchEvent(new WidgetTypeLoaderEvent(WidgetTypeLoaderEvent.LOAD_ERROR));
}
private function parseCustomWidgetType(configXML:XML):CustomWidgetType
{
if (Log.isInfo())
{
LOG.info('Creating widget type from XML: {0}', configXML);
}
var customModule:CustomXMLModule = new CustomXMLModule();
customModule.widgetName = configXML.name;
customModule.isOpenByDefault = (configXML.openbydefault == 'true');
var widgetLabel:String = configXML.label[0];
var widgetDescription:String = configXML.description[0];
var widgetHelpURL:String = configXML.helpurl[0];
var widgetConfiguration:XML = configXML.configuration[0] ? configXML.configuration[0] : <configuration/>;
var widgetVersion:String = configXML.widgetversion[0];
customModule.widgetIconLocation = createWidgetIconPath(configXML.icon[0], customModule.widgetName);
customModule.widgetLabel = widgetLabel ? widgetLabel : customModule.widgetName;
customModule.widgetDescription = widgetDescription ? widgetDescription : "";
customModule.widgetHelpURL = widgetHelpURL ? widgetHelpURL : "";
return new CustomWidgetType(customModule, widgetVersion, widgetConfiguration);
}
private function createWidgetIconPath(iconPath:String, widgetName:String):String
{
var widgetIconPath:String;
if (iconPath)
{
widgetIconPath = "widgets/" + widgetName + "/" + iconPath;
}
else
{
widgetIconPath = "assets/images/i_widget.png";
}
return widgetIconPath;
}
}
}
|
Add workaround to prevent widget load process from hanging.
|
Add workaround to prevent widget load process from hanging.
|
ActionScript
|
apache-2.0
|
Esri/arcgis-viewer-builder-flex
|
066f630c858b3d3364392496ac76790af848bfcf
|
src/aerys/minko/type/binding/DataProvider.as
|
src/aerys/minko/type/binding/DataProvider.as
|
package aerys.minko.type.binding
{
import aerys.minko.type.Signal;
import aerys.minko.type.enum.DataProviderUsage;
import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public dynamic class DataProvider extends Proxy implements IDynamicDataProvider
{
private var _usage : uint;
private var _name : String;
private var _descriptor : Object;
private var _propertyChanged : Signal;
private var _propertyAdded : Signal;
private var _propertyRemoved : Signal;
private var _nameToProperty : Object;
private var _propertyToNames : Dictionary;
public function get usage() : uint
{
return _usage;
}
public function get dataDescriptor() : Object
{
return _descriptor;
}
public function get propertyChanged() : Signal
{
return _propertyChanged;
}
public function get propertyAdded() : Signal
{
return _propertyAdded;
}
public function get propertyRemoved() : Signal
{
return _propertyRemoved;
}
public function get name() : String
{
return _name;
}
public function set name(v : String) : void
{
_name = v;
}
public function DataProvider(properties : Object = null,
name : String = null,
usage : uint = 1)
{
_name = name;
_usage = usage;
initialize(properties);
}
private function initialize(properties : Object) : void
{
_descriptor = {};
_propertyChanged = new Signal('DataProvider.changed');
_propertyAdded = new Signal('DataProvider.propertyAdded');
_propertyRemoved = new Signal('DataProvider.propertyRemoved');
_nameToProperty = {};
_propertyToNames = new Dictionary();
var propertyName : String = null;
if (properties is DataProvider)
{
var provider : DataProvider = properties as DataProvider;
for each (propertyName in provider.dataDescriptor)
setProperty(propertyName, provider[propertyName]);
}
else if (properties is Object)
{
for (propertyName in properties)
setProperty(propertyName, properties[propertyName]);
}
}
override flash_proxy function getProperty(name : *) : *
{
return getProperty(String(name));
}
override flash_proxy function setProperty(name : *, value : *) : void
{
setProperty(String(name), value);
}
override flash_proxy function deleteProperty(name : *) : Boolean
{
removeProperty(String(name));
return true;
}
public function getProperty(name : String) : *
{
return _nameToProperty[name];
}
public function setProperty(name : String, newValue : Object) : DataProvider
{
var oldValue : Object = _nameToProperty[name];
var oldWatchedValue : IWatchable = oldValue as IWatchable;
var newWatchedValue : IWatchable = newValue as IWatchable;
var oldPropertyNames : Vector.<String> = _propertyToNames[oldWatchedValue];
var newPropertyNames : Vector.<String> = _propertyToNames[newWatchedValue];
if (newWatchedValue != oldWatchedValue)
{
if (oldWatchedValue != null)
unwatchProperty(name, oldWatchedValue);
if (newWatchedValue != null)
watchProperty(name, newWatchedValue);
}
var propertyAdded : Boolean = !_descriptor.hasOwnProperty(name);
_descriptor[name] = name;
_nameToProperty[name] = newValue;
if (propertyAdded)
_propertyAdded.execute(this, name, name, newValue);
else
_propertyChanged.execute(this, name);
return this;
}
public function setProperties(properties : Object) : DataProvider
{
for (var propertyName : String in properties)
setProperty(propertyName, properties[propertyName]);
return this;
}
protected function watchProperty(name : String, property : IWatchable) : void
{
if (property != null)
{
var newPropertyNames : Vector.<String> = _propertyToNames[property] as Vector.<String>;
if (newPropertyNames == null)
{
_propertyToNames[property] = newPropertyNames = new <String>[name];
property.changed.add(propertyChangedHandler);
}
else
newPropertyNames.push(name);
}
}
protected function unwatchProperty(name : String, property : IWatchable) : void
{
var oldPropertyNames : Vector.<String> = _propertyToNames[property];
if (oldPropertyNames.length == 1)
{
property.changed.remove(propertyChangedHandler);
delete _propertyToNames[property];
}
else
{
var numPropertyNames : uint = oldPropertyNames.length - 1;
oldPropertyNames[oldPropertyNames.indexOf(name)] = oldPropertyNames[numPropertyNames];
oldPropertyNames.length = numPropertyNames;
}
}
public function removeProperty(name : String) : DataProvider
{
if (_descriptor.hasOwnProperty(name))
{
var oldMonitoredValue : IWatchable = _nameToProperty[name] as IWatchable;
var oldPropertyNames : Vector.<String> = _propertyToNames[oldMonitoredValue];
var bindingName : String = _descriptor[name];
delete _descriptor[name];
delete _nameToProperty[name];
if (oldMonitoredValue != null)
unwatchProperty(name, oldMonitoredValue);
// _changed.execute(this, 'dataDescriptor');
_propertyRemoved.execute(this, name, bindingName, oldMonitoredValue);
}
return this;
}
public function removeAllProperties() : DataProvider
{
for (var propertyName : String in _nameToProperty)
removeProperty(propertyName);
return this;
}
public function propertyExists(name : String) : Boolean
{
return _descriptor.hasOwnProperty(name);
}
public function invalidate() : DataProvider
{
_propertyChanged.execute(this, null);
return this;
}
public function clone() : IDataProvider
{
switch (_usage)
{
case DataProviderUsage.EXCLUSIVE:
return new DataProvider(_nameToProperty, _name + '_cloned', _usage);
case DataProviderUsage.SHARED:
return this;
case DataProviderUsage.MANAGED:
throw new Error('This dataprovider is managed, and must not be cloned');
default:
throw new Error('Unkown usage value');
}
}
private function propertyChangedHandler(source : IWatchable) : void
{
var names : Vector.<String> = _propertyToNames[source];
var numNames : uint = names.length;
for (var nameId : uint = 0; nameId < numNames; ++nameId)
_propertyChanged.execute(this, names[nameId]);
}
}
}
|
package aerys.minko.type.binding
{
import aerys.minko.type.Signal;
import aerys.minko.type.enum.DataProviderUsage;
import flash.utils.Dictionary;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public dynamic class DataProvider extends Proxy implements IDynamicDataProvider
{
private var _usage : uint;
private var _name : String;
private var _descriptor : Object;
private var _propertyChanged : Signal;
private var _propertyAdded : Signal;
private var _propertyRemoved : Signal;
private var _nameToProperty : Object;
private var _propertyToNames : Dictionary;
public function get usage() : uint
{
return _usage;
}
public function get dataDescriptor() : Object
{
return _descriptor;
}
public function get propertyChanged() : Signal
{
return _propertyChanged;
}
public function get propertyAdded() : Signal
{
return _propertyAdded;
}
public function get propertyRemoved() : Signal
{
return _propertyRemoved;
}
public function get name() : String
{
return _name;
}
public function set name(v : String) : void
{
_name = v;
}
public function DataProvider(properties : Object = null,
name : String = null,
usage : uint = 1)
{
_name = name;
_usage = usage;
initialize(properties);
}
private function initialize(properties : Object) : void
{
_descriptor = {};
_propertyChanged = new Signal('DataProvider.changed');
_propertyAdded = new Signal('DataProvider.propertyAdded');
_propertyRemoved = new Signal('DataProvider.propertyRemoved');
_nameToProperty = {};
_propertyToNames = new Dictionary();
var propertyName : String = null;
if (properties is DataProvider)
{
var provider : DataProvider = properties as DataProvider;
for each (propertyName in provider.dataDescriptor)
setProperty(propertyName, provider[propertyName]);
}
else if (properties is Object)
{
for (propertyName in properties)
setProperty(propertyName, properties[propertyName]);
}
}
override flash_proxy function getProperty(name : *) : *
{
return getProperty(String(name));
}
override flash_proxy function setProperty(name : *, value : *) : void
{
setProperty(String(name), value);
}
override flash_proxy function deleteProperty(name : *) : Boolean
{
removeProperty(String(name));
return true;
}
public function getProperty(name : String) : *
{
return _nameToProperty[name];
}
public function setProperty(name : String, newValue : Object) : DataProvider
{
var oldValue : Object = _nameToProperty[name];
var oldWatchedValue : IWatchable = oldValue as IWatchable;
var newWatchedValue : IWatchable = newValue as IWatchable;
var oldPropertyNames : Vector.<String> = _propertyToNames[oldWatchedValue];
var newPropertyNames : Vector.<String> = _propertyToNames[newWatchedValue];
if (newWatchedValue != oldWatchedValue)
{
if (oldWatchedValue != null)
unwatchProperty(name, oldWatchedValue);
if (newWatchedValue != null)
watchProperty(name, newWatchedValue);
}
var propertyAdded : Boolean = !_descriptor.hasOwnProperty(name);
_descriptor[name] = name;
_nameToProperty[name] = newValue;
if (propertyAdded)
_propertyAdded.execute(this, name, name, newValue);
else
_propertyChanged.execute(this, name);
return this;
}
public function setProperties(properties : Object) : DataProvider
{
for (var propertyName : String in properties)
setProperty(propertyName, properties[propertyName]);
return this;
}
protected function watchProperty(name : String, property : IWatchable) : void
{
if (property != null)
{
var newPropertyNames : Vector.<String> = _propertyToNames[property] as Vector.<String>;
if (newPropertyNames == null)
{
_propertyToNames[property] = newPropertyNames = new <String>[name];
property.changed.add(propertyChangedHandler);
}
else
newPropertyNames.push(name);
}
}
protected function unwatchProperty(name : String, property : IWatchable) : void
{
var oldPropertyNames : Vector.<String> = _propertyToNames[property];
if (oldPropertyNames.length == 1)
{
property.changed.remove(propertyChangedHandler);
delete _propertyToNames[property];
}
else
{
var numPropertyNames : uint = oldPropertyNames.length - 1;
oldPropertyNames[oldPropertyNames.indexOf(name)] = oldPropertyNames[numPropertyNames];
oldPropertyNames.length = numPropertyNames;
}
}
public function removeProperty(name : String) : DataProvider
{
if (_descriptor.hasOwnProperty(name))
{
var oldMonitoredValue : IWatchable = _nameToProperty[name] as IWatchable;
var oldPropertyNames : Vector.<String> = _propertyToNames[oldMonitoredValue];
var bindingName : String = _descriptor[name];
delete _descriptor[name];
delete _nameToProperty[name];
if (oldMonitoredValue != null)
unwatchProperty(name, oldMonitoredValue);
// _changed.execute(this, 'dataDescriptor');
_propertyRemoved.execute(this, name, bindingName, oldMonitoredValue);
}
return this;
}
public function removeAllProperties() : DataProvider
{
for (var propertyName : String in _nameToProperty)
removeProperty(propertyName);
return this;
}
public function dispose() : void
{
removeAllProperties();
_propertyToNames = null;
_nameToProperty = null;
_descriptor = null;
_propertyAdded = null;
_propertyChanged = null;
_propertyRemoved = null;
}
public function propertyExists(name : String) : Boolean
{
return _descriptor.hasOwnProperty(name);
}
public function invalidate() : DataProvider
{
_propertyChanged.execute(this, null);
return this;
}
public function clone() : IDataProvider
{
switch (_usage)
{
case DataProviderUsage.EXCLUSIVE:
return new DataProvider(_nameToProperty, _name + '_cloned', _usage);
case DataProviderUsage.SHARED:
return this;
case DataProviderUsage.MANAGED:
throw new Error('This dataprovider is managed, and must not be cloned');
default:
throw new Error('Unkown usage value');
}
}
private function propertyChangedHandler(source : IWatchable) : void
{
var names : Vector.<String> = _propertyToNames[source];
var numNames : uint = names.length;
for (var nameId : uint = 0; nameId < numNames; ++nameId)
_propertyChanged.execute(this, names[nameId]);
}
}
}
|
add DataProvider.dispose() method to remove/unwatch all properties and free the memory
|
add DataProvider.dispose() method to remove/unwatch all properties and free the memory
|
ActionScript
|
mit
|
aerys/minko-as3
|
667118c2a761b50b382d87085b5006fd3599dc46
|
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
|
kdp3Lib/src/com/kaltura/kdpfl/ApplicationFacade.as
|
package com.kaltura.kdpfl
{
import com.kaltura.kdpfl.controller.InitMacroCommand;
import com.kaltura.kdpfl.controller.LayoutReadyCommand;
import com.kaltura.kdpfl.controller.PlaybackCompleteCommand;
import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand;
import com.kaltura.kdpfl.controller.SequenceSkipNextCommand;
import com.kaltura.kdpfl.controller.StartupCommand;
import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand;
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.controller.media.MediaReadyCommand;
import com.kaltura.kdpfl.events.DynamicEvent;
import com.kaltura.kdpfl.model.ExternalInterfaceProxy;
import com.kaltura.kdpfl.model.type.DebugLevel;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import com.kaltura.puremvc.as3.core.KView;
import flash.display.DisplayObject;
import mx.utils.ObjectProxy;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.IFacade;
import org.puremvc.as3.interfaces.IMediator;
import org.puremvc.as3.interfaces.IProxy;
import org.puremvc.as3.patterns.facade.Facade;
public class ApplicationFacade extends Facade implements IFacade
{
/**
* The current version of the KDP.
*/
public var kdpVersion : String = "v3.9.1";
/**
* save any mediator name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _mediatorNameArray : Array = new Array();
/**
* save any proxy name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _proxyNameArray : Array = new Array();
/**
* save any notification that create a command name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _commandNameArray : Array = new Array();
/**
* The bindObject create dynamicly all attributes that need to be binded on it
*/
public var bindObject:ObjectProxy = new ObjectProxy();
/**
* a reference to KDP3 main application
*/
private var _app : DisplayObject;
/**
* the url of the kdp
*/
public var appFolder : String;
public var debugMode : Boolean = false;
/**
*
* will affect the traces that will be sent. See DebugLevel enum
*/
public var debugLevel:int;
private var externalInterface : ExternalInterfaceProxy;
/**
* return the one and only instance of the ApplicationFacade,
* if not exist it will be created.
* @return
*
*/
public static function getInstance() : ApplicationFacade
{
if (instance == null) instance = new ApplicationFacade();
return instance as ApplicationFacade;
}
/**
* All this simply does is fire a notification which is routed to
* "StartupCommand" via the "registerCommand" handlers
* @param app
*
*/
public function start(app:DisplayObject):void
{
CONFIG::isSDK46 {
kdpVersion += ".sdk46";
}
_app = app;
appFolder = app.root.loaderInfo.url;
appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1);
sendNotification(NotificationType.STARTUP, app);
externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy;
}
/**
* Created to trace all notifications for debug
* @param notificationName
* @param body
* @param type
*
*/
override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void {
if (debugMode) {
var s:String;
if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) ||
(notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) ||
(notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE))
{
if (notificationName == NotificationType.PLAYER_STATE_CHANGE)
s = 'Sent ' + notificationName + ' ==> ' + body.toString();
else {
s = 'Sent ' + notificationName;
if (body) {
var found:Boolean = false;
for (var o:* in body) {
s += ", " + o + ":" + body[o];
found = true;
}
if (!found) {
s += ", " + body.toString();
}
}
}
}
if (s && s != "null") {
var curTime:Number = 0;
var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator;
if (kmediaPlayerMediator &&
kmediaPlayerMediator.player &&
kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING &&
kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED &&
kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR)
{
curTime = kmediaPlayerMediator.getCurrentTime();
}
var date:Date = new Date();
KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime);
}
}
super.sendNotification(notificationName, body, type);
//For external Flash/Flex application application listening to the KDP events
_app.dispatchEvent(new DynamicEvent(notificationName, body));
//For external Javascript application listening to the KDP events
if (externalInterface)
externalInterface.notifyJs(notificationName, body);
}
/**
* controls the routing of notifications to our controllers,
* we all know them as commands
*
*/
override protected function initializeController():void
{
super.initializeController();
registerCommand(NotificationType.STARTUP, StartupCommand);
// we do both init start KDP life cycle, and start to load the entry simultaneously
registerCommand(NotificationType.INITIATE_APP, InitMacroCommand);
//There are several things that need to be done as soon as the layout of the kdp is ready.
registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand );
//when one call change media we fire the load media command again
registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand);
registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand );
registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand );
registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand);
registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand);
registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand);
}
override protected function initializeView():void
{
if ( view != null ) return;
view = KView.getInstance();
}
override protected function initializeFacade():void
{
initializeView();
initializeModel();
initializeController();
}
/**
* Help to remove all commands, mediator, proxies from the facade
*
*/
public function dispose() : void
{
var i:int =0;
for(i=0; i<_commandNameArray.length; i++)
this.removeCommand( _commandNameArray[i] );
for(i=0; i<_mediatorNameArray.length; i++)
this.removeMediator( _mediatorNameArray[i] );
for(i=0; i<_proxyNameArray.length; i++)
this.removeProxy( _proxyNameArray[i] );
_commandNameArray = new Array();
_mediatorNameArray = new Array();
_proxyNameArray = new Array();
}
/**
* after registartion add the notification name to a
* @param notificationName
* @param commandClassRef
*
*/
override public function registerCommand(notificationName:String, commandClassRef:Class):void
{
super.registerCommand(notificationName, commandClassRef);
//save the notification name so we can delete it later
_commandNameArray.push( notificationName );
}
override public function registerMediator(mediator:IMediator):void
{
super.registerMediator(mediator);
//save the mediator name so we can delete it later
_mediatorNameArray.push( mediator.getMediatorName() );
}
override public function registerProxy(proxy:IProxy):void
{
bindObject[proxy.getProxyName()] = proxy.getData();
super.registerProxy(proxy);
//save the proxy name so we can delete it later
_proxyNameArray.push( proxy.getProxyName() );
}
/**
* add notification observer for a given mediator
* @param notification the notification to listen for
* @param notificationHandler handler to be called
* @param mediator
*
*/
public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void {
(view as KView).addNotificationInterest(notification, notificationHandler, mediator);
}
public function get app () : DisplayObject
{
return _app;
}
public function set app (disObj : DisplayObject) : void
{
_app = disObj;
}
}
}
|
package com.kaltura.kdpfl
{
import com.kaltura.kdpfl.controller.InitMacroCommand;
import com.kaltura.kdpfl.controller.LayoutReadyCommand;
import com.kaltura.kdpfl.controller.PlaybackCompleteCommand;
import com.kaltura.kdpfl.controller.SequenceItemPlayEndCommand;
import com.kaltura.kdpfl.controller.SequenceSkipNextCommand;
import com.kaltura.kdpfl.controller.StartupCommand;
import com.kaltura.kdpfl.controller.media.InitChangeMediaMacroCommand;
import com.kaltura.kdpfl.controller.media.LiveStreamCommand;
import com.kaltura.kdpfl.controller.media.MediaReadyCommand;
import com.kaltura.kdpfl.events.DynamicEvent;
import com.kaltura.kdpfl.model.ExternalInterfaceProxy;
import com.kaltura.kdpfl.model.type.DebugLevel;
import com.kaltura.kdpfl.model.type.NotificationType;
import com.kaltura.kdpfl.view.controls.KTrace;
import com.kaltura.kdpfl.view.media.KMediaPlayerMediator;
import com.kaltura.puremvc.as3.core.KView;
import flash.display.DisplayObject;
import mx.utils.ObjectProxy;
import org.osmf.media.MediaPlayerState;
import org.puremvc.as3.interfaces.IFacade;
import org.puremvc.as3.interfaces.IMediator;
import org.puremvc.as3.interfaces.IProxy;
import org.puremvc.as3.patterns.facade.Facade;
public class ApplicationFacade extends Facade implements IFacade
{
/**
* The current version of the KDP.
*/
public var kdpVersion : String = "v3.9.2";
/**
* save any mediator name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _mediatorNameArray : Array = new Array();
/**
* save any proxy name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _proxyNameArray : Array = new Array();
/**
* save any notification that create a command name that is registered to this array in order to delete at any time
* (the pure mvc don't support it as built-in function)
*/
private var _commandNameArray : Array = new Array();
/**
* The bindObject create dynamicly all attributes that need to be binded on it
*/
public var bindObject:ObjectProxy = new ObjectProxy();
/**
* a reference to KDP3 main application
*/
private var _app : DisplayObject;
/**
* the url of the kdp
*/
public var appFolder : String;
public var debugMode : Boolean = false;
/**
*
* will affect the traces that will be sent. See DebugLevel enum
*/
public var debugLevel:int;
private var externalInterface : ExternalInterfaceProxy;
/**
* return the one and only instance of the ApplicationFacade,
* if not exist it will be created.
* @return
*
*/
public static function getInstance() : ApplicationFacade
{
if (instance == null) instance = new ApplicationFacade();
return instance as ApplicationFacade;
}
/**
* All this simply does is fire a notification which is routed to
* "StartupCommand" via the "registerCommand" handlers
* @param app
*
*/
public function start(app:DisplayObject):void
{
CONFIG::isSDK46 {
kdpVersion += ".sdk46";
}
_app = app;
appFolder = app.root.loaderInfo.url;
appFolder = appFolder.substr(0, appFolder.lastIndexOf('/') + 1);
sendNotification(NotificationType.STARTUP, app);
externalInterface = retrieveProxy(ExternalInterfaceProxy.NAME) as ExternalInterfaceProxy;
}
/**
* Created to trace all notifications for debug
* @param notificationName
* @param body
* @param type
*
*/
override public function sendNotification(notificationName:String, body:Object = null, type:String = null):void {
if (debugMode) {
var s:String;
if ((notificationName == NotificationType.BYTES_DOWNLOADED_CHANGE && debugLevel == DebugLevel.HIGH) ||
(notificationName == NotificationType.PLAYER_UPDATE_PLAYHEAD && (debugLevel == DebugLevel.HIGH || debugLevel == DebugLevel.MEDIUM)) ||
(notificationName != NotificationType.PLAYER_UPDATE_PLAYHEAD && notificationName != NotificationType.BYTES_DOWNLOADED_CHANGE))
{
if (notificationName == NotificationType.PLAYER_STATE_CHANGE)
s = 'Sent ' + notificationName + ' ==> ' + body.toString();
else {
s = 'Sent ' + notificationName;
if (body) {
var found:Boolean = false;
for (var o:* in body) {
s += ", " + o + ":" + body[o];
found = true;
}
if (!found) {
s += ", " + body.toString();
}
}
}
}
if (s && s != "null") {
var curTime:Number = 0;
var kmediaPlayerMediator:KMediaPlayerMediator = retrieveMediator(KMediaPlayerMediator.NAME) as KMediaPlayerMediator;
if (kmediaPlayerMediator &&
kmediaPlayerMediator.player &&
kmediaPlayerMediator.player.state!=MediaPlayerState.LOADING &&
kmediaPlayerMediator.player.state!=MediaPlayerState.UNINITIALIZED &&
kmediaPlayerMediator.player.state!=MediaPlayerState.PLAYBACK_ERROR)
{
curTime = kmediaPlayerMediator.getCurrentTime();
}
var date:Date = new Date();
KTrace.getInstance().log(date.toTimeString(), ":", s, ", playhead position:", curTime);
}
}
super.sendNotification(notificationName, body, type);
//For external Flash/Flex application application listening to the KDP events
_app.dispatchEvent(new DynamicEvent(notificationName, body));
//For external Javascript application listening to the KDP events
if (externalInterface)
externalInterface.notifyJs(notificationName, body);
}
/**
* controls the routing of notifications to our controllers,
* we all know them as commands
*
*/
override protected function initializeController():void
{
super.initializeController();
registerCommand(NotificationType.STARTUP, StartupCommand);
// we do both init start KDP life cycle, and start to load the entry simultaneously
registerCommand(NotificationType.INITIATE_APP, InitMacroCommand);
//There are several things that need to be done as soon as the layout of the kdp is ready.
registerCommand(NotificationType.LAYOUT_READY, LayoutReadyCommand );
//when one call change media we fire the load media command again
registerCommand(NotificationType.CHANGE_MEDIA, InitChangeMediaMacroCommand);
registerCommand (NotificationType.LIVE_ENTRY, LiveStreamCommand );
registerCommand (NotificationType.MEDIA_LOADED, MediaReadyCommand );
registerCommand (NotificationType.PLAYBACK_COMPLETE, PlaybackCompleteCommand);
registerCommand(NotificationType.SEQUENCE_ITEM_PLAY_END, SequenceItemPlayEndCommand);
registerCommand(NotificationType.SEQUENCE_SKIP_NEXT, SequenceSkipNextCommand);
}
override protected function initializeView():void
{
if ( view != null ) return;
view = KView.getInstance();
}
override protected function initializeFacade():void
{
initializeView();
initializeModel();
initializeController();
}
/**
* Help to remove all commands, mediator, proxies from the facade
*
*/
public function dispose() : void
{
var i:int =0;
for(i=0; i<_commandNameArray.length; i++)
this.removeCommand( _commandNameArray[i] );
for(i=0; i<_mediatorNameArray.length; i++)
this.removeMediator( _mediatorNameArray[i] );
for(i=0; i<_proxyNameArray.length; i++)
this.removeProxy( _proxyNameArray[i] );
_commandNameArray = new Array();
_mediatorNameArray = new Array();
_proxyNameArray = new Array();
}
/**
* after registartion add the notification name to a
* @param notificationName
* @param commandClassRef
*
*/
override public function registerCommand(notificationName:String, commandClassRef:Class):void
{
super.registerCommand(notificationName, commandClassRef);
//save the notification name so we can delete it later
_commandNameArray.push( notificationName );
}
override public function registerMediator(mediator:IMediator):void
{
super.registerMediator(mediator);
//save the mediator name so we can delete it later
_mediatorNameArray.push( mediator.getMediatorName() );
}
override public function registerProxy(proxy:IProxy):void
{
bindObject[proxy.getProxyName()] = proxy.getData();
super.registerProxy(proxy);
//save the proxy name so we can delete it later
_proxyNameArray.push( proxy.getProxyName() );
}
/**
* add notification observer for a given mediator
* @param notification the notification to listen for
* @param notificationHandler handler to be called
* @param mediator
*
*/
public function addNotificationInterest(notification:String, notificationHandler:Function, mediator:IMediator):void {
(view as KView).addNotificationInterest(notification, notificationHandler, mediator);
}
public function get app () : DisplayObject
{
return _app;
}
public function set app (disObj : DisplayObject) : void
{
_app = disObj;
}
}
}
|
update version 3.9.2
|
update version 3.9.2
|
ActionScript
|
agpl-3.0
|
shvyrev/kdp,shvyrev/kdp,kaltura/kdp,kaltura/kdp,shvyrev/kdp,kaltura/kdp
|
e2571b2f775656f5a070ec062bdf9535b0d7689b
|
exporter/src/main/as/flump/xfl/XflLayer.as
|
exporter/src/main/as/flump/xfl/XflLayer.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.xfl {
import aspire.util.XmlUtil;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
public class XflLayer
{
public static const NAME :String = "name";
public static const TYPE :String = "layerType";
public static const TYPE_GUIDE :String = "guide";
public static const TYPE_FOLDER :String = "folder";
public static const TYPE_MASK :String = "mask";
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;
// mask
if (mask!=null) layer.mask = mask;
const location :String = baseLocation + ":" + layer.name;
var frameXmlList :XMLList = xml.frames.DOMFrame;
for each (var frameXml :XML in frameXmlList) {
layer.keyframes.push(XflKeyframe.parse(lib, location, frameXml, flipbook));
}
if (layer.keyframes.length == 0) lib.addError(location, ParseError.INFO, "No keyframes on layer");
var ii :int;
var kf :KeyframeMold;
var nextKf :KeyframeMold;
// normalize skews, so that we always skew the shortest distance between
// two angles (we don't want to skew more than Math.PI)
for (ii = 0; ii < layer.keyframes.length - 1; ++ii) {
kf = layer.keyframes[ii];
nextKf = layer.keyframes[ii+1];
frameXml = frameXmlList[ii];
if (kf.skewX + Math.PI < nextKf.skewX) {
nextKf.skewX += -Math.PI * 2;
} else if (kf.skewX - Math.PI > nextKf.skewX) {
nextKf.skewX += Math.PI * 2;
}
if (kf.skewY + Math.PI < nextKf.skewY) {
nextKf.skewY += -Math.PI * 2;
} else if (kf.skewY - Math.PI > nextKf.skewY) {
nextKf.skewY += Math.PI * 2;
}
}
// apply additional rotations
var additionalRotation :Number = 0;
for (ii = 0; ii < layer.keyframes.length - 1; ++ii) {
kf = layer.keyframes[ii];
nextKf = layer.keyframes[ii+1];
frameXml = frameXmlList[ii];
var motionTweenRotate :String = XmlUtil.getStringAttr(frameXml,
XflKeyframe.MOTION_TWEEN_ROTATE, XflKeyframe.MOTION_TWEEN_ROTATE_NONE);
// If a direction is specified, take it into account
if (motionTweenRotate != XflKeyframe.MOTION_TWEEN_ROTATE_NONE) {
var direction :Number = (motionTweenRotate == XflKeyframe.MOTION_TWEEN_ROTATE_CLOCKWISE ? 1 : -1);
// negative scales affect rotation direction
direction *= sign(nextKf.scaleX) * sign(nextKf.scaleY);
while (direction < 0 && kf.skewX < nextKf.skewX) {
nextKf.skewX -= Math.PI * 2;
}
while (direction > 0 && kf.skewX > nextKf.skewX) {
nextKf.skewX += Math.PI * 2;
}
while (direction < 0 && kf.skewY < nextKf.skewY) {
nextKf.skewY -= Math.PI * 2;
}
while (direction > 0 && kf.skewY > nextKf.skewY) {
nextKf.skewY += Math.PI * 2;
}
// additional rotations specified?
var motionTweenRotateTimes :Number =
XmlUtil.getNumberAttr(frameXml, XflKeyframe.MOTION_TWEEN_ROTATE_TIMES, 0);
var thisRotation :Number = motionTweenRotateTimes * Math.PI * 2 * direction;
additionalRotation += thisRotation;
}
nextKf.rotate(additionalRotation);
}
return layer;
}
protected static function sign (n :Number) :Number {
return (n > 0 ? 1 : (n < 0 ? -1 : 0));
}
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.xfl {
import aspire.util.XmlUtil;
import flump.mold.KeyframeMold;
import flump.mold.LayerMold;
public class XflLayer
{
public static const NAME :String = "name";
public static const TYPE :String = "layerType";
public static const TYPE_GUIDE :String = "guide";
public static const TYPE_FOLDER :String = "folder";
public static const TYPE_MASK :String = "mask";
use namespace xflns;
public static function parse (lib :XflLibrary, baseLocation :String, xml :XML, flipbook :Boolean,mask:String=null) :LayerMold {
const layer :LayerMold = new LayerMold();
layer.name = XmlUtil.getStringAttr(xml, NAME);
layer.flipbook = flipbook;
// mask
if (mask!=null) layer.mask = mask;
const location :String = baseLocation + ":" + layer.name;
var frameXmlList :XMLList = xml.frames.DOMFrame;
for each (var frameXml :XML in frameXmlList) {
layer.keyframes.push(XflKeyframe.parse(lib, location, frameXml, flipbook));
}
if (layer.keyframes.length == 0) lib.addError(location, ParseError.INFO, "No keyframes on layer");
var ii :int;
var kf :KeyframeMold;
var nextKf :KeyframeMold;
// normalize skews, so that we always skew the shortest distance between
// two angles (we don't want to skew more than Math.PI)
for (ii = 0; ii < layer.keyframes.length - 1; ++ii) {
kf = layer.keyframes[ii];
nextKf = layer.keyframes[ii+1];
frameXml = frameXmlList[ii];
if (kf.skewX + Math.PI < nextKf.skewX) {
nextKf.skewX += -Math.PI * 2;
} else if (kf.skewX - Math.PI > nextKf.skewX) {
nextKf.skewX += Math.PI * 2;
}
if (kf.skewY + Math.PI < nextKf.skewY) {
nextKf.skewY += -Math.PI * 2;
} else if (kf.skewY - Math.PI > nextKf.skewY) {
nextKf.skewY += Math.PI * 2;
}
}
// apply additional rotations
var additionalRotation :Number = 0;
for (ii = 0; ii < layer.keyframes.length - 1; ++ii) {
kf = layer.keyframes[ii];
nextKf = layer.keyframes[ii+1];
frameXml = frameXmlList[ii];
var motionTweenRotate :String = XmlUtil.getStringAttr(frameXml,
XflKeyframe.MOTION_TWEEN_ROTATE, XflKeyframe.MOTION_TWEEN_ROTATE_NONE);
// If a direction is specified, take it into account
if (motionTweenRotate != XflKeyframe.MOTION_TWEEN_ROTATE_NONE) {
var direction :Number = (motionTweenRotate == XflKeyframe.MOTION_TWEEN_ROTATE_CLOCKWISE ? 1 : -1);
// negative scales affect rotation direction
direction *= sign(nextKf.scaleX) * sign(nextKf.scaleY);
while (direction < 0 && kf.skewX < nextKf.skewX) {
nextKf.skewX -= Math.PI * 2;
}
while (direction > 0 && kf.skewX > nextKf.skewX) {
nextKf.skewX += Math.PI * 2;
}
while (direction < 0 && kf.skewY < nextKf.skewY) {
nextKf.skewY -= Math.PI * 2;
}
while (direction > 0 && kf.skewY > nextKf.skewY) {
nextKf.skewY += Math.PI * 2;
}
// additional rotations specified?
var motionTweenRotateTimes :Number =
XmlUtil.getNumberAttr(frameXml, XflKeyframe.MOTION_TWEEN_ROTATE_TIMES, 0);
var thisRotation :Number = motionTweenRotateTimes * Math.PI * 2 * direction;
additionalRotation += thisRotation;
}
nextKf.rotate(additionalRotation);
}
return layer;
}
protected static function sign (n :Number) :Number {
return (n > 0 ? 1 : (n < 0 ? -1 : 0));
}
}
}
|
fix XflLayer parse signature
|
fix XflLayer parse signature
|
ActionScript
|
mit
|
mathieuanthoine/flump,mathieuanthoine/flump,mathieuanthoine/flump
|
ee8f636d7e68f53282deea141e85146cf83c0d55
|
src/as/com/threerings/ezgame/client/EZGamePanel.as
|
src/as/com/threerings/ezgame/client/EZGamePanel.as
|
package com.threerings.ezgame.client {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.events.Event;
import flash.utils.Dictionary;
import mx.containers.Canvas;
import mx.containers.VBox;
import mx.core.Container;
import mx.core.IChildList;
import mx.utils.DisplayUtil;
import com.threerings.util.MediaContainer;
import com.threerings.mx.controls.ChatDisplayBox;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import com.threerings.ezgame.data.EZGameConfig;
import com.threerings.ezgame.data.EZGameObject;
public class EZGamePanel extends VBox
implements PlaceView
{
/** The game object backend. */
public var backend :GameControlBackend;
public function EZGamePanel (ctx :CrowdContext, ctrl :EZGameController)
{
_ctx = ctx;
_ctrl = ctrl;
//addChild(new ChatDisplayBox(ctx));
}
// from PlaceView
public function willEnterPlace (plobj :PlaceObject) :void
{
var cfg :EZGameConfig = (_ctrl.getPlaceConfig() as EZGameConfig);
_ezObj = (plobj as EZGameObject);
backend = new GameControlBackend(_ctx, _ezObj);
_gameView = new GameContainer(cfg.configData); // TODO?
backend.setSharedEvents(
Loader(_gameView.getMedia()).contentLoaderInfo.sharedEvents);
backend.setContainer(_gameView);
addChild(_gameView);
}
// from PlaceView
public function didLeavePlace (plobj :PlaceObject) :void
{
_gameView.shutdown(true);
removeChild(_gameView);
backend.shutdown();
}
protected var _ctx :CrowdContext;
protected var _ctrl :EZGameController;
protected var _gameView :GameContainer;
protected var _ezObj :EZGameObject;
}
}
|
package com.threerings.ezgame.client {
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.events.Event;
import flash.utils.Dictionary;
import mx.containers.Canvas;
import mx.containers.VBox;
import mx.core.Container;
import mx.core.IChildList;
import mx.utils.DisplayUtil;
import com.threerings.util.MediaContainer;
import com.threerings.mx.controls.ChatDisplayBox;
import com.threerings.crowd.client.PlaceView;
import com.threerings.crowd.data.PlaceObject;
import com.threerings.crowd.util.CrowdContext;
import com.threerings.ezgame.data.EZGameConfig;
import com.threerings.ezgame.data.EZGameObject;
public class EZGamePanel extends VBox
implements PlaceView
{
/** The game object backend. */
public var backend :GameControlBackend;
public function EZGamePanel (ctx :CrowdContext, ctrl :EZGameController)
{
_ctx = ctx;
_ctrl = ctrl;
//addChild(new ChatDisplayBox(ctx));
}
// from PlaceView
public function willEnterPlace (plobj :PlaceObject) :void
{
var cfg :EZGameConfig = (_ctrl.getPlaceConfig() as EZGameConfig);
_ezObj = (plobj as EZGameObject);
backend = createBackend();
_gameView = new GameContainer(cfg.configData); // TODO?
backend.setSharedEvents(
Loader(_gameView.getMedia()).contentLoaderInfo.sharedEvents);
backend.setContainer(_gameView);
addChild(_gameView);
}
// from PlaceView
public function didLeavePlace (plobj :PlaceObject) :void
{
_gameView.shutdown(true);
removeChild(_gameView);
backend.shutdown();
}
/**
* Creates the backend object that will handle requests from user code.
*/
protected function createBackend () :GameControlBackend
{
return new GameControlBackend(_ctx, _ezObj);
}
protected var _ctx :CrowdContext;
protected var _ctrl :EZGameController;
protected var _gameView :GameContainer;
protected var _ezObj :EZGameObject;
}
}
|
Allow subclasses to create custom backends.
|
Allow subclasses to create custom backends.
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@143 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
1904f15da90673bb70650e0a796cbdf3ac2749b7
|
src/org/mangui/HLS/streaming/AutoLevelManager.as
|
src/org/mangui/HLS/streaming/AutoLevelManager.as
|
package org.mangui.HLS.streaming {
import org.mangui.HLS.*;
import org.mangui.HLS.utils.Log;
/** Class that manages auto level selection **/
public class AutoLevelManager {
/** Reference to the HLS controller. **/
private var _hls:HLS;
/** Reference to the manifest levels. **/
private var _levels:Array;
/** switch up threshold **/
private var _switchup:Array = null;
/** switch down threshold **/
private var _switchdown:Array = null;
/** Create the loader. **/
public function AutoLevelManager(hls:HLS):void {
_hls = hls;
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
};
/** Store the manifest data. **/
private function _manifestLoadedHandler(event:HLSEvent):void {
_levels = event.levels;
_initlevelswitch();
};
/* initialize level switching heuristic tables */
private function _initlevelswitch():void {
var i:Number;
var maxswitchup:Number=0;
var minswitchdwown:Number=Number.MAX_VALUE;
_switchup = new Array(_levels.length);
_switchdown = new Array(_levels.length);
for(i=0 ; i < _levels.length-1; i++) {
_switchup[i] = (_levels[i+1].bitrate - _levels[i].bitrate) / _levels[i].bitrate;
maxswitchup = Math.max(maxswitchup,_switchup[i]);
}
for(i=0 ; i < _levels.length-1; i++) {
_switchup[i] = Math.min(maxswitchup,2*_switchup[i]);
//Log.txt("_switchup["+i+"]="+_switchup[i]);
}
for(i = 1; i < _levels.length; i++) {
_switchdown[i] = (_levels[i].bitrate - _levels[i-1].bitrate) / _levels[i].bitrate;
minswitchdwown =Math.min(minswitchdwown,_switchdown[i]);
}
for(i = 1; i < _levels.length; i++) {
_switchdown[i] = Math.max(2*minswitchdwown,_switchdown[i]);
//Log.txt("_switchdown["+i+"]="+_switchdown[i]);
}
}
/** Update the quality level for the next fragment load. **/
public function getnextlevel(current_level:Number, buffer:Number, last_segment_duration:Number, last_fetch_duration:Number, last_bandwidth:Number):Number {
var i:Number;
var level:Number = -1;
// Select the lowest non-audio level.
for(i = 0; i < _levels.length; i++) {
if(!_levels[i].audio) {
level = i;
break;
}
}
if(level == -1) {
Log.txt("No other quality levels are available");
return -1;
}
if(last_fetch_duration == 0 || last_segment_duration == 0) {
return 0;
}
var fetchratio:Number = last_segment_duration/last_fetch_duration;
var bufferratio:Number = 1000*buffer/last_segment_duration;
//Log.txt("fetchratio:" + fetchratio);
//Log.txt("bufferratio:" + bufferratio);
/* to switch level up :
fetchratio should be greater than switch up condition,
but also, when switching levels, we might have to load two fragments :
- first one for PTS analysis,
- second one for NetStream injection
the condition (bufferratio > 2*_levels[_level+1].bitrate/_last_bandwidth)
ensures that buffer time is bigger than than the time to download 2 fragments from current_level+1, if we keep same bandwidth
*/
if((current_level < _levels.length-1) && (fetchratio > (1+_switchup[current_level])) && (bufferratio > 2*_levels[current_level+1].bitrate/last_bandwidth)) {
//Log.txt("fetchratio:> 1+_switchup[_level]="+(1+_switchup[current_level]));
//Log.txt("switch to level " + (current_level+1));
//level up
return (current_level+1);
}
/* to switch level down :
fetchratio should be smaller than switch down condition,
or buffer time is too small to retrieve one fragment with current level
*/
else if(current_level > 0 &&((fetchratio < (1-_switchdown[current_level])) || (bufferratio < 1)) ) {
//Log.txt("bufferratio < 2 || fetchratio: < 1-_switchdown[_level]="+(1-_switchdown[_level]));
/* find suitable level matching current bandwidth, starting from current level
when switching level down, we also need to consider that we might need to load two fragments.
the condition (bufferratio > 2*_levels[j].bitrate/_last_bandwidth)
ensures that buffer time is bigger than than the time to download 2 fragments from level j, if we keep same bandwidth
*/
for(var j:Number = current_level-1; j > 0; j--) {
if( _levels[j].bitrate <= last_bandwidth && (bufferratio > 2*_levels[j].bitrate/last_bandwidth)) {
Log.txt("switch to level " + j);
return j;
}
}
Log.txt("switch to level 0");
return 0;
}
return current_level;
}
}
}
|
package org.mangui.HLS.streaming {
import org.mangui.HLS.*;
import org.mangui.HLS.utils.Log;
/** Class that manages auto level selection **/
public class AutoLevelManager {
/** Reference to the HLS controller. **/
private var _hls:HLS;
/** switch up threshold **/
private var _switchup:Array = null;
/** switch down threshold **/
private var _switchdown:Array = null;
/** bitrate array **/
private var _bitrate:Array = null;
/** nb level **/
private var _nbLevel:Number = 0;
/** lowest non audio level **/
private var _lowestNonAudioLevel:Number = -1;
/** Create the loader. **/
public function AutoLevelManager(hls:HLS):void {
_hls = hls;
_hls.addEventListener(HLSEvent.MANIFEST_LOADED, _manifestLoadedHandler);
};
/** Store the manifest data. **/
private function _manifestLoadedHandler(event:HLSEvent):void {
var levels:Array= event.levels;
var maxswitchup:Number=0;
var minswitchdwown:Number=Number.MAX_VALUE;
_nbLevel = levels.length;
_bitrate = new Array(_nbLevel);
_switchup = new Array(_nbLevel);
_switchdown = new Array(_nbLevel);
var i:Number;
for(i=0 ; i < _nbLevel; i++) {
_bitrate[i] = levels[i].bitrate;
}
// Select the lowest non-audio level.
for(i = 0; i < _nbLevel; i++) {
if(!levels[i].audio) {
_lowestNonAudioLevel = i;
break;
}
}
for(i=0 ; i < _nbLevel-1; i++) {
_switchup[i] = (_bitrate[i+1] - _bitrate[i]) / _bitrate[i];
maxswitchup = Math.max(maxswitchup,_switchup[i]);
}
for(i=0 ; i < _nbLevel-1; i++) {
_switchup[i] = Math.min(maxswitchup,2*_switchup[i]);
//Log.txt("_switchup["+i+"]="+_switchup[i]);
}
for(i = 1; i < _nbLevel; i++) {
_switchdown[i] = (_bitrate[i] - _bitrate[i-1]) / _bitrate[i];
minswitchdwown =Math.min(minswitchdwown,_switchdown[i]);
}
for(i = 1; i < _nbLevel; i++) {
_switchdown[i] = Math.max(2*minswitchdwown,_switchdown[i]);
//Log.txt("_switchdown["+i+"]="+_switchdown[i]);
}
};
/** Update the quality level for the next fragment load. **/
public function getnextlevel(current_level:Number, buffer:Number, last_segment_duration:Number, last_fetch_duration:Number, last_bandwidth:Number):Number {
var i:Number;
var level:Number = _lowestNonAudioLevel;
if(level == -1) {
Log.txt("No other quality levels are available");
return -1;
}
if(last_fetch_duration == 0 || last_segment_duration == 0) {
return 0;
}
var fetchratio:Number = last_segment_duration/last_fetch_duration;
var bufferratio:Number = 1000*buffer/last_segment_duration;
//Log.txt("fetchratio:" + fetchratio);
//Log.txt("bufferratio:" + bufferratio);
/* to switch level up :
fetchratio should be greater than switch up condition,
but also, when switching levels, we might have to load two fragments :
- first one for PTS analysis,
- second one for NetStream injection
the condition (bufferratio > 2*_levels[_level+1].bitrate/_last_bandwidth)
ensures that buffer time is bigger than than the time to download 2 fragments from current_level+1, if we keep same bandwidth
*/
if((current_level < _nbLevel-1) && (fetchratio > (1+_switchup[current_level])) && (bufferratio > 2*_bitrate[current_level+1]/last_bandwidth)) {
//Log.txt("fetchratio:> 1+_switchup[_level]="+(1+_switchup[current_level]));
//Log.txt("switch to level " + (current_level+1));
//level up
return (current_level+1);
}
/* to switch level down :
fetchratio should be smaller than switch down condition,
or buffer time is too small to retrieve one fragment with current level
*/
else if(current_level > 0 && ((fetchratio < (1-_switchdown[current_level])) || (bufferratio < 1)) ) {
//Log.txt("bufferratio < 2 || fetchratio: < 1-_switchdown[_level]="+(1-_switchdown[_level]));
/* find suitable level matching current bandwidth, starting from current level
when switching level down, we also need to consider that we might need to load two fragments.
the condition (bufferratio > 2*_levels[j].bitrate/_last_bandwidth)
ensures that buffer time is bigger than than the time to download 2 fragments from level j, if we keep same bandwidth
*/
for(var j:Number = current_level-1; j > 0; j--) {
if( _bitrate[j] <= last_bandwidth && (bufferratio > 2*_bitrate[j]/last_bandwidth)) {
Log.txt("switch to level " + j);
return j;
}
}
Log.txt("switch to level 0");
return 0;
}
return current_level;
}
}
}
|
remove dependencies on global levels Array (make the code re-entrant)
|
remove dependencies on global levels Array (make the code re-entrant)
|
ActionScript
|
mpl-2.0
|
desaintmartin/hlsprovider,desaintmartin/hlsprovider,desaintmartin/hlsprovider
|
bff95367e7657906745761bf06f795bb767219e0
|
src/flails/resource/Resource.as
|
src/flails/resource/Resource.as
|
/**
* Copyright (c) 2009 Lance Carlson
* See LICENSE for full license information.
*/
package flails.resource {
import flails.request.RequestPipe;
import flails.request.HTTPClient;
import flails.request.ResourcePathBuilder;
import flails.request.JSONFilter;
import flash.utils.getQualifiedClassName;
import mx.core.IMXMLObject;
public class Resource {
public var name:String;
public var instanceClass:Class;
public function Resource() {}
public function initialized(parent:Object, id:String):void {
}
public function index(resultHandler:Function, errorHandler:Function = null):void {
requestPipe(resultHandler, errorHandler).index();
}
public function show(id:Number, resultHandler:Function, errorHandler:Function = null):void {
requestPipe(resultHandler, errorHandler).show(id);
}
public function requestPipe(resultHandler:Function, errorHandler:Function):RequestPipe {
// TODO: The pluralization obviously needs to be taken care of
var pipe:RequestPipe = new HTTPClient(new ResourcePathBuilder(name), new JSONFilter(instanceClass));
pipe.addEventListener("result", resultHandler);
return pipe;
}
}
}
|
/**
* Copyright (c) 2009 Lance Carlson
* See LICENSE for full license information.
*/
package flails.resource {
import flails.request.RequestPipe;
import flails.request.HTTPClient;
import flails.request.ResourcePathBuilder;
import flails.request.JSONFilter;
import mx.core.IMXMLObject;
public class Resource implements IMXMLObject {
public var name:String;
public var instanceClass:Class;
public function Resource() {}
public function initialized(parent:Object, id:String):void {
if (name == null) throw new Error("Name not set for resource.");
if (instanceClass == null) instanceClass = Record;
}
public function index(resultHandler:Function, errorHandler:Function = null):void {
requestPipe(resultHandler, errorHandler).index();
}
public function show(id:Number, resultHandler:Function, errorHandler:Function = null):void {
requestPipe(resultHandler, errorHandler).show(id);
}
public function requestPipe(resultHandler:Function, errorHandler:Function):RequestPipe {
// TODO: The pluralization obviously needs to be taken care of
var pipe:RequestPipe = new HTTPClient(new ResourcePathBuilder(name), new JSONFilter(instanceClass));
pipe.addEventListener("result", resultHandler);
return pipe;
}
}
}
|
Implement IMXMLObject. Some defaults and checks.
|
Implement IMXMLObject. Some defaults and checks.
|
ActionScript
|
mit
|
lancecarlson/flails,lancecarlson/flails
|
c7b6d2e9e409c49e9211a6a9ec0d8f9251f05c61
|
src/aerys/minko/render/material/phong/multipass/ZPrepassShader.as
|
src/aerys/minko/render/material/phong/multipass/ZPrepassShader.as
|
package aerys.minko.render.material.phong.multipass
{
import aerys.minko.render.RenderTarget;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart;
import aerys.minko.type.enum.ColorMask;
public class ZPrepassShader extends Shader
{
private var _vertexAnimationPart : VertexAnimationShaderPart;
public function ZPrepassShader(renderTarget : RenderTarget = null,
priority : Number = 0.0)
{
super(renderTarget, priority);
_vertexAnimationPart = new VertexAnimationShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
super.initializeSettings(settings);
settings.colorMask = ColorMask.NONE;
}
override protected function getVertexPosition():SFloat
{
return localToScreen(_vertexAnimationPart.getAnimatedVertexPosition());
}
override protected function getPixelColor():SFloat
{
return float4(0, 0, 0, 0);
}
}
}
|
package aerys.minko.render.material.phong.multipass
{
import aerys.minko.render.RenderTarget;
import aerys.minko.render.material.basic.BasicProperties;
import aerys.minko.render.shader.SFloat;
import aerys.minko.render.shader.Shader;
import aerys.minko.render.shader.ShaderSettings;
import aerys.minko.render.shader.part.DiffuseShaderPart;
import aerys.minko.render.shader.part.animation.VertexAnimationShaderPart;
import aerys.minko.type.enum.ColorMask;
public class ZPrepassShader extends Shader
{
private var _vertexAnimationPart : VertexAnimationShaderPart;
private var _diffuseShaderPart : DiffuseShaderPart;
public function ZPrepassShader(renderTarget : RenderTarget = null,
priority : Number = 0.0)
{
super(renderTarget, priority);
_diffuseShaderPart = new DiffuseShaderPart(this);
_vertexAnimationPart = new VertexAnimationShaderPart(this);
}
override protected function initializeSettings(settings : ShaderSettings) : void
{
super.initializeSettings(settings);
settings.colorMask = ColorMask.NONE;
}
override protected function getVertexPosition():SFloat
{
return localToScreen(_vertexAnimationPart.getAnimatedVertexPosition());
}
override protected function getPixelColor():SFloat
{
if (meshBindings.propertyExists(BasicProperties.ALPHA_THRESHOLD))
{
var diffuseColor : SFloat = _diffuseShaderPart.getDiffuseColor(false);
var alphaThreshold : SFloat = meshBindings.getParameter(
BasicProperties.ALPHA_THRESHOLD, 1
);
kill(subtract(0.5, lessThan(diffuseColor.w, alphaThreshold)));
}
return float4(0, 0, 0, 0);
}
}
}
|
Fix alpha threshold on multi pass phong effect
|
Fix alpha threshold on multi pass phong effect
|
ActionScript
|
mit
|
aerys/minko-as3
|
6de83743fa9c3f68e4b1fcfd05a21c84bbb49dc5
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
src/com/merlinds/miracle_tool/viewer/ViewerView.as
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.display.MiracleImage;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MtfReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
private var _name:String;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TIMELINE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose mesh");
var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
_window.x = this.stage.stageWidth - _window.width;
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
}
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [];
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
if(asset.type == Asset.TIMELINE_TYPE){
_name = asset.name;
}
_assets.push(asset);
// var name:String = asset.name;
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets, 1);
Miracle.currentScene.createImage(_name)
.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
log(this, "selectAnimationHandler", list.selectedItem);
//add animation to miracle
var name:String = list.selectedItem.toString();
}
private function imageAddedToStage(event:Event):void {
var target:MiracleImage = event.target as MiracleImage;
target.moveTO(
this.stage.stageWidth - target.width >> 1,
this.stage.stageHeight - target.height >> 1
);
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
/**
* User: MerlinDS
* Date: 18.07.2014
* Time: 17:42
*/
package com.merlinds.miracle_tool.viewer {
import com.bit101.components.List;
import com.bit101.components.List;
import com.bit101.components.Window;
import com.merlinds.debug.log;
import com.merlinds.miracle.Miracle;
import com.merlinds.miracle.display.MiracleImage;
import com.merlinds.miracle.utils.Asset;
import com.merlinds.miracle.utils.MafReader;
import com.merlinds.miracle.utils.MtfReader;
import com.merlinds.miracle_tool.models.AppModel;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.utils.ByteArray;
[SWF(backgroundColor="0x333333", frameRate=60)]
public class ViewerView extends Sprite {
private var _model:AppModel;
private var _assets:Vector.<Asset>;
private var _window:Window;
private var _name:String;
public function ViewerView(model:AppModel = null) {
super();
_model = model;
if(_model == null){
_model = new AppModel();
}
this.addEventListener(Event.ADDED_TO_STAGE, this.initialize);
}
//==============================================================================
//{region PUBLIC METHODS
//} endregion PUBLIC METHODS ===================================================
//==============================================================================
//{region PRIVATE\PROTECTED METHODS
private function initialize(event:Event):void {
this.removeEventListener(event.type, this.initialize);
this.stage.scaleMode = StageScaleMode.NO_SCALE;
this.stage.align = StageAlign.TOP_LEFT;
Miracle.start(this.stage, this.createHandler, true);
}
private function choseAnimation():void {
//find animation asset and add all of animations to chose list
var n:int = _assets.length;
for(var i:int = 0; i < n; i++){
var asset:Asset = _assets[i];
if(asset.type == Asset.TIMELINE_TYPE){
//parse output
_window = new Window(this, 0, 0, "Chose mesh");
var list:List = new List(_window, 0, 0, this.getAnimations(asset.output));
_window.x = this.stage.stageWidth - _window.width;
list.addEventListener(Event.SELECT, this.selectAnimationHandler);
}
}
}
private function getAnimations(bytes:ByteArray):Array {
var result:Array = [];
var reader:MafReader = new MafReader();
reader.execute(bytes);
var animations:Vector.<Object> = reader.animations;
for each(var animation:Object in animations){
result.push(animation.name);
}
return result;
}
//} endregion PRIVATE\PROTECTED METHODS ========================================
//==============================================================================
//{region EVENTS HANDLERS
private function createHandler(animation:Boolean = false):void {
//TODO: Show view if it exit
if(animation || _model.viewerInput == null){
_model.viewerInput = _model.lastFileDirection;
_model.viewerInput.addEventListener(Event.SELECT, this.selectFileHandler);
_model.viewerInput.browseForOpen("Open " + animation ? "Animation" : "Sprite"
+ "file that you want to view");
}
}
private function selectFileHandler(event:Event):void {
_model.viewerInput.removeEventListener(event.type, this.selectFileHandler);
_model.lastFileDirection = _model.viewerInput.parent;
var byteArray:ByteArray = new ByteArray();
var stream:FileStream = new FileStream();
stream.open(_model.viewerInput, FileMode.READ);
stream.readBytes(byteArray);
stream.close();
//parse
if(_assets == null)_assets = new <Asset>[];
var asset:Asset = new Asset(_model.viewerInput.name, byteArray);
if(asset.type == Asset.TIMELINE_TYPE){
_name = asset.name;
}
_assets.push(asset);
// var name:String = asset.name;
if(_assets.length > 1){
this.choseAnimation();
Miracle.createScene(_assets, 1);
Miracle.currentScene.createImage(_name)
.addEventListener(Event.ADDED_TO_STAGE, this.imageAddedToStage);
Miracle.resume();
}else{
this.createHandler(true);
}
}
private function selectAnimationHandler(event:Event):void {
var list:List = event.target as List;
log(this, "selectAnimationHandler", list.selectedItem);
//add animation to miracle
var name:String = list.selectedItem.toString();
}
private function imageAddedToStage(event:Event):void {
var target:MiracleImage = event.target as MiracleImage;
target.moveTO(
this.stage.stageWidth - target.width >> 1,
this.stage.stageHeight - target.height >> 1
);
}
//} endregion EVENTS HANDLERS ==================================================
//==============================================================================
//{region GETTERS/SETTERS
//} endregion GETTERS/SETTERS ==================================================
}
}
|
create animation format in miracle
|
create animation format in miracle
|
ActionScript
|
mit
|
MerlinDS/miracle_tool
|
4115b0d9a633c13bbb4b78b6511e0e98207841af
|
src/aerys/minko/render/geometry/stream/IndexStream.as
|
src/aerys/minko/render/geometry/stream/IndexStream.as
|
package aerys.minko.render.geometry.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.type.Signal;
import flash.utils.ByteArray;
public final class IndexStream
{
use namespace minko_stream;
minko_stream var _data : Vector.<uint> = null;
private var _usage : uint = 0;
private var _resource : IndexBuffer3DResource = null;
private var _length : uint = 0;
private var _changed : Signal = new Signal('IndexStream.changed');
public function get usage() : uint
{
return _usage;
}
public function get resource() : IndexBuffer3DResource
{
return _resource;
}
public function get length() : uint
{
return _length;
}
public function set length(value : uint) : void
{
_data.length = value;
invalidate();
}
public function get changed() : Signal
{
return _changed;
}
public function IndexStream(usage : uint,
data : Vector.<uint> = null,
length : uint = 0)
{
super();
initialize(data, length, usage);
}
minko_stream function invalidate() : void
{
_length = _data.length;
_changed.execute(this);
}
private function initialize(indices : Vector.<uint>,
length : uint,
usage : uint) : void
{
_usage = usage;
_resource = new IndexBuffer3DResource(this);
if (indices)
{
var numIndices : int = indices && length == 0
? indices.length
: Math.min(indices.length, length);
_data = new Vector.<uint>(numIndices);
for (var i : int = 0; i < numIndices; ++i)
_data[i] = indices[i];
}
else
{
_data = dummyData(length);
}
invalidate();
}
public function get(index : int) : uint
{
checkReadUsage(this);
return _data[index];
}
public function set(index : int, value : uint) : void
{
checkWriteUsage(this);
_data[index] = value;
}
public function deleteTriangleByIndex(index : int) : Vector.<uint>
{
checkWriteUsage(this);
var deletedIndices : Vector.<uint> = _data.splice(index, 3);
invalidate();
return deletedIndices;
}
public function getIndices(indices : Vector.<uint> = null) : Vector.<uint>
{
checkReadUsage(this);
var numIndices : int = length;
indices ||= new Vector.<uint>();
for (var i : int = 0; i < numIndices; ++i)
indices[i] = _data[i];
return indices;
}
public function setIndices(indices : Vector.<uint>) : void
{
checkWriteUsage(this);
var length : int = indices.length;
for (var i : int = 0; i < length; ++i)
_data[i] = indices[i];
_data.length = length;
invalidate();
}
public function clone() : IndexStream
{
return new IndexStream(_usage, _data, length);
}
public function toString() : String
{
return _data.toString();
}
public function concat(indexStream : IndexStream,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : IndexStream
{
checkReadUsage(indexStream);
checkWriteUsage(this);
var numIndices : int = _data.length;
var toConcat : Vector.<uint> = indexStream._data;
count ||= toConcat.length;
for (var i : int = 0; i < count; ++i, ++numIndices)
_data[numIndices] = toConcat[int(firstIndex + i)] + offset;
invalidate();
return this;
}
public function push(indices : Vector.<uint>,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : void
{
checkWriteUsage(this);
var numIndices : int = _data.length;
count ||= indices.length;
for (var i : int = 0; i < count; ++i)
_data[int(numIndices++)] = indices[int(firstIndex + i)] + offset;
invalidate();
}
public function disposeLocalData() : void
{
if (length != resource.numIndices)
{
throw new Error(
"Unable to dispose local data: "
+ "some indices have not been uploaded."
);
}
_data = null;
_usage = StreamUsage.STATIC;
}
public function dispose() : void
{
_resource.dispose();
}
private static function checkReadUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.READ))
throw new Error(
'Unable to read from vertex stream: stream usage '
+ 'is not set to StreamUsage.READ.'
);
}
private static function checkWriteUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.WRITE))
throw new Error(
'Unable to write in vertex stream: stream usage '
+ 'is not set to StreamUsage.WRITE.'
);
}
public static function dummyData(size : uint, offset : uint = 0) : Vector.<uint>
{
var indices : Vector.<uint> = new Vector.<uint>(size);
for (var i : int = 0; i < size; ++i)
indices[i] = i + offset;
return indices;
}
public static function fromByteArray(usage : uint,
data : ByteArray,
numIndices : int) : IndexStream
{
var indices : Vector.<uint> = new Vector.<uint>(numIndices, true);
var stream : IndexStream = new IndexStream(usage);
for (var i : int = 0; i < numIndices; ++i)
indices[i] = data.readInt();
stream._data = indices;
stream.invalidate();
return stream;
}
}
}
|
package aerys.minko.render.geometry.stream
{
import aerys.minko.ns.minko_stream;
import aerys.minko.render.resource.IndexBuffer3DResource;
import aerys.minko.type.Signal;
import flash.utils.ByteArray;
public final class IndexStream
{
use namespace minko_stream;
minko_stream var _data : Vector.<uint> = null;
minko_stream var _localDispose : Boolean = false;
private var _usage : uint = 0;
private var _resource : IndexBuffer3DResource = null;
private var _length : uint = 0;
private var _changed : Signal = new Signal('IndexStream.changed');
public function get usage() : uint
{
return _usage;
}
public function get resource() : IndexBuffer3DResource
{
return _resource;
}
public function get length() : uint
{
return _length;
}
public function set length(value : uint) : void
{
_data.length = value;
invalidate();
}
public function get changed() : Signal
{
return _changed;
}
public function IndexStream(usage : uint,
data : Vector.<uint> = null,
length : uint = 0)
{
super();
initialize(data, length, usage);
}
minko_stream function invalidate() : void
{
_length = _data.length;
_changed.execute(this);
}
private function initialize(indices : Vector.<uint>,
length : uint,
usage : uint) : void
{
_usage = usage;
_resource = new IndexBuffer3DResource(this);
if (indices)
{
var numIndices : int = indices && length == 0
? indices.length
: Math.min(indices.length, length);
_data = new Vector.<uint>(numIndices);
for (var i : int = 0; i < numIndices; ++i)
_data[i] = indices[i];
}
else
{
_data = dummyData(length);
}
invalidate();
}
public function get(index : int) : uint
{
checkReadUsage(this);
return _data[index];
}
public function set(index : int, value : uint) : void
{
checkWriteUsage(this);
_data[index] = value;
}
public function deleteTriangleByIndex(index : int) : Vector.<uint>
{
checkWriteUsage(this);
var deletedIndices : Vector.<uint> = _data.splice(index, 3);
invalidate();
return deletedIndices;
}
public function getIndices(indices : Vector.<uint> = null) : Vector.<uint>
{
checkReadUsage(this);
var numIndices : int = length;
indices ||= new Vector.<uint>();
for (var i : int = 0; i < numIndices; ++i)
indices[i] = _data[i];
return indices;
}
public function setIndices(indices : Vector.<uint>) : void
{
checkWriteUsage(this);
var length : int = indices.length;
for (var i : int = 0; i < length; ++i)
_data[i] = indices[i];
_data.length = length;
invalidate();
}
public function clone(usage : uint = 0) : IndexStream
{
return new IndexStream(usage || _usage, _data, length);
}
public function toString() : String
{
return _data.toString();
}
public function concat(indexStream : IndexStream,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : IndexStream
{
checkReadUsage(indexStream);
checkWriteUsage(this);
var numIndices : int = _data.length;
var toConcat : Vector.<uint> = indexStream._data;
count ||= toConcat.length;
for (var i : int = 0; i < count; ++i, ++numIndices)
_data[numIndices] = toConcat[int(firstIndex + i)] + offset;
invalidate();
return this;
}
public function push(indices : Vector.<uint>,
firstIndex : uint = 0,
count : uint = 0,
offset : uint = 0) : void
{
checkWriteUsage(this);
var numIndices : int = _data.length;
count ||= indices.length;
for (var i : int = 0; i < count; ++i)
_data[int(numIndices++)] = indices[int(firstIndex + i)] + offset;
invalidate();
}
public function disposeLocalData(waitForUpload : Boolean = true) : void
{
if (waitForUpload && _length != resource.numIndices)
_localDispose = true;
else
{
_data = null;
_usage = StreamUsage.STATIC;
}
}
public function dispose() : void
{
_resource.dispose();
}
private static function checkReadUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.READ))
throw new Error(
'Unable to read from vertex stream: stream usage '
+ 'is not set to StreamUsage.READ.'
);
}
private static function checkWriteUsage(stream : IndexStream) : void
{
if (!(stream._usage & StreamUsage.WRITE))
throw new Error(
'Unable to write in vertex stream: stream usage '
+ 'is not set to StreamUsage.WRITE.'
);
}
public static function dummyData(size : uint, offset : uint = 0) : Vector.<uint>
{
var indices : Vector.<uint> = new Vector.<uint>(size);
for (var i : int = 0; i < size; ++i)
indices[i] = i + offset;
return indices;
}
public static function fromByteArray(usage : uint,
data : ByteArray,
numIndices : int) : IndexStream
{
var indices : Vector.<uint> = new Vector.<uint>(numIndices, true);
var stream : IndexStream = new IndexStream(usage);
for (var i : int = 0; i < numIndices; ++i)
indices[i] = data.readInt();
stream._data = indices;
stream.invalidate();
return stream;
}
}
}
|
add an optional StreamUsage argument to IndexStream.clone() and the possibility to "wait for upload" when calling IndexStream.disposeLocalData()
|
add an optional StreamUsage argument to IndexStream.clone() and the possibility to "wait for upload" when calling IndexStream.disposeLocalData()
|
ActionScript
|
mit
|
aerys/minko-as3
|
234c7c10873a8cfde274e26e2b760b61cc891e22
|
src/org/igniterealtime/xiff/si/FileTransferManager.as
|
src/org/igniterealtime/xiff/si/FileTransferManager.as
|
/*
* Copyright (C) 2003-2012 Igniterealtime Community Contributors
*
* Daniel Henninger
* Derrick Grigg <[email protected]>
* Juga Paazmaya <[email protected]>
* Nick Velloff <[email protected]>
* Sean Treadway <[email protected]>
* Sean Voisen <[email protected]>
* Mark Walters <[email protected]>
* Michael McCarthy <[email protected]>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.igniterealtime.xiff.si
{
import flash.events.EventDispatcher;
import org.igniterealtime.xiff.core.*;
import org.igniterealtime.xiff.data.forms.*;
import org.igniterealtime.xiff.data.si.*;
import org.igniterealtime.xiff.events.*;
/**
*
* @eventType org.igniterealtime.xiff.events.FileTransferEvent.TRANSFER_INIT
*/
[Event(name="transferInit", type="org.igniterealtime.xiff.events.FileTransferEvent")]
/**
* Manages Stream Initiation (XEP-0095) based File Transfer (XEP-0096)
*
* @see http://xmpp.org/extensions/xep-0095.html
* @see http://xmpp.org/extensions/xep-0096.html
*/
public class FileTransferManager extends EventDispatcher
{
private var _connection:IXMPPConnection;
/**
*
* @param aConnection A reference to an XMPPConnection class instance
*/
public function FileTransferManager( aConnection:IXMPPConnection = null )
{
if ( aConnection != null )
{
connection = aConnection;
}
}
/**
* The connection used for sending and receiving data.
*/
public function get connection():IXMPPConnection
{
return _connection;
}
public function set connection( value:IXMPPConnection ):void
{
if ( _connection != null )
{
}
_connection = value;
_connection.enableExtensions( FileTransferExtension, FormExtension, StreamInitiationExtension );
}
}
}
|
/*
* Copyright (C) 2003-2012 Igniterealtime Community Contributors
*
* Daniel Henninger
* Derrick Grigg <[email protected]>
* Juga Paazmaya <[email protected]>
* Nick Velloff <[email protected]>
* Sean Treadway <[email protected]>
* Sean Voisen <[email protected]>
* Mark Walters <[email protected]>
* Michael McCarthy <[email protected]>
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.igniterealtime.xiff.si
{
import flash.events.EventDispatcher;
import flash.utils.ByteArray;
import org.igniterealtime.xiff.core.*;
import org.igniterealtime.xiff.data.*;
import org.igniterealtime.xiff.data.feature.FeatureNegotiationExtension;
import org.igniterealtime.xiff.data.forms.*;
import org.igniterealtime.xiff.data.forms.enum.*;
import org.igniterealtime.xiff.data.si.*;
import org.igniterealtime.xiff.data.stream.*;
import org.igniterealtime.xiff.data.message.*;
import org.igniterealtime.xiff.events.*;
/**
*
* @eventType org.igniterealtime.xiff.events.FileTransferEvent.TRANSFER_INIT
*/
[Event(name="transferInit", type="org.igniterealtime.xiff.events.FileTransferEvent")]
/**
*
* @eventType org.igniterealtime.xiff.events.FileTransferEvent.FEATURE_NEGOTIATED
*/
[Event(name="featureNegotiated", type="org.igniterealtime.xiff.events.FileTransferEvent")]
/**
* INCOMPLETE
*
* Manages Stream Initiation (XEP-0095) based File Transfer (XEP-0096)
*
* @see http://xmpp.org/extensions/xep-0095.html
* @see http://xmpp.org/extensions/xep-0096.html
*/
public class FileTransferManager extends EventDispatcher
{
private var _connection:IXMPPConnection;
private var _outGoingData:ByteArray;
private var _sequence:uint = 0;
private var _chunkSize:uint = 4096;
/**
* Set the out going data first.
* Then beginNegotiation with all the relevant information
* Once FEATURE_NEGOTIATED occurs, call initiateSession.
*
* @param aConnection A reference to an XMPPConnection class instance
*/
public function FileTransferManager( aConnection:IXMPPConnection = null )
{
if ( aConnection != null )
{
connection = aConnection;
}
}
/**
* Negotiate a suitable transfer protocol.
* Feature negotiation is done with a FormExtension.
*
* <p>It can for example contain a list of possible stream methods.
* It seems that SOCKS5 Bytestreams (XEP-0065) will always be
* preferable, but it not implemented in XIFF.</p>
*
* @see http://xmpp.org/extensions/xep-0065.html
* @see http://xmpp.org/extensions/xep-0066.html
* @see http://xmpp.org/extensions/xep-0047.html
*/
public function beginNegotiation(to:EscapedJID, fileName:String, fileSize:uint, mimeType:String):void
{
/*
<iq type='set' id='offer1' to='[email protected]/resource'>
<si xmlns='http://jabber.org/protocol/si'
id='a0'
mime-type='text/plain'
profile='http://jabber.org/protocol/si/profile/file-transfer'>
<file xmlns='http://jabber.org/protocol/si/profile/file-transfer'
name='test.txt'
size='1022'/>
<feature xmlns='http://jabber.org/protocol/feature-neg'>
<x xmlns='jabber:x:data' type='form'>
<field var='stream-method' type='list-single'>
<option><value>http://jabber.org/protocol/bytestreams</value></option>
<option><value>http://jabber.org/protocol/ibb</value></option>
</field>
</x>
</feature>
</si>
</iq>
*/
var options:Array = [
{ label: "XEP-0066: Out of Band Data", value: OutOfBoundDataExtension.NS },
{ label: "XEP-0047: In-Band Bytestreams", value: IBBExtension.NS }
];
var field:FormField = new FormField(
FormFieldType.LIST_SINGLE,
"stream-method",
null,
options
);
var formExt:FormExtension = new FormExtension();
formExt.type = FormType.FORM;
formExt.fields = [field];
var featExt:FeatureNegotiationExtension = new FeatureNegotiationExtension();
featExt.addExtension(formExt);
var fileExt:FileTransferExtension = new FileTransferExtension();
fileExt.name = fileName;
fileExt.size = fileSize;
fileExt.addExtension(featExt);
var siExt:StreamInitiationExtension = new StreamInitiationExtension();
siExt.id = "letsdoit";
siExt.profile = FileTransferExtension.NS;
siExt.mimeType = mimeType;
siExt.addExtension(featExt);
var iq:IQ = new IQ(to, IQ.TYPE_SET, null, beginNegotiation_callback, beginNegotiation_errorCallback);
iq.addExtension(siExt);
_connection.send(iq);
}
/**
* Called once the IQ stanza with the proper id is coming back
*/
private function beginNegotiation_callback(iq:IQ):void
{
var event:FileTransferEvent = new FileTransferEvent(FileTransferEvent.FEATURE_NEGOTIATED);
dispatchEvent(event);
/*
<iq type='result' to='[email protected]/resource' id='offer1'>
<si xmlns='http://jabber.org/protocol/si'>
<feature xmlns='http://jabber.org/protocol/feature-neg'>
<x xmlns='jabber:x:data' type='submit'>
<field var='stream-method'>
<value>http://jabber.org/protocol/bytestreams</value>
</field>
</x>
</feature>
</si>
</iq>
*/
var siExt:StreamInitiationExtension = iq.getAllExtensionsByNS(StreamInitiationExtension.NS)[0] as StreamInitiationExtension;
var featExt:FeatureNegotiationExtension = siExt.getAllExtensionsByNS(FeatureNegotiationExtension.NS)[0] as FeatureNegotiationExtension;
var formExt:FormExtension = featExt.getAllExtensionsByNS(FormExtension.NS)[0] as FormExtension;
var field:FormField = formExt.getFormField("stream-method");
trace("beginNegotiation_callback. field.value: " + field.value);
}
private function beginNegotiation_errorCallback(iq:IQ):void
{
// fail....
}
/**
* Once the stream method has been negotiated, initiate the session.
*/
public function initiateSession(to:EscapedJID):void
{
/*
<iq from='[email protected]/orchard'
id='jn3h8g65'
to='[email protected]/balcony'
type='set'>
<open xmlns='http://jabber.org/protocol/ibb'
block-size='4096'
sid='i781hf64'
stanza='iq'/>
</iq>
*/
var openExt:IBBOpenExtension = new IBBOpenExtension();
openExt.sid = "letsdoit";
openExt.blockSize = _chunkSize;
var iq:IQ = new IQ(to, IQ.TYPE_SET, null, initiateSession_callback, initiateSession_errorCallback);
iq.addExtension(openExt);
_connection.send(iq);
}
/**
* Called once the IQ stanza with the proper id is coming back
*/
private function initiateSession_callback(iq:IQ):void
{
var event:FileTransferEvent = new FileTransferEvent(FileTransferEvent.TRANSFER_INIT);
dispatchEvent(event);
/*
<iq from='[email protected]/balcony'
id='jn3h8g65'
to='[email protected]/orchard'
type='result'/>
*/
sendChunk(iq.from);
}
private function initiateSession_errorCallback(iq:IQ):void
{
// fail....
}
private function sendChunk(to:EscapedJID):void
{
/*
<iq from='[email protected]/orchard'
id='kr91n475'
to='[email protected]/balcony'
type='set'>
<data xmlns='http://jabber.org/protocol/ibb' seq='0' sid='i781hf64'>
qANQR1DBwU4DX7jmYZnncmUQB/9KuKBddzQH+tZ1ZywKK0yHKnq57kWq+RFtQdCJ
WpdWpR0uQsuJe7+vh3NWn59/gTc5MDlX8dS9p0ovStmNcyLhxVgmqS8ZKhsblVeu
IpQ0JgavABqibJolc3BKrVtVV1igKiX/N7Pi8RtY1K18toaMDhdEfhBRzO/XB0+P
AQhYlRjNacGcslkhXqNjK5Va4tuOAPy2n1Q8UUrHbUd0g+xJ9Bm0G0LZXyvCWyKH
kuNEHFQiLuCY6Iv0myq6iX6tjuHehZlFSh80b5BVV9tNLwNR5Eqz1klxMhoghJOA
</data>
</iq>
*/
var iq:IQ = new IQ(to, IQ.TYPE_SET, null, sendChunk_callback, sendChunk_errorCallback);
var len:uint = Math.min(_outGoingData.bytesAvailable, _chunkSize);
if (len > 0)
{
var dataExt:IBBDataExtension = new IBBDataExtension();
dataExt.sid = "letsdoit";
dataExt.seq = _sequence;
dataExt.data = _outGoingData.readUTFBytes(len);
iq.addExtension(dataExt);
++_sequence;
}
else
{
iq.addExtension(new IBBCloseExtension());
}
_connection.send(iq);
}
private function sendChunk_callback(iq:IQ):void
{
if (_outGoingData.bytesAvailable > 0)
{
sendChunk(iq.from);
}
}
private function sendChunk_errorCallback(iq:IQ):void
{
// fail....
}
/**
* Base64 encoded data that is sent to the recipient.
*/
public function get outGoingData():ByteArray
{
return _outGoingData;
}
public function set outGoingData( value:ByteArray ):void
{
_outGoingData = value;
}
/**
* The connection used for sending and receiving data.
*/
public function get connection():IXMPPConnection
{
return _connection;
}
public function set connection( value:IXMPPConnection ):void
{
if ( _connection != null )
{
}
_connection = value;
_connection.enableExtensions( FileTransferExtension, FormExtension, StreamInitiationExtension );
}
}
}
|
Work in progress...
|
Work in progress...
git-svn-id: c197267f952b24206666de142881703007ca05d5@13250 b35dd754-fafc-0310-a699-88a17e54d16e
|
ActionScript
|
apache-2.0
|
nazoking/xiff
|
ded66ea34536a8819df2ff4f6e54a296322f15dc
|
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);
};
protected function _setupExternalGetters():void {
ExternalInterface.addCallback("getLevel", _getLevel);
ExternalInterface.addCallback("getLevels", _getLevels);
ExternalInterface.addCallback("getAutoLevel", _getAutoLevel);
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 _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("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 _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 && rect.width > 0) {
_stageVideo.viewPort = rect;
}
}
}
}
|
add robustness in _resize() related to https://github.com/bemtv/flashls/commit/4635e3b1a667d34923b6377037ac8a8d2a686dc5
|
add robustness in _resize()
related to https://github.com/bemtv/flashls/commit/4635e3b1a667d34923b6377037ac8a8d2a686dc5
|
ActionScript
|
mpl-2.0
|
vidible/vdb-flashls,JulianPena/flashls,ryanhefner/flashls,neilrackett/flashls,mangui/flashls,jlacivita/flashls,JulianPena/flashls,codex-corp/flashls,hola/flashls,loungelogic/flashls,NicolasSiver/flashls,clappr/flashls,viktorot/flashls,thdtjsdn/flashls,stevemayhew/flashls,jlacivita/flashls,Corey600/flashls,Peer5/flashls,clappr/flashls,ryanhefner/flashls,suuhas/flashls,suuhas/flashls,stevemayhew/flashls,tedconf/flashls,stevemayhew/flashls,aevange/flashls,Boxie5/flashls,Peer5/flashls,School-Improvement-Network/flashls,dighan/flashls,aevange/flashls,NicolasSiver/flashls,codex-corp/flashls,suuhas/flashls,suuhas/flashls,fixedmachine/flashls,viktorot/flashls,Corey600/flashls,tedconf/flashls,ryanhefner/flashls,viktorot/flashls,aevange/flashls,ryanhefner/flashls,vidible/vdb-flashls,neilrackett/flashls,fixedmachine/flashls,Peer5/flashls,Peer5/flashls,aevange/flashls,hola/flashls,loungelogic/flashls,stevemayhew/flashls,thdtjsdn/flashls,dighan/flashls,mangui/flashls,School-Improvement-Network/flashls,Boxie5/flashls,School-Improvement-Network/flashls
|
c14c5b91d468c462a2a33f38de44d3996ece2707
|
src/swf2png.as
|
src/swf2png.as
|
package
{
import com.adobe.images.PNGEncoder;
import flash.desktop.NativeApplication;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
import flash.utils.Timer;
public class swf2png extends Sprite
{
public var outputWidth:int;
public var outputHeight:int;
public var loadedSwf:MovieClip;
public var loader:Loader;
private var counter:int = 0;
private var timer:Timer;
private var totalFrames:int;
private var inputFileName:String;
private var inputFilePath:String;
private var prefix:String;
private var separator:String = "_";
private var outfield:TextField;
private var outputDirPath:String;
private var offsetMatrix:Matrix;
private var bBox:Rectangle;
public function swf2png() {
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
outfield = new TextField();
outfield.autoSize = TextFieldAutoSize.LEFT;
stage.addChild(outfield);
stage.frameRate = 12;
}
//Loads in file
private function loadSwf():void {
loader = new Loader();
log("Loading " + inputFilePath);
loader.load(new URLRequest("file://" + inputFilePath));
loader.contentLoaderInfo.addEventListener(Event.INIT, startLoop);
}
//Event handler called when the swf is loaded. Sets it up and starts the export loop
private function startLoop(ev:Event):void {
loadedSwf = MovieClip(ev.target.content);
outputWidth = Math.ceil(ev.target.width);
outputHeight = Math.ceil(ev.target.height);
log("Loaded!");
totalFrames = loadedSwf.totalFrames;
log("Frame count: " + totalFrames);
calculateBBox();
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
timer = new Timer(1);
timer.addEventListener(TimerEvent.TIMER, step);
timer.start();
}
private function calculateBBox():void {
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
var boundsArray:Object = {
"x" : new Array(),
"y" : new Array(),
"w" : new Array(),
"h" : new Array()
}
var r:Rectangle;
for(var currentFrame:int = 0; currentFrame < totalFrames; currentFrame++) {
goToFrame(loadedSwf, currentFrame);
r = loader.content.getRect(stage);
boundsArray.x.push(r.x);
boundsArray.y.push(r.y);
boundsArray.w.push(r.width);
boundsArray.h.push(r.height);
}
boundsArray.x.sort(Array.NUMERIC);
boundsArray.y.sort(Array.NUMERIC);
boundsArray.w.sort(Array.NUMERIC | Array.DESCENDING);
boundsArray.h.sort(Array.NUMERIC | Array.DESCENDING);
bBox = new Rectangle(
Math.floor(boundsArray.x[0]),
Math.floor(boundsArray.y[0]),
Math.ceil(boundsArray.w[0]),
Math.ceil(boundsArray.h[0])
);
log("Bounding box: " + bBox)
outputWidth = bBox.width;
outputHeight = bBox.height;
offsetMatrix = new Matrix();
offsetMatrix.translate(bBox.x * -1, bBox.y * -1);
return;
}
//Called for every frame
private function step(ev:TimerEvent):void {
counter++;
if(counter <= totalFrames) {
goToFrame(loadedSwf, counter);
saveFrame();
}
else {
timer.stop();
log("Done!");
exit(0);
return;
}
}
//Saves the current frame of the loader object to a png
private function saveFrame():void {
var bitmapData:BitmapData = new BitmapData(outputWidth, outputHeight, true, 0x0);
bitmapData.draw(loader.content, offsetMatrix);
var bytearr:ByteArray = PNGEncoder.encode(bitmapData);
var outfileName:String = outputDirPath + File.separator + prefix + separator + counter + ".png"
var file:File = new File(outfileName);
log("Writing: " + outfileName);
var stream:FileStream = new FileStream();
stream.open(file, "write");
stream.writeBytes(bytearr);
stream.close();
}
//Stops the movie clip and all its subclips.
private function stopClip(inMc:MovieClip):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.stop();
if(mc.numChildren > 0) {
stopClip(mc);
}
}
}
inMc.stop();
}
//Traverses the movie clip and sets the current frame for all subclips too, looping them where needed.
private function goToFrame(inMc:MovieClip, frameNo:int):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.gotoAndStop(frameNo % inMc.totalFrames);
if(mc.numChildren > 0) {
goToFrame(mc, frameNo);
}
}
}
inMc.gotoAndStop(frameNo % inMc.totalFrames);
}
//Finds and checks for existance of input file
private function getInputFile(ev:InvokeEvent):String {
if(ev.arguments && ev.arguments.length) {
inputFileName = ev.arguments[0];
var matches:Array = inputFileName.match(/([a-zA-Z0-9_\-\+\.]*?)\.swf$/);
if(!matches) {
// File inputFileName not valid
exit(2);
return "";
}
prefix = matches[1];
log("Prefix: " + prefix);
var f:File = new File(ev.currentDirectory.nativePath);
f = f.resolvePath(inputFileName);
if(!f.exists) {
log("Input file not found!");
//Input file not found
exit(3);
return "";
}
return f.nativePath;
}
else {
//App opened without input data
exit(1);
return "";
}
}
//Finds and checks for existance of output directory
private function getOutputDir(ev:InvokeEvent):String {
var d:File;
if(ev.arguments.length > 1) {
outputDirPath = ev.arguments[1];
d = new File(ev.currentDirectory.nativePath);
d = d.resolvePath(outputDirPath);
if(!d.isDirectory) {
//outdir not a directory
exit(4);
return "";
}
log("inpt: " + d.nativePath);
return d.nativePath;
}
else {
if(ev.currentDirectory.nativePath === '/') {
if(ev.arguments.length) {
d = new File(ev.arguments[0]);
d = d.resolvePath('..');
return d.nativePath;
}
else {
return File.desktopDirectory.nativePath;
}
}
else {
log("cwd: " + ev.currentDirectory.nativePath);
return ev.currentDirectory.nativePath;
}
return "";
}
}
private function log(message:String="", add_new_line:Boolean=true):void {
outfield.appendText((add_new_line ? "\n" : "") + message);
}
//Invoke handler called when started
private function onInvoke(ev:InvokeEvent):void {
inputFilePath = getInputFile(ev);
outputDirPath = getOutputDir(ev);
log("Input file: " + inputFilePath);
log("Output directory: " + outputDirPath);
loadSwf();
}
private function exit(code:int=0):void {
NativeApplication.nativeApplication.exit(code);
}
}
}
|
package
{
import com.adobe.images.PNGEncoder;
import flash.desktop.NativeApplication;
import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.filesystem.FileStream;
import flash.geom.Rectangle;
import flash.geom.Matrix;
import flash.net.URLRequest;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.utils.ByteArray;
import flash.utils.Timer;
public class swf2png extends Sprite
{
public var outputWidth:int;
public var outputHeight:int;
public var loadedSwf:MovieClip;
public var loader:Loader;
private var counter:int = 0;
private var timer:Timer;
private var totalFrames:int;
private var inputFileName:String;
private var inputFilePath:String;
private var prefix:String;
private var separator:String = "_";
private var outfield:TextField;
private var outputDirPath:String;
private var offsetMatrix:Matrix;
private var bBox:Rectangle;
public function swf2png() {
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke);
outfield = new TextField();
outfield.autoSize = TextFieldAutoSize.LEFT;
stage.addChild(outfield);
stage.frameRate = 12;
}
//Loads in file
private function loadSwf():void {
loader = new Loader();
log("Loading " + inputFilePath);
loader.load(new URLRequest("file://" + inputFilePath));
loader.contentLoaderInfo.addEventListener(Event.INIT, startLoop);
}
//Event handler called when the swf is loaded. Sets it up and starts the export loop
private function startLoop(ev:Event):void {
loadedSwf = MovieClip(ev.target.content);
outputWidth = Math.ceil(ev.target.width);
outputHeight = Math.ceil(ev.target.height);
log("Loaded!");
totalFrames = loadedSwf.totalFrames;
log("Frame count: " + totalFrames);
calculateBBox();
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
timer = new Timer(1);
timer.addEventListener(TimerEvent.TIMER, step);
timer.start();
}
private function calculateBBox():void {
stopClip(loadedSwf);
goToFrame(loadedSwf, 0);
var boundsArray:Object = {
"x" : new Array(),
"y" : new Array(),
"w" : new Array(),
"h" : new Array()
}
var r:Rectangle;
for(var currentFrame:int = 0; currentFrame < totalFrames; currentFrame++) {
goToFrame(loadedSwf, currentFrame);
r = loader.content.getRect(stage);
boundsArray.x.push(r.x);
boundsArray.y.push(r.y);
boundsArray.w.push(r.width);
boundsArray.h.push(r.height);
}
boundsArray.x.sort(Array.NUMERIC);
boundsArray.y.sort(Array.NUMERIC);
boundsArray.w.sort(Array.NUMERIC | Array.DESCENDING);
boundsArray.h.sort(Array.NUMERIC | Array.DESCENDING);
bBox = new Rectangle(
Math.floor(boundsArray.x[0]),
Math.floor(boundsArray.y[0]),
Math.ceil(boundsArray.w[0]),
Math.ceil(boundsArray.h[0])
);
log("Bounding box: " + bBox)
outputWidth = bBox.width;
outputHeight = bBox.height;
offsetMatrix = new Matrix();
offsetMatrix.translate(bBox.x * -1, bBox.y * -1);
return;
}
//Called for every frame
private function step(ev:TimerEvent):void {
counter++;
if(counter <= totalFrames) {
goToFrame(loadedSwf, counter);
saveFrame();
}
else {
timer.stop();
log("Done!");
exit(0);
return;
}
}
//Saves the current frame of the loader object to a png
private function saveFrame():void {
var bitmapData:BitmapData = new BitmapData(outputWidth, outputHeight, true, 0x0);
bitmapData.draw(loader.content, offsetMatrix);
var bytearr:ByteArray = PNGEncoder.encode(bitmapData);
var increment:String = '';
if(totalFrames > 1) {
increment = separator + counter;
}
var outfileName:String = outputDirPath + File.separator + prefix + increment + ".png"
var file:File = new File(outfileName);
log("Writing: " + outfileName);
var stream:FileStream = new FileStream();
stream.open(file, "write");
stream.writeBytes(bytearr);
stream.close();
}
//Stops the movie clip and all its subclips.
private function stopClip(inMc:MovieClip):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.stop();
if(mc.numChildren > 0) {
stopClip(mc);
}
}
}
inMc.stop();
}
//Traverses the movie clip and sets the current frame for all subclips too, looping them where needed.
private function goToFrame(inMc:MovieClip, frameNo:int):void {
var l:int = inMc.numChildren;
for (var i:int = 0; i < l; i++)
{
var mc:MovieClip = inMc.getChildAt(i) as MovieClip;
if(mc) {
mc.gotoAndStop(frameNo % inMc.totalFrames);
if(mc.numChildren > 0) {
goToFrame(mc, frameNo);
}
}
}
inMc.gotoAndStop(frameNo % inMc.totalFrames);
}
//Finds and checks for existance of input file
private function getInputFile(ev:InvokeEvent):String {
if(ev.arguments && ev.arguments.length) {
inputFileName = ev.arguments[0];
var matches:Array = inputFileName.match(/([a-zA-Z0-9_\-\+\.]*?)\.swf$/);
if(!matches) {
// File inputFileName not valid
exit(2);
return "";
}
prefix = matches[1];
log("Prefix: " + prefix);
var f:File = new File(ev.currentDirectory.nativePath);
f = f.resolvePath(inputFileName);
if(!f.exists) {
log("Input file not found!");
//Input file not found
exit(3);
return "";
}
return f.nativePath;
}
else {
//App opened without input data
exit(1);
return "";
}
}
//Finds and checks for existance of output directory
private function getOutputDir(ev:InvokeEvent):String {
var d:File;
if(ev.arguments.length > 1) {
outputDirPath = ev.arguments[1];
d = new File(ev.currentDirectory.nativePath);
d = d.resolvePath(outputDirPath);
if(!d.isDirectory) {
//outdir not a directory
exit(4);
return "";
}
log("inpt: " + d.nativePath);
return d.nativePath;
}
else {
if(ev.currentDirectory.nativePath === '/') {
if(ev.arguments.length) {
d = new File(ev.arguments[0]);
d = d.resolvePath('..');
return d.nativePath;
}
else {
return File.desktopDirectory.nativePath;
}
}
else {
log("cwd: " + ev.currentDirectory.nativePath);
return ev.currentDirectory.nativePath;
}
return "";
}
}
private function log(message:String="", add_new_line:Boolean=true):void {
outfield.appendText((add_new_line ? "\n" : "") + message);
}
//Invoke handler called when started
private function onInvoke(ev:InvokeEvent):void {
inputFilePath = getInputFile(ev);
outputDirPath = getOutputDir(ev);
log("Input file: " + inputFilePath);
log("Output directory: " + outputDirPath);
loadSwf();
}
private function exit(code:int=0):void {
NativeApplication.nativeApplication.exit(code);
}
}
}
|
Remove frame count when only one frame. Fixes #5.
|
Remove frame count when only one frame. Fixes #5.
The frame count suffix is only added when there's more than one frame in the swf.
|
ActionScript
|
mit
|
mdahlstrand/swf2png
|
efed4d21791f51bf181adc1553d4d93976475e64
|
flexEditor/src/org/arisgames/editor/components/ItemEditorMediaPickerView.as
|
flexEditor/src/org/arisgames/editor/components/ItemEditorMediaPickerView.as
|
package org.arisgames.editor.components
{
import com.ninem.controls.TreeBrowser;
import com.ninem.events.TreeBrowserEvent;
import flash.events.MouseEvent;
import mx.containers.Panel;
import mx.controls.Alert;
import mx.controls.Button;
import mx.controls.DataGrid;
import mx.core.ClassFactory;
import mx.events.DynamicEvent;
import mx.events.FlexEvent;
import mx.managers.PopUpManager;
import mx.rpc.Responder;
import org.arisgames.editor.data.arisserver.Media;
import org.arisgames.editor.data.businessobjects.ObjectPaletteItemBO;
import org.arisgames.editor.models.GameModel;
import org.arisgames.editor.services.AppServices;
import org.arisgames.editor.util.AppConstants;
import org.arisgames.editor.util.AppDynamicEventManager;
import org.arisgames.editor.util.AppUtils;
public class ItemEditorMediaPickerView extends Panel
{
// Data Object
public var delegate:Object;
private var objectPaletteItem:ObjectPaletteItemBO;
private var isIconPicker:Boolean = false;
private var isNPC:Boolean = false;
private var uploadFormVisable:Boolean = false;
// Media Data
[Bindable] public var xmlData:XML;
// GUI
[Bindable] public var treeBrowser:TreeBrowser;
[Bindable] public var closeButton:Button;
[Bindable] public var selectButton:Button;
// Tree Icons
[Bindable]
[Embed(source="assets/img/separator.png")]
public var separatorIcon:Class; //If these names are changed, make sure it is also changed in AppConstants (MEDIATREEICON_*)
[Bindable]
[Embed(source="assets/img/upload.png")]
public var uploadIcon:Class; //If these names are changed, make sure it is also changed in AppConstants (MEDIATREEICON_*)
private var mediaUploader:ItemEditorMediaPickerUploadFormMX;
/**
* Constructor
*/
public function ItemEditorMediaPickerView()
{
super();
this.addEventListener(FlexEvent.CREATION_COMPLETE, handleInit);
}
private function handleInit(event:FlexEvent):void
{
trace("in ItemEditorMediaPickerView's handleInit");
var cf:ClassFactory = new ClassFactory(ItemEditorMediaPickerCustomEditorMX);
cf.properties = {objectPaletteItem: this.objectPaletteItem};
treeBrowser.detailRenderer = cf;
treeBrowser.addEventListener(TreeBrowserEvent.NODE_SELECTED, onNodeSelected);
closeButton.addEventListener(MouseEvent.CLICK, handleCloseButton);
selectButton.addEventListener(MouseEvent.CLICK, handleSelectButton);
// Load Game's Media Into XML
AppServices.getInstance().getMediaForGame(GameModel.getInstance().game.gameId, new Responder(handleLoadingOfMediaIntoXML, handleFault));
}
private function printXMLData():void
{
trace("XML Data = '" + xmlData.toXMLString() + "'");
}
public function setObjectPaletteItem(opi:ObjectPaletteItemBO):void
{
trace("setting objectPaletteItem with name = '" + opi.name + "' in ItemEditorPlaqueView");
objectPaletteItem = opi;
}
public function isInIconPickerMode():Boolean
{
return isIconPicker;
}
public function setIsIconPicker(isIconPickerMode:Boolean):void
{
trace("setting isIconPicker mode to: " + isIconPickerMode);
this.isIconPicker = isIconPickerMode;
this.updateTitleBasedOnMode();
}
private function updateTitleBasedOnMode():void
{
if (isIconPicker)
{
title = "Icon Picker";
}
else
{
title = "Media Picker";
}
}
private function handleCloseButton(evt:MouseEvent):void
{
trace("ItemEditorMediaPickerView: handleCloseButton()");
PopUpManager.removePopUp(this);
}
private function handleSelectButton(evt:MouseEvent):void
{
trace("Select Button clicked...");
var m:Media = new Media();
m.mediaId = treeBrowser.selectedItem.@mediaId;
m.name = treeBrowser.selectedItem.@name;
m.type = treeBrowser.selectedItem.@type;
m.urlPath = treeBrowser.selectedItem.@urlPath;
m.fileName = treeBrowser.selectedItem.@fileName;
m.isDefault = treeBrowser.selectedItem.@isDefault;
if (delegate.hasOwnProperty("didSelectMediaItem")){
delegate.didSelectMediaItem(this, m);
}
PopUpManager.removePopUp(this);
}
private function handleLoadingOfMediaIntoXML(obj:Object):void
{
if(this.objectPaletteItem.objectType == AppConstants.CONTENTTYPE_CHARACTER_DATABASE){
this.isNPC = true;
trace("This is an NPC, so disallow Audio/Visual media");
}
trace("In handleLoadingOfMediaIntoXML() Result called with obj = " + obj + "; Result = " + obj.result);
if (obj.result.returnCode != 0)
{
trace("Bad loading of media attempt... let's see what happened. Error = '" + obj.result.returnCodeDescription + "'");
var msg:String = obj.result.returnCodeDescription;
Alert.show("Error Was: " + msg, "Error While Loading Media");
return;
}
//Init the XML Data
xmlData = new XML('<nodes label="' + AppConstants.MEDIATYPE + '"/>');
if (!this.isIconPicker && !this.isNPC) {
xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_IMAGE + '"/>');
xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_AUDIO + '"/>');
xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_VIDEO + '"/>');
}
this.printXMLData();
var media:Array = obj.result.data as Array;
trace("Number of Media Objects returned from server = '" + media.length + "'");
//Puts media items in xml readable format
var numImageDefaults:Number = 0;
var numAudioDefaults:Number = 0;
var numVideoDefaults:Number = 0;
var numIconDefaults:Number = 0;
for (var k:Number = 0; k <= 1; k++) //Iterates over list twice; once for uploaded items, again for default
{
for (var j:Number = 0; j < media.length; j++)
{
var o:Object = media[j];
if((k==0 && !o.is_default) || (k==1 && o.is_default)){
var m:Media = new Media();
m.mediaId = o.media_id;
m.name = o.name;
m.type = o.type;
m.urlPath = o.url_path;
m.fileName = o.file_name;
m.isDefault = o.is_default; //for both default files and uploaded files
var node:String = "<node label='" + AppUtils.filterStringToXMLEscapeCharacters(m.name) + "' mediaId='" + m.mediaId + "' type='" + m.type + "' urlPath='" + m.urlPath + "' fileName='" + m.fileName + "' isDefault='" + m.isDefault + "'/>";
switch (m.type)
{
case AppConstants.MEDIATYPE_IMAGE:
if(!this.isNPC){
if (!this.isIconPicker) {
//Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from
if(k > numImageDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>');
xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild(node);
numImageDefaults+=k;
}
}
else{
if (!this.isIconPicker) {
if(k > numIconDefaults) xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>');
xmlData.appendChild(node);
numIconDefaults+=k;
}
}
break;
case AppConstants.MEDIATYPE_AUDIO:
if (!this.isIconPicker && !this.isNPC) {
//Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from
if(k > numAudioDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>');
xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild(node);
numAudioDefaults+=k;
}
break;
case AppConstants.MEDIATYPE_VIDEO:
if (!this.isIconPicker && !this.isNPC) {
//Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from
if(k > numVideoDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>');
xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild(node);
numVideoDefaults+=k;
}
break;
case AppConstants.MEDIATYPE_ICON:
if (this.isIconPicker) {
trace("hello?:"+node);
if(k > numIconDefaults) xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>');
xmlData.appendChild(node);
numIconDefaults+=k;
}
break;
default:
trace("Default statement reached in load media. This SHOULD NOT HAPPEN. The offending mediaId = '" + m.mediaId + "' and type = '" + m.type + "'");
break;
}
}
}
//Add "Upload new" in between uploaded and default pictures
if(k==0 && (!this.isIconPicker && !this.isNPC)){
xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>');
xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>');
xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>');
}
else if(k == 0){
xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>');
}
}
trace("ItemEditorMediaPickerView: handleLoadingOfMediaIntoXML: Just finished loading Media Objects into XML. Here's what the new XML looks like:");
this.printXMLData();
trace("Finished with handleLoadingOfMediaIntoXML().");
}
public function handleFault(obj:Object):void
{
trace("Fault called: " + obj.message);
Alert.show("Error occurred: " + obj.message, "Problems Loading Media");
}
private function onNodeSelected(event:TreeBrowserEvent):void
{
if (!event.isBranch)
{
if (event.item.@label == AppConstants.MEDIATYPE_UPLOADNEW)
{
if (uploadFormVisable == false) {
trace("ItemEditorMediaPickerView: onNodeSelected label == MEDIATYPE_UPLOADNEW, display form");
selectButton.enabled = false;
uploadFormVisable = true;
this.displayMediaUploader();
PopUpManager.removePopUp(this);
}
else trace("ItemEditorMediaPickerView: ignored second TreeBrowserEvent == MEDIATYPE_UPLOADNEW");
}
else if(event.item.@label == AppConstants.MEDIATYPE_SEPARATOR){
//Do Nothing
trace("Separator Selected");
selectButton.enabled = false;
}
else
{
trace("ItemEditorMediaPickerView: onNodeSelected is a media item");
selectButton.enabled = true;
}
}
else {
selectButton.enabled = false;
}
}
private function displayMediaUploader():void
{
trace("itemEditorMediaPickerPickerView: displayMediaUploader");
mediaUploader = new ItemEditorMediaPickerUploadFormMX();
mediaUploader.isIconPicker = this.isIconPicker;
mediaUploader.delegate = this;
PopUpManager.addPopUp(mediaUploader, AppUtils.getInstance().getMainView(), true);
PopUpManager.centerPopUp(mediaUploader);
}
public function didUploadMedia(uploader:ItemEditorMediaPickerUploadFormMX, m:Media):void{
trace("ItemEditorMediaPicker: didUploadMedia");
uploadFormVisable = false;
if (delegate.hasOwnProperty("didSelectMediaItem")){
delegate.didSelectMediaItem(this, m);
}
PopUpManager.removePopUp(uploader);
}
}
}
|
package org.arisgames.editor.components
{
import com.ninem.controls.TreeBrowser;
import com.ninem.events.TreeBrowserEvent;
import flash.events.MouseEvent;
import mx.containers.Panel;
import mx.controls.Alert;
import mx.controls.Button;
import mx.controls.DataGrid;
import mx.core.ClassFactory;
import mx.events.DynamicEvent;
import mx.events.FlexEvent;
import mx.managers.PopUpManager;
import mx.rpc.Responder;
import org.arisgames.editor.data.arisserver.Media;
import org.arisgames.editor.data.businessobjects.ObjectPaletteItemBO;
import org.arisgames.editor.models.GameModel;
import org.arisgames.editor.services.AppServices;
import org.arisgames.editor.util.AppConstants;
import org.arisgames.editor.util.AppDynamicEventManager;
import org.arisgames.editor.util.AppUtils;
public class ItemEditorMediaPickerView extends Panel
{
// Data Object
public var delegate:Object;
private var objectPaletteItem:ObjectPaletteItemBO;
private var isIconPicker:Boolean = false;
private var isNPC:Boolean = false;
private var uploadFormVisable:Boolean = false;
// Media Data
[Bindable] public var xmlData:XML;
// GUI
[Bindable] public var treeBrowser:TreeBrowser;
[Bindable] public var closeButton:Button;
[Bindable] public var selectButton:Button;
// Tree Icons
[Bindable]
[Embed(source="assets/img/separator.png")]
public var separatorIcon:Class; //If these names are changed, make sure it is also changed in AppConstants (MEDIATREEICON_*)
[Bindable]
[Embed(source="assets/img/upload.png")]
public var uploadIcon:Class; //If these names are changed, make sure it is also changed in AppConstants (MEDIATREEICON_*)
private var mediaUploader:ItemEditorMediaPickerUploadFormMX;
/**
* Constructor
*/
public function ItemEditorMediaPickerView()
{
super();
this.addEventListener(FlexEvent.CREATION_COMPLETE, handleInit);
}
private function handleInit(event:FlexEvent):void
{
trace("in ItemEditorMediaPickerView's handleInit");
var cf:ClassFactory = new ClassFactory(ItemEditorMediaPickerCustomEditorMX);
cf.properties = {objectPaletteItem: this.objectPaletteItem};
treeBrowser.detailRenderer = cf;
treeBrowser.addEventListener(TreeBrowserEvent.NODE_SELECTED, onNodeSelected);
closeButton.addEventListener(MouseEvent.CLICK, handleCloseButton);
selectButton.addEventListener(MouseEvent.CLICK, handleSelectButton);
// Load Game's Media Into XML
AppServices.getInstance().getMediaForGame(GameModel.getInstance().game.gameId, new Responder(handleLoadingOfMediaIntoXML, handleFault));
}
private function printXMLData():void
{
trace("XML Data = '" + xmlData.toXMLString() + "'");
}
public function setObjectPaletteItem(opi:ObjectPaletteItemBO):void
{
trace("setting objectPaletteItem with name = '" + opi.name + "' in ItemEditorPlaqueView");
objectPaletteItem = opi;
}
public function isInIconPickerMode():Boolean
{
return isIconPicker;
}
public function setIsIconPicker(isIconPickerMode:Boolean):void
{
trace("setting isIconPicker mode to: " + isIconPickerMode);
this.isIconPicker = isIconPickerMode;
this.updateTitleBasedOnMode();
}
private function updateTitleBasedOnMode():void
{
if (isIconPicker)
{
title = "Icon Picker";
}
else
{
title = "Media Picker";
}
}
private function handleCloseButton(evt:MouseEvent):void
{
trace("ItemEditorMediaPickerView: handleCloseButton()");
PopUpManager.removePopUp(this);
}
private function handleSelectButton(evt:MouseEvent):void
{
trace("Select Button clicked...");
var m:Media = new Media();
m.mediaId = treeBrowser.selectedItem.@mediaId;
m.name = treeBrowser.selectedItem.@name;
m.type = treeBrowser.selectedItem.@type;
m.urlPath = treeBrowser.selectedItem.@urlPath;
m.fileName = treeBrowser.selectedItem.@fileName;
m.isDefault = treeBrowser.selectedItem.@isDefault;
if (delegate.hasOwnProperty("didSelectMediaItem")){
delegate.didSelectMediaItem(this, m);
}
PopUpManager.removePopUp(this);
}
private function handleLoadingOfMediaIntoXML(obj:Object):void
{
if(this.objectPaletteItem.objectType == AppConstants.CONTENTTYPE_CHARACTER_DATABASE){
this.isNPC = true;
trace("This is an NPC, so disallow Audio/Visual media");
}
trace("In handleLoadingOfMediaIntoXML() Result called with obj = " + obj + "; Result = " + obj.result);
if (obj.result.returnCode != 0)
{
trace("Bad loading of media attempt... let's see what happened. Error = '" + obj.result.returnCodeDescription + "'");
var msg:String = obj.result.returnCodeDescription;
Alert.show("Error Was: " + msg, "Error While Loading Media");
return;
}
//Init the XML Data
xmlData = new XML('<nodes label="' + AppConstants.MEDIATYPE + '"/>');
if (!this.isIconPicker && !this.isNPC) {
xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_IMAGE + '"/>');
xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_AUDIO + '"/>');
xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_VIDEO + '"/>');
}
this.printXMLData();
var media:Array = obj.result.data as Array;
trace("Number of Media Objects returned from server = '" + media.length + "'");
//Puts media items in xml readable format
var numImageDefaults:Number = 0;
var numAudioDefaults:Number = 0;
var numVideoDefaults:Number = 0;
var numIconDefaults:Number = 0;
for (var k:Number = 0; k <= 1; k++) //Iterates over list twice; once for uploaded items, again for default
{
//Add "Upload new" in between uploaded and default pictures
if(k==0 && (!this.isIconPicker && !this.isNPC)){
xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>');
xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>');
xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>');
}
else if(k == 0){
xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_UPLOADNEW + '" icon="'+ AppConstants.MEDIATREEICON_UPLOAD +'"/>');
}
for (var j:Number = 0; j < media.length; j++)
{
var o:Object = media[j];
if((k==0 && !o.is_default) || (k==1 && o.is_default)){
var m:Media = new Media();
m.mediaId = o.media_id;
m.name = o.name;
m.type = o.type;
m.urlPath = o.url_path;
m.fileName = o.file_name;
m.isDefault = o.is_default; //for both default files and uploaded files
var node:String = "<node label='" + AppUtils.filterStringToXMLEscapeCharacters(m.name) + "' mediaId='" + m.mediaId + "' type='" + m.type + "' urlPath='" + m.urlPath + "' fileName='" + m.fileName + "' isDefault='" + m.isDefault + "'/>";
switch (m.type)
{
case AppConstants.MEDIATYPE_IMAGE:
if(!this.isNPC){
if (!this.isIconPicker) {
//Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from
if(k > numImageDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>');
xmlData.node.(@label == AppConstants.MEDIATYPE_IMAGE).appendChild(node);
numImageDefaults+=k;
}
}
else{
if (!this.isIconPicker) {
if(k > numIconDefaults) xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>');
xmlData.appendChild(node);
numIconDefaults+=k;
}
}
break;
case AppConstants.MEDIATYPE_AUDIO:
if (!this.isIconPicker && !this.isNPC) {
//Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from
if(k > numAudioDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>');
xmlData.node.(@label == AppConstants.MEDIATYPE_AUDIO).appendChild(node);
numAudioDefaults+=k;
}
break;
case AppConstants.MEDIATYPE_VIDEO:
if (!this.isIconPicker && !this.isNPC) {
//Only add "-----------" (AppConstants.MEDIATYPE_SEPARATOR) if there are also defaults to choose from
if(k > numVideoDefaults) xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>');
xmlData.node.(@label == AppConstants.MEDIATYPE_VIDEO).appendChild(node);
numVideoDefaults+=k;
}
break;
case AppConstants.MEDIATYPE_ICON:
if (this.isIconPicker) {
trace("hello?:"+node);
if(k > numIconDefaults) xmlData.appendChild('<node label="' + AppConstants.MEDIATYPE_SEPARATOR + '" icon="'+ AppConstants.MEDIATREEICON_SEPARATOR +'"/>');
xmlData.appendChild(node);
numIconDefaults+=k;
}
break;
default:
trace("Default statement reached in load media. This SHOULD NOT HAPPEN. The offending mediaId = '" + m.mediaId + "' and type = '" + m.type + "'");
break;
}
}
}
}
trace("ItemEditorMediaPickerView: handleLoadingOfMediaIntoXML: Just finished loading Media Objects into XML. Here's what the new XML looks like:");
this.printXMLData();
trace("Finished with handleLoadingOfMediaIntoXML().");
}
public function handleFault(obj:Object):void
{
trace("Fault called: " + obj.message);
Alert.show("Error occurred: " + obj.message, "Problems Loading Media");
}
private function onNodeSelected(event:TreeBrowserEvent):void
{
if (!event.isBranch)
{
if (event.item.@label == AppConstants.MEDIATYPE_UPLOADNEW)
{
if (uploadFormVisable == false) {
trace("ItemEditorMediaPickerView: onNodeSelected label == MEDIATYPE_UPLOADNEW, display form");
selectButton.enabled = false;
uploadFormVisable = true;
this.displayMediaUploader();
PopUpManager.removePopUp(this);
}
else trace("ItemEditorMediaPickerView: ignored second TreeBrowserEvent == MEDIATYPE_UPLOADNEW");
}
else if(event.item.@label == AppConstants.MEDIATYPE_SEPARATOR){
//Do Nothing
trace("Separator Selected");
selectButton.enabled = false;
}
else
{
trace("ItemEditorMediaPickerView: onNodeSelected is a media item");
selectButton.enabled = true;
}
}
else {
selectButton.enabled = false;
}
}
private function displayMediaUploader():void
{
trace("itemEditorMediaPickerPickerView: displayMediaUploader");
mediaUploader = new ItemEditorMediaPickerUploadFormMX();
mediaUploader.isIconPicker = this.isIconPicker;
mediaUploader.delegate = this;
PopUpManager.addPopUp(mediaUploader, AppUtils.getInstance().getMainView(), true);
PopUpManager.centerPopUp(mediaUploader);
}
public function didUploadMedia(uploader:ItemEditorMediaPickerUploadFormMX, m:Media):void{
trace("ItemEditorMediaPicker: didUploadMedia");
uploadFormVisable = false;
if (delegate.hasOwnProperty("didSelectMediaItem")){
delegate.didSelectMediaItem(this, m);
}
PopUpManager.removePopUp(uploader);
}
}
}
|
Put Upload New button at top of media picker list
|
Put Upload New button at top of media picker list
|
ActionScript
|
mit
|
ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames
|
373eede6342f363cc6ccc0173ffb3bc95ba8e7c5
|
src/aerys/minko/type/Signal.as
|
src/aerys/minko/type/Signal.as
|
package aerys.minko.type
{
public final class Signal
{
private var _name : String = null;
private var _callbacks : Array = [];
private var _numCallbacks : uint = 0;
private var _executed : Boolean = false;
private var _numAdded : uint = 0;
private var _toAdd : Array = null;
private var _numRemoved : uint = 0;
private var _toRemove : Array = null;
public function get numCallbacks() : uint
{
return _numCallbacks;
}
public function Signal(name : String)
{
_name = name;
}
public function add(callback : Function) : void
{
if (_callbacks.indexOf(callback) >= 0)
throw new Error('The same callback cannot be added twice.');
if (_executed)
{
if (_toAdd)
_toAdd.push(callback);
else
_toAdd = [callback];
++_numAdded;
return ;
}
_callbacks[_numCallbacks] = callback;
++_numCallbacks;
}
public function remove(callback : Function) : void
{
var index : int = _callbacks.indexOf(callback);
if (index < 0)
throw new Error('This callback does not exist.');
if (_executed)
{
if (_toRemove)
_toRemove.push(callback);
else
_toRemove = [callback];
++_numRemoved;
return ;
}
--_numCallbacks;
_callbacks[index] = _callbacks[_numCallbacks];
_callbacks.length = _numCallbacks;
}
public function hasCallback(callback : Function) : Boolean
{
return _callbacks.indexOf(callback) >= 0;
}
public function execute(...params) : void
{
if (_numCallbacks)
{
_executed = true;
for (var i : uint = 0; i < _numCallbacks; ++i)
(_callbacks[i] as Function).apply(null, params);
_executed = false;
for (i = 0; i < _numAdded; ++i)
add(_toAdd[i]);
_numAdded = 0;
_toAdd = null;
for (i = 0; i < _numRemoved; ++i)
remove(_toRemove[i]);
_numRemoved = 0;
_toRemove = null;
}
}
}
}
|
package aerys.minko.type
{
public final class Signal
{
private var _name : String;
private var _callbacks : Vector.<Function>;
private var _numCallbacks : uint;
private var _executed : Boolean;
private var _numAdded : uint;
private var _toAdd : Vector.<Function>;
private var _numRemoved : uint;
private var _toRemove : Vector.<Function>;
public function get numCallbacks() : uint
{
return _numCallbacks;
}
public function Signal(name : String)
{
_name = name;
_callbacks = new <Function>[];
}
public function add(callback : Function) : void
{
if (_callbacks.indexOf(callback) >= 0)
throw new Error('The same callback cannot be added twice.');
if (_executed)
{
if (_toAdd)
_toAdd.push(callback);
else
_toAdd = new <Function>[callback];
++_numAdded;
return ;
}
_callbacks[_numCallbacks] = callback;
++_numCallbacks;
}
public function remove(callback : Function) : void
{
var index : int = _callbacks.indexOf(callback);
if (index < 0)
throw new Error('This callback does not exist.');
if (_executed)
{
if (_toRemove)
_toRemove.push(callback);
else
_toRemove = new <Function>[callback];
++_numRemoved;
return ;
}
--_numCallbacks;
_callbacks[index] = _callbacks[_numCallbacks];
_callbacks.length = _numCallbacks;
}
public function hasCallback(callback : Function) : Boolean
{
return _callbacks.indexOf(callback) >= 0;
}
public function execute(...params) : void
{
if (_numCallbacks)
{
_executed = true;
for (var i : uint = 0; i < _numCallbacks; ++i)
_callbacks[i].apply(null, params);
_executed = false;
for (i = 0; i < _numAdded; ++i)
add(_toAdd[i]);
_numAdded = 0;
_toAdd = null;
for (i = 0; i < _numRemoved; ++i)
remove(_toRemove[i]);
_numRemoved = 0;
_toRemove = null;
}
}
}
}
|
use Vector.<Function> instead of Array in Signal to get a ~10% performance boost
|
use Vector.<Function> instead of Array in Signal to get a ~10% performance boost
|
ActionScript
|
mit
|
aerys/minko-as3
|
aac09e75258c7a4aae8a3c3d763bc7085606d2a3
|
frameworks/projects/Core/as/src/org/apache/flex/core/Application.as
|
frameworks/projects/Core/as/src/org/apache/flex/core/Application.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.system.ApplicationDomain;
import flash.utils.getQualifiedClassName;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.events.MouseEvent;
import org.apache.flex.events.utils.MouseEventConverter;
import org.apache.flex.utils.MXMLDataInterpreter;
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched at startup. Attributes and sub-instances of
* the MXML document have been created and assigned.
* The component lifecycle is different
* than the Flex SDK. There is no creationComplete event.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="initialize", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="viewChanged", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="applicationComplete", type="org.apache.flex.events.Event")]
/**
* The Application class is the main class and entry point for a FlexJS
* application. This Application class is different than the
* Flex SDK's mx:Application or spark:Application in that it does not contain
* user interface elements. Those UI elements go in the views. This
* Application class expects there to be a main model, a controller, and
* an initial view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class Application extends Sprite implements IStrand, IFlexInfo, IParent, IEventDispatcher
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Application()
{
super();
if (stage)
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
// should be opt-in
//stage.quality = StageQuality.HIGH_16X16_LINEAR;
}
loaderInfo.addEventListener(flash.events.Event.INIT, initHandler);
}
/**
* The document property is used to provide
* a property lookup context for non-display objects.
* For Application, it points to itself.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var document:Object = this;
private function initHandler(event:flash.events.Event):void
{
if (model is IBead) addBead(model as IBead);
if (controller is IBead) addBead(controller as IBead);
MouseEventConverter.setupAllConverters(stage);
for each (var bead:IBead in beads)
addBead(bead);
dispatchEvent(new org.apache.flex.events.Event("beadsAdded"));
MXMLDataInterpreter.generateMXMLInstances(this, null, MXMLDescriptor);
dispatchEvent(new org.apache.flex.events.Event("initialize"));
if (initialView)
{
initialView.applicationModel = model;
if (isNaN(initialView.explicitWidth))
initialView.setWidth(stage.stageWidth);
if (isNaN(initialView.explicitHeight))
initialView.setHeight(stage.stageHeight);
this.addElement(initialView);
var bgColor:Object = ValuesManager.valuesImpl.getValue(this, "background-color");
if (bgColor != null)
{
var backgroundColor:uint = ValuesManager.valuesImpl.convertColor(bgColor);
graphics.beginFill(backgroundColor);
graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
graphics.endFill();
}
dispatchEvent(new org.apache.flex.events.Event("viewChanged"));
}
dispatchEvent(new org.apache.flex.events.Event("applicationComplete"));
}
/**
* The org.apache.flex.core.IValuesImpl that will
* determine the default values and other values
* for the application. The most common choice
* is org.apache.flex.core.SimpleCSSValuesImpl.
*
* @see org.apache.flex.core.SimpleCSSValuesImpl
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set valuesImpl(value:IValuesImpl):void
{
ValuesManager.valuesImpl = value;
ValuesManager.valuesImpl.init(this);
}
/**
* The initial view.
*
* @see org.apache.flex.core.ViewBase
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var initialView:ViewBase;
/**
* The data model (for the initial view).
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var model:Object;
/**
* The controller. The controller typically watches
* the UI for events and updates the model accordingly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var controller:Object;
/**
* An array of data that describes the MXML attributes
* and tags in an MXML document. This data is usually
* decoded by an MXMLDataInterpreter
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get MXMLDescriptor():Array
{
return null;
}
/**
* An method called by the compiler's generated
* code to kick off the setting of MXML attribute
* values and instantiation of child tags.
*
* The call has to be made in the generated code
* in order to ensure that the constructors have
* completed first.
*
* @param data The encoded data representing the
* MXML attributes.
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateMXMLAttributes(data:Array):void
{
MXMLDataInterpreter.generateMXMLProperties(this, data);
}
/**
* The array property that is used to add additional
* beads to an MXML tag. From ActionScript, just
* call addBead directly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var beads:Array;
private var _beads:Vector.<IBead>;
/**
* @copy org.apache.flex.core.IStrand#addBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
bead.strand = this;
}
/**
* @copy org.apache.flex.core.IStrand#getBeadByType()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
/**
* @copy org.apache.flex.core.IStrand#removeBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeBead(value:IBead):IBead
{
var n:int = _beads.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = _beads[i];
if (bead == value)
{
_beads.splice(i, 1);
return bead;
}
}
return null;
}
private var _info:Object;
/**
* An Object containing information generated
* by the compiler that is useful at startup time.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function info():Object
{
if (!_info)
{
var mainClassName:String = getQualifiedClassName(this);
var initClassName:String = "_" + mainClassName + "_FlexInit";
var c:Class = ApplicationDomain.currentDomain.getDefinition(initClassName) as Class;
_info = c.info();
}
return _info;
}
/**
* @copy org.apache.flex.core.IParent#addElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElement(c:Object, dispatchEvent:Boolean = true):void
{
if (c is IUIBase)
{
addChild(IUIBase(c).element as DisplayObject);
IUIBase(c).addedToParent();
}
else
addChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#addElementAt()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElementAt(c:Object, index:int, dispatchEvent:Boolean = true):void
{
if (c is IUIBase)
{
addChildAt(IUIBase(c).element as DisplayObject, index);
IUIBase(c).addedToParent();
}
else
addChildAt(c as DisplayObject, index);
}
/**
* @copy org.apache.flex.core.IParent#getElementAt()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getElementAt(index:int):Object
{
return getChildAt(index);
}
/**
* @copy org.apache.flex.core.IParent#getElementIndex()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getElementIndex(c:Object):int
{
if (c is IUIBase)
return getChildIndex(IUIBase(c).element as DisplayObject);
return getChildIndex(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#removeElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeElement(c:Object, dispatchEvent:Boolean = true):void
{
if (c is IUIBase)
{
removeChild(IUIBase(c).element as DisplayObject);
}
else
removeChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#numElements
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get numElements():int
{
return numChildren;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.MouseEvent;
import flash.system.ApplicationDomain;
import flash.utils.getQualifiedClassName;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
import org.apache.flex.events.MouseEvent;
import org.apache.flex.events.utils.MouseEventConverter;
import org.apache.flex.utils.MXMLDataInterpreter;
//--------------------------------------
// Events
//--------------------------------------
/**
* Dispatched at startup. Attributes and sub-instances of
* the MXML document have been created and assigned.
* The component lifecycle is different
* than the Flex SDK. There is no creationComplete event.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="initialize", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="viewChanged", type="org.apache.flex.events.Event")]
/**
* Dispatched at startup after the initial view has been
* put on the display list.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="applicationComplete", type="org.apache.flex.events.Event")]
/**
* The Application class is the main class and entry point for a FlexJS
* application. This Application class is different than the
* Flex SDK's mx:Application or spark:Application in that it does not contain
* user interface elements. Those UI elements go in the views. This
* Application class expects there to be a main model, a controller, and
* an initial view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class Application extends Sprite implements IStrand, IFlexInfo, IParent, IEventDispatcher
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function Application()
{
super();
if (stage)
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
// should be opt-in
//stage.quality = StageQuality.HIGH_16X16_LINEAR;
}
loaderInfo.addEventListener(flash.events.Event.INIT, initHandler);
}
/**
* The document property is used to provide
* a property lookup context for non-display objects.
* For Application, it points to itself.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var document:Object = this;
private function initHandler(event:flash.events.Event):void
{
if (model is IBead) addBead(model as IBead);
if (controller is IBead) addBead(controller as IBead);
MouseEventConverter.setupAllConverters(stage);
for each (var bead:IBead in beads)
addBead(bead);
dispatchEvent(new org.apache.flex.events.Event("beadsAdded"));
MXMLDataInterpreter.generateMXMLInstances(this, null, MXMLDescriptor);
dispatchEvent(new org.apache.flex.events.Event("initialize"));
if (initialView)
{
initialView.applicationModel = model;
if (isNaN(initialView.explicitWidth))
initialView.width = stage.stageWidth;
if (isNaN(initialView.explicitHeight))
initialView.height = stage.stageHeight;
this.addElement(initialView);
var bgColor:Object = ValuesManager.valuesImpl.getValue(this, "background-color");
if (bgColor != null)
{
var backgroundColor:uint = ValuesManager.valuesImpl.convertColor(bgColor);
graphics.beginFill(backgroundColor);
graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
graphics.endFill();
}
dispatchEvent(new org.apache.flex.events.Event("viewChanged"));
}
dispatchEvent(new org.apache.flex.events.Event("applicationComplete"));
}
/**
* The org.apache.flex.core.IValuesImpl that will
* determine the default values and other values
* for the application. The most common choice
* is org.apache.flex.core.SimpleCSSValuesImpl.
*
* @see org.apache.flex.core.SimpleCSSValuesImpl
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set valuesImpl(value:IValuesImpl):void
{
ValuesManager.valuesImpl = value;
ValuesManager.valuesImpl.init(this);
}
/**
* The initial view.
*
* @see org.apache.flex.core.ViewBase
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var initialView:ViewBase;
/**
* The data model (for the initial view).
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var model:Object;
/**
* The controller. The controller typically watches
* the UI for events and updates the model accordingly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var controller:Object;
/**
* An array of data that describes the MXML attributes
* and tags in an MXML document. This data is usually
* decoded by an MXMLDataInterpreter
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get MXMLDescriptor():Array
{
return null;
}
/**
* An method called by the compiler's generated
* code to kick off the setting of MXML attribute
* values and instantiation of child tags.
*
* The call has to be made in the generated code
* in order to ensure that the constructors have
* completed first.
*
* @param data The encoded data representing the
* MXML attributes.
*
* @see org.apache.flex.utils.MXMLDataInterpreter
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateMXMLAttributes(data:Array):void
{
MXMLDataInterpreter.generateMXMLProperties(this, data);
}
/**
* The array property that is used to add additional
* beads to an MXML tag. From ActionScript, just
* call addBead directly.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var beads:Array;
private var _beads:Vector.<IBead>;
/**
* @copy org.apache.flex.core.IStrand#addBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addBead(bead:IBead):void
{
if (!_beads)
_beads = new Vector.<IBead>;
_beads.push(bead);
bead.strand = this;
}
/**
* @copy org.apache.flex.core.IStrand#getBeadByType()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getBeadByType(classOrInterface:Class):IBead
{
for each (var bead:IBead in _beads)
{
if (bead is classOrInterface)
return bead;
}
return null;
}
/**
* @copy org.apache.flex.core.IStrand#removeBead()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeBead(value:IBead):IBead
{
var n:int = _beads.length;
for (var i:int = 0; i < n; i++)
{
var bead:IBead = _beads[i];
if (bead == value)
{
_beads.splice(i, 1);
return bead;
}
}
return null;
}
private var _info:Object;
/**
* An Object containing information generated
* by the compiler that is useful at startup time.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function info():Object
{
if (!_info)
{
var mainClassName:String = getQualifiedClassName(this);
var initClassName:String = "_" + mainClassName + "_FlexInit";
var c:Class = ApplicationDomain.currentDomain.getDefinition(initClassName) as Class;
_info = c.info();
}
return _info;
}
/**
* @copy org.apache.flex.core.IParent#addElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElement(c:Object, dispatchEvent:Boolean = true):void
{
if (c is IUIBase)
{
addChild(IUIBase(c).element as DisplayObject);
IUIBase(c).addedToParent();
}
else
addChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#addElementAt()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function addElementAt(c:Object, index:int, dispatchEvent:Boolean = true):void
{
if (c is IUIBase)
{
addChildAt(IUIBase(c).element as DisplayObject, index);
IUIBase(c).addedToParent();
}
else
addChildAt(c as DisplayObject, index);
}
/**
* @copy org.apache.flex.core.IParent#getElementAt()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getElementAt(index:int):Object
{
return getChildAt(index);
}
/**
* @copy org.apache.flex.core.IParent#getElementIndex()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function getElementIndex(c:Object):int
{
if (c is IUIBase)
return getChildIndex(IUIBase(c).element as DisplayObject);
return getChildIndex(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#removeElement()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function removeElement(c:Object, dispatchEvent:Boolean = true):void
{
if (c is IUIBase)
{
removeChild(IUIBase(c).element as DisplayObject);
}
else
removeChild(c as DisplayObject);
}
/**
* @copy org.apache.flex.core.IParent#numElements
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get numElements():int
{
return numChildren;
}
}
}
|
set explicitWidth/Height so that initial view doesn't think it is sized to content
|
set explicitWidth/Height so that initial view doesn't think it is sized to content
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
cd75303755eef77444628c2c19fd1698d3c5c53c
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/ContainerBase.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/core/ContainerBase.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 mx.states.State;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.ValueChangeEvent;
import org.apache.flex.utils.MXMLDataInterpreter;
/**
* Indicates that the state change has completed. All properties
* that need to change have been changed, and all transitinos
* that need to run have completed. However, any deferred work
* may not be completed, and the screen may not be updated until
* code stops executing.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="stateChangeComplete", type="org.apache.flex.events.Event")]
[DefaultProperty("mxmlContent")]
/**
* The ContainerBase class is the base class for most containers
* in FlexJS. It is usable as the root tag of MXML
* documents and UI controls and containers are added to it.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ContainerBase extends UIBase
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ContainerBase()
{
super();
}
/**
* A ContainerBase doesn't create its children until it is added to
* a parent.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function addedToParent():void
{
// each MXML file can also have styles in fx:Style block
ValuesManager.valuesImpl.init(this);
MXMLDataInterpreter.generateMXMLProperties(this, mxmlProperties);
super.addedToParent();
MXMLDataInterpreter.generateMXMLInstances(this, this, MXMLDescriptor);
dispatchEvent(new Event("initComplete"))
dispatchEvent(new Event("childrenAdded"));
}
/**
* @copy org.apache.flex.core.Application#MXMLDescriptor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get MXMLDescriptor():Array
{
return null;
}
private var mxmlProperties:Array ;
/**
* @copy org.apache.flex.core.Application#generateMXMLAttributes()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateMXMLAttributes(data:Array):void
{
mxmlProperties = data;
}
/**
* @copy org.apache.flex.core.ItemRendererClassFactory#mxmlContent
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var mxmlContent:Array;
private var _states:Array;
/**
* The array of view states. These should
* be instances of mx.states.State.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get states():Array
{
return _states;
}
/**
* @private
*/
public function set states(value:Array):void
{
_states = value;
_currentState = _states[0].name;
try{
if (getBeadByType(IStatesImpl) == null)
addBead(new (ValuesManager.valuesImpl.getValue(this, "iStatesImpl")) as IBead);
}
//TODO: Need to handle this case more gracefully
catch(e:Error)
{
trace(e.message);
}
}
/**
* <code>true</code> if the array of states
* contains a state with this name.
*
* @param state The state namem.
* @return True if state in state array
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function hasState(state:String):Boolean
{
for each (var s:State in _states)
{
if (s.name == state)
return true;
}
return false;
}
private var _currentState:String;
/**
* The name of the current state.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get currentState():String
{
return _currentState;
}
/**
* @private
*/
public function set currentState(value:String):void
{
var event:ValueChangeEvent = new ValueChangeEvent("currentStateChanged", false, false, _currentState, value)
_currentState = value;
dispatchEvent(event);
}
private var _transitions:Array;
/**
* The array of transitions.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get transitions():Array
{
return _transitions;
}
/**
* @private
*/
public function set transitions(value:Array):void
{
_transitions = value;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.core
{
import mx.states.State;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.ValueChangeEvent;
import org.apache.flex.utils.MXMLDataInterpreter;
/**
* Indicates that the state change has completed. All properties
* that need to change have been changed, and all transitinos
* that need to run have completed. However, any deferred work
* may not be completed, and the screen may not be updated until
* code stops executing.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="stateChangeComplete", type="org.apache.flex.events.Event")]
/**
* Indicates that the initialization of the container is complete.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="initComplete", type="org.apache.flex.events.Event")]
/**
* Indicates that the children of the container is have been added.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
[Event(name="childrenAdded", type="org.apache.flex.events.Event")]
[DefaultProperty("mxmlContent")]
/**
* The ContainerBase class is the base class for most containers
* in FlexJS. It is usable as the root tag of MXML
* documents and UI controls and containers are added to it.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class ContainerBase extends UIBase
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function ContainerBase()
{
super();
}
/**
* A ContainerBase doesn't create its children until it is added to
* a parent.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
override public function addedToParent():void
{
// each MXML file can also have styles in fx:Style block
ValuesManager.valuesImpl.init(this);
MXMLDataInterpreter.generateMXMLProperties(this, mxmlProperties);
super.addedToParent();
MXMLDataInterpreter.generateMXMLInstances(this, this, MXMLDescriptor);
dispatchEvent(new Event("initComplete"))
dispatchEvent(new Event("childrenAdded"));
}
/**
* @copy org.apache.flex.core.Application#MXMLDescriptor
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get MXMLDescriptor():Array
{
return null;
}
private var mxmlProperties:Array ;
/**
* @copy org.apache.flex.core.Application#generateMXMLAttributes()
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function generateMXMLAttributes(data:Array):void
{
mxmlProperties = data;
}
/**
* @copy org.apache.flex.core.ItemRendererClassFactory#mxmlContent
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var mxmlContent:Array;
private var _states:Array;
/**
* The array of view states. These should
* be instances of mx.states.State.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get states():Array
{
return _states;
}
/**
* @private
*/
public function set states(value:Array):void
{
_states = value;
_currentState = _states[0].name;
try{
if (getBeadByType(IStatesImpl) == null)
addBead(new (ValuesManager.valuesImpl.getValue(this, "iStatesImpl")) as IBead);
}
//TODO: Need to handle this case more gracefully
catch(e:Error)
{
trace(e.message);
}
}
/**
* <code>true</code> if the array of states
* contains a state with this name.
*
* @param state The state namem.
* @return True if state in state array
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function hasState(state:String):Boolean
{
for each (var s:State in _states)
{
if (s.name == state)
return true;
}
return false;
}
private var _currentState:String;
/**
* The name of the current state.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get currentState():String
{
return _currentState;
}
/**
* @private
*/
public function set currentState(value:String):void
{
var event:ValueChangeEvent = new ValueChangeEvent("currentStateChanged", false, false, _currentState, value)
_currentState = value;
dispatchEvent(event);
}
private var _transitions:Array;
/**
* The array of transitions.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get transitions():Array
{
return _transitions;
}
/**
* @private
*/
public function set transitions(value:Array):void
{
_transitions = value;
}
}
}
|
add container events
|
add container events
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
75065a1c8617f661434f0b989b1e7af93abd763c
|
src/aerys/minko/render/material/basic/BasicMaterial.as
|
src/aerys/minko/render/material/basic/BasicMaterial.as
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.Material;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.binding.IDataProvider;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
public class BasicMaterial extends Material
{
public static const DEFAULT_NAME : String = 'BasicMaterial';
public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader();
public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER);
public function get diffuseMapFormat() : uint
{
return getProperty(BasicProperties.DIFFUSE_MAP_FORMAT);
}
public function set diffuseMapFormat(value : uint) : void
{
setProperty(BasicProperties.DIFFUSE_MAP_FORMAT, value);
}
public function get blending() : uint
{
return getProperty(BasicProperties.BLENDING);
}
public function set blending(value : uint) : void
{
setProperty(BasicProperties.BLENDING, value);
}
public function get triangleCulling() : uint
{
return getProperty(BasicProperties.TRIANGLE_CULLING);
}
public function set triangleCulling(value : uint) : void
{
setProperty(BasicProperties.TRIANGLE_CULLING, value);
}
public function get diffuseColor() : Object
{
return getProperty(BasicProperties.DIFFUSE_COLOR);
}
public function set diffuseColor(value : Object) : void
{
setProperty(BasicProperties.DIFFUSE_COLOR, value);
}
public function get diffuseMap() : TextureResource
{
return getProperty(BasicProperties.DIFFUSE_MAP);
}
public function set diffuseMap(value : TextureResource) : void
{
setProperty(BasicProperties.DIFFUSE_MAP, value);
}
public function get alphaMap() : TextureResource
{
return getProperty(BasicProperties.ALPHA_MAP) as TextureResource;
}
public function set alphaMap(value : TextureResource) : void
{
setProperty(BasicProperties.ALPHA_MAP, value);
}
public function get alphaThreshold() : Number
{
return getProperty(BasicProperties.ALPHA_THRESHOLD);
}
public function set alphaThreshold(value : Number) : void
{
setProperty(BasicProperties.ALPHA_THRESHOLD, value);
}
public function get depthTest() : uint
{
return getProperty(BasicProperties.DEPTH_TEST);
}
public function set depthTest(value : uint) : void
{
setProperty(BasicProperties.DEPTH_TEST, value);
}
public function get depthWriteEnabled() : Boolean
{
return getProperty(BasicProperties.DEPTH_WRITE_ENABLED);
}
public function set depthWriteEnabled(value : Boolean) : void
{
setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value);
}
public function get stencilTriangleFace() : uint
{
return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE);
}
public function set stencilTriangleFace(value : uint) : void
{
setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value);
}
public function get stencilCompareMode() : uint
{
return getProperty(BasicProperties.STENCIL_COMPARE_MODE);
}
public function set stencilCompareMode(value : uint) : void
{
setProperty(BasicProperties.STENCIL_COMPARE_MODE, value);
}
public function get stencilActionBothPass() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS);
}
public function set stencilActionBothPass(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value);
}
public function get stencilActionDepthFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL);
}
public function set stencilActionDepthFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value);
}
public function get stencilActionDepthPassStencilFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL);
}
public function set stencilActionDepthPassStencilFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value);
}
public function get stencilReferenceValue() : Number
{
return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE);
}
public function set stencilReferenceValue(value : Number) : void
{
setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value);
}
public function get stencilReadMask() : uint
{
return getProperty(BasicProperties.STENCIL_READ_MASK);
}
public function set stencilReadMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_READ_MASK, value);
}
public function get stencilWriteMask() : uint
{
return getProperty(BasicProperties.STENCIL_WRITE_MASK);
}
public function set stencilWriteMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_WRITE_MASK, value);
}
public function get diffuseTransform() : Matrix4x4
{
return getProperty(BasicProperties.DIFFUSE_TRANSFORM);
}
public function set diffuseTransform(value : Matrix4x4) : void
{
setProperty(BasicProperties.DIFFUSE_TRANSFORM, value);
}
public function get uvOffset() : Vector4
{
return getProperty(BasicProperties.UV_OFFSET);
}
public function set uvOffset(value : Vector4) : void
{
setProperty(BasicProperties.UV_OFFSET, value);
}
public function get uvScale() : Vector4
{
return getProperty(BasicProperties.UV_SCALE);
}
public function set uvScale(value : Vector4) : void
{
setProperty(BasicProperties.UV_SCALE, value);
}
public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME)
{
super(effect || DEFAULT_EFFECT, properties, name);
}
override public function clone() : IDataProvider
{
var mat : BasicMaterial = new BasicMaterial(this, effect, name);
return mat;
}
}
}
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.Material;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.binding.IDataProvider;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
public class BasicMaterial extends Material
{
public static const DEFAULT_NAME : String = 'BasicMaterial';
public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader();
public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER);
public function get blending() : uint
{
return getProperty(BasicProperties.BLENDING);
}
public function set blending(value : uint) : void
{
setProperty(BasicProperties.BLENDING, value);
}
public function get triangleCulling() : uint
{
return getProperty(BasicProperties.TRIANGLE_CULLING);
}
public function set triangleCulling(value : uint) : void
{
setProperty(BasicProperties.TRIANGLE_CULLING, value);
}
public function get diffuseColor() : Object
{
return getProperty(BasicProperties.DIFFUSE_COLOR);
}
public function set diffuseColor(value : Object) : void
{
setProperty(BasicProperties.DIFFUSE_COLOR, value);
}
public function get diffuseMap() : TextureResource
{
return getProperty(BasicProperties.DIFFUSE_MAP);
}
public function set diffuseMap(value : TextureResource) : void
{
setProperty(BasicProperties.DIFFUSE_MAP, value);
}
public function get diffuseMapFiltering() : uint
{
return getProperty(BasicProperties.DIFFUSE_MAP_FILTERING);
}
public function set diffuseMapFiltering(value : uint) : void
{
setProperty(BasicProperties.DIFFUSE_MAP_FILTERING, value);
}
public function get diffuseMapFormat() : uint
{
return getProperty(BasicProperties.DIFFUSE_MAP_FORMAT);
}
public function set diffuseMapFormat(value : uint) : void
{
setProperty(BasicProperties.DIFFUSE_MAP_FORMAT, value);
}
public function get alphaMap() : TextureResource
{
return getProperty(BasicProperties.ALPHA_MAP) as TextureResource;
}
public function set alphaMap(value : TextureResource) : void
{
setProperty(BasicProperties.ALPHA_MAP, value);
}
public function get alphaThreshold() : Number
{
return getProperty(BasicProperties.ALPHA_THRESHOLD);
}
public function set alphaThreshold(value : Number) : void
{
setProperty(BasicProperties.ALPHA_THRESHOLD, value);
}
public function get depthTest() : uint
{
return getProperty(BasicProperties.DEPTH_TEST);
}
public function set depthTest(value : uint) : void
{
setProperty(BasicProperties.DEPTH_TEST, value);
}
public function get depthWriteEnabled() : Boolean
{
return getProperty(BasicProperties.DEPTH_WRITE_ENABLED);
}
public function set depthWriteEnabled(value : Boolean) : void
{
setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value);
}
public function get stencilTriangleFace() : uint
{
return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE);
}
public function set stencilTriangleFace(value : uint) : void
{
setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value);
}
public function get stencilCompareMode() : uint
{
return getProperty(BasicProperties.STENCIL_COMPARE_MODE);
}
public function set stencilCompareMode(value : uint) : void
{
setProperty(BasicProperties.STENCIL_COMPARE_MODE, value);
}
public function get stencilActionBothPass() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS);
}
public function set stencilActionBothPass(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value);
}
public function get stencilActionDepthFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL);
}
public function set stencilActionDepthFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value);
}
public function get stencilActionDepthPassStencilFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL);
}
public function set stencilActionDepthPassStencilFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value);
}
public function get stencilReferenceValue() : Number
{
return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE);
}
public function set stencilReferenceValue(value : Number) : void
{
setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value);
}
public function get stencilReadMask() : uint
{
return getProperty(BasicProperties.STENCIL_READ_MASK);
}
public function set stencilReadMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_READ_MASK, value);
}
public function get stencilWriteMask() : uint
{
return getProperty(BasicProperties.STENCIL_WRITE_MASK);
}
public function set stencilWriteMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_WRITE_MASK, value);
}
public function get diffuseTransform() : Matrix4x4
{
return getProperty(BasicProperties.DIFFUSE_TRANSFORM);
}
public function set diffuseTransform(value : Matrix4x4) : void
{
setProperty(BasicProperties.DIFFUSE_TRANSFORM, value);
}
public function get uvOffset() : Vector4
{
return getProperty(BasicProperties.UV_OFFSET);
}
public function set uvOffset(value : Vector4) : void
{
setProperty(BasicProperties.UV_OFFSET, value);
}
public function get uvScale() : Vector4
{
return getProperty(BasicProperties.UV_SCALE);
}
public function set uvScale(value : Vector4) : void
{
setProperty(BasicProperties.UV_SCALE, value);
}
public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME)
{
super(effect || DEFAULT_EFFECT, properties, name);
}
override public function clone() : IDataProvider
{
var mat : BasicMaterial = new BasicMaterial(this, effect, name);
return mat;
}
}
}
|
add property BasicMaterial.diffuseMapFiltering
|
add property BasicMaterial.diffuseMapFiltering
|
ActionScript
|
mit
|
aerys/minko-as3
|
6e17d4ec0195dd022f4869682b500811524d4a6f
|
src/aerys/minko/render/material/basic/BasicMaterial.as
|
src/aerys/minko/render/material/basic/BasicMaterial.as
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.Material;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.binding.IDataProvider;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
public class BasicMaterial extends Material
{
public static const DEFAULT_NAME : String = 'BasicMaterial';
public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader();
public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER);
public function get diffuseFormat() : uint
{
return getProperty(BasicProperties.DIFFUSE_MAP_FORMAT);
}
public function set diffuseFormat(value : uint) : void
{
setProperty(BasicProperties.DIFFUSE_MAP_FORMAT, value);
}
public function get blending() : uint
{
return getProperty(BasicProperties.BLENDING);
}
public function set blending(value : uint) : void
{
setProperty(BasicProperties.BLENDING, value);
}
public function get triangleCulling() : uint
{
return getProperty(BasicProperties.TRIANGLE_CULLING);
}
public function set triangleCulling(value : uint) : void
{
setProperty(BasicProperties.TRIANGLE_CULLING, value);
}
public function get diffuseColor() : Object
{
return getProperty(BasicProperties.DIFFUSE_COLOR);
}
public function set diffuseColor(value : Object) : void
{
setProperty(BasicProperties.DIFFUSE_COLOR, value);
}
public function get diffuseMap() : TextureResource
{
return getProperty(BasicProperties.DIFFUSE_MAP);
}
public function set diffuseMap(value : TextureResource) : void
{
setProperty(BasicProperties.DIFFUSE_MAP, value);
}
public function get alphaMap() : TextureResource
{
return getProperty(BasicProperties.ALPHA_MAP) as TextureResource;
}
public function set alphaMap(value : TextureResource) : void
{
setProperty(BasicProperties.ALPHA_MAP, value);
}
public function get alphaThreshold() : Number
{
return getProperty(BasicProperties.ALPHA_THRESHOLD);
}
public function set alphaThreshold(value : Number) : void
{
setProperty(BasicProperties.ALPHA_THRESHOLD, value);
}
public function get depthTest() : uint
{
return getProperty(BasicProperties.DEPTH_TEST);
}
public function set depthTest(value : uint) : void
{
setProperty(BasicProperties.DEPTH_TEST, value);
}
public function get depthWriteEnabled() : Boolean
{
return getProperty(BasicProperties.DEPTH_WRITE_ENABLED);
}
public function set depthWriteEnabled(value : Boolean) : void
{
setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value);
}
public function get stencilTriangleFace() : uint
{
return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE);
}
public function set stencilTriangleFace(value : uint) : void
{
setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value);
}
public function get stencilCompareMode() : uint
{
return getProperty(BasicProperties.STENCIL_COMPARE_MODE);
}
public function set stencilCompareMode(value : uint) : void
{
setProperty(BasicProperties.STENCIL_COMPARE_MODE, value);
}
public function get stencilActionBothPass() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS);
}
public function set stencilActionBothPass(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value);
}
public function get stencilActionDepthFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL);
}
public function set stencilActionDepthFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value);
}
public function get stencilActionDepthPassStencilFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL);
}
public function set stencilActionDepthPassStencilFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value);
}
public function get stencilReferenceValue() : Number
{
return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE);
}
public function set stencilReferenceValue(value : Number) : void
{
setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value);
}
public function get stencilReadMask() : uint
{
return getProperty(BasicProperties.STENCIL_READ_MASK);
}
public function set stencilReadMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_READ_MASK, value);
}
public function get stencilWriteMask() : uint
{
return getProperty(BasicProperties.STENCIL_WRITE_MASK);
}
public function set stencilWriteMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_WRITE_MASK, value);
}
public function get diffuseTransform() : Matrix4x4
{
return getProperty(BasicProperties.DIFFUSE_TRANSFORM);
}
public function set diffuseTransform(value : Matrix4x4) : void
{
setProperty(BasicProperties.DIFFUSE_TRANSFORM, value);
}
public function get uvOffset() : Vector4
{
return getProperty(BasicProperties.UV_OFFSET);
}
public function set uvOffset(value : Vector4) : void
{
setProperty(BasicProperties.UV_OFFSET, value);
}
public function get uvScale() : Vector4
{
return getProperty(BasicProperties.UV_SCALE);
}
public function set uvScale(value : Vector4) : void
{
setProperty(BasicProperties.UV_SCALE, value);
}
public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME)
{
super(effect || DEFAULT_EFFECT, properties, name);
}
override public function clone() : IDataProvider
{
var mat : BasicMaterial = new BasicMaterial(this, effect, name);
return mat;
}
}
}
|
package aerys.minko.render.material.basic
{
import aerys.minko.render.Effect;
import aerys.minko.render.material.Material;
import aerys.minko.render.resource.texture.TextureResource;
import aerys.minko.type.binding.IDataProvider;
import aerys.minko.type.math.Matrix4x4;
import aerys.minko.type.math.Vector4;
public class BasicMaterial extends Material
{
public static const DEFAULT_NAME : String = 'BasicMaterial';
public static const DEFAULT_BASIC_SHADER : BasicShader = new BasicShader();
public static const DEFAULT_EFFECT : Effect = new Effect(DEFAULT_BASIC_SHADER);
public function get diffuseMapFormat() : uint
{
return getProperty(BasicProperties.DIFFUSE_MAP_FORMAT);
}
public function set diffuseMapFormat(value : uint) : void
{
setProperty(BasicProperties.DIFFUSE_MAP_FORMAT, value);
}
public function get blending() : uint
{
return getProperty(BasicProperties.BLENDING);
}
public function set blending(value : uint) : void
{
setProperty(BasicProperties.BLENDING, value);
}
public function get triangleCulling() : uint
{
return getProperty(BasicProperties.TRIANGLE_CULLING);
}
public function set triangleCulling(value : uint) : void
{
setProperty(BasicProperties.TRIANGLE_CULLING, value);
}
public function get diffuseColor() : Object
{
return getProperty(BasicProperties.DIFFUSE_COLOR);
}
public function set diffuseColor(value : Object) : void
{
setProperty(BasicProperties.DIFFUSE_COLOR, value);
}
public function get diffuseMap() : TextureResource
{
return getProperty(BasicProperties.DIFFUSE_MAP);
}
public function set diffuseMap(value : TextureResource) : void
{
setProperty(BasicProperties.DIFFUSE_MAP, value);
}
public function get alphaMap() : TextureResource
{
return getProperty(BasicProperties.ALPHA_MAP) as TextureResource;
}
public function set alphaMap(value : TextureResource) : void
{
setProperty(BasicProperties.ALPHA_MAP, value);
}
public function get alphaThreshold() : Number
{
return getProperty(BasicProperties.ALPHA_THRESHOLD);
}
public function set alphaThreshold(value : Number) : void
{
setProperty(BasicProperties.ALPHA_THRESHOLD, value);
}
public function get depthTest() : uint
{
return getProperty(BasicProperties.DEPTH_TEST);
}
public function set depthTest(value : uint) : void
{
setProperty(BasicProperties.DEPTH_TEST, value);
}
public function get depthWriteEnabled() : Boolean
{
return getProperty(BasicProperties.DEPTH_WRITE_ENABLED);
}
public function set depthWriteEnabled(value : Boolean) : void
{
setProperty(BasicProperties.DEPTH_WRITE_ENABLED, value);
}
public function get stencilTriangleFace() : uint
{
return getProperty(BasicProperties.STENCIL_TRIANGLE_FACE);
}
public function set stencilTriangleFace(value : uint) : void
{
setProperty(BasicProperties.STENCIL_TRIANGLE_FACE, value);
}
public function get stencilCompareMode() : uint
{
return getProperty(BasicProperties.STENCIL_COMPARE_MODE);
}
public function set stencilCompareMode(value : uint) : void
{
setProperty(BasicProperties.STENCIL_COMPARE_MODE, value);
}
public function get stencilActionBothPass() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS);
}
public function set stencilActionBothPass(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_BOTH_PASS, value);
}
public function get stencilActionDepthFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL);
}
public function set stencilActionDepthFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_FAIL, value);
}
public function get stencilActionDepthPassStencilFail() : uint
{
return getProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL);
}
public function set stencilActionDepthPassStencilFail(value : uint) : void
{
setProperty(BasicProperties.STENCIL_ACTION_DEPTH_PASS_STENCIL_FAIL, value);
}
public function get stencilReferenceValue() : Number
{
return getProperty(BasicProperties.STENCIL_REFERENCE_VALUE);
}
public function set stencilReferenceValue(value : Number) : void
{
setProperty(BasicProperties.STENCIL_REFERENCE_VALUE, value);
}
public function get stencilReadMask() : uint
{
return getProperty(BasicProperties.STENCIL_READ_MASK);
}
public function set stencilReadMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_READ_MASK, value);
}
public function get stencilWriteMask() : uint
{
return getProperty(BasicProperties.STENCIL_WRITE_MASK);
}
public function set stencilWriteMask(value : uint) : void
{
setProperty(BasicProperties.STENCIL_WRITE_MASK, value);
}
public function get diffuseTransform() : Matrix4x4
{
return getProperty(BasicProperties.DIFFUSE_TRANSFORM);
}
public function set diffuseTransform(value : Matrix4x4) : void
{
setProperty(BasicProperties.DIFFUSE_TRANSFORM, value);
}
public function get uvOffset() : Vector4
{
return getProperty(BasicProperties.UV_OFFSET);
}
public function set uvOffset(value : Vector4) : void
{
setProperty(BasicProperties.UV_OFFSET, value);
}
public function get uvScale() : Vector4
{
return getProperty(BasicProperties.UV_SCALE);
}
public function set uvScale(value : Vector4) : void
{
setProperty(BasicProperties.UV_SCALE, value);
}
public function BasicMaterial(properties : Object = null, effect : Effect = null, name : String = DEFAULT_NAME)
{
super(effect || DEFAULT_EFFECT, properties, name);
}
override public function clone() : IDataProvider
{
var mat : BasicMaterial = new BasicMaterial(this, effect, name);
return mat;
}
}
}
|
refactor BasicMaterial.diffuseFormat into BasicMaterial.diffuseMapFormat
|
refactor BasicMaterial.diffuseFormat into BasicMaterial.diffuseMapFormat
|
ActionScript
|
mit
|
aerys/minko-as3
|
096b3fd9eb743d0f0c772ce3b73787e09d682156
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/TextFieldViewBase.as
|
frameworks/projects/HTML/as/src/org/apache/flex/html/beads/TextFieldViewBase.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.ITextModel;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The TextFieldViewBase class is the base class for
* the components that display text.
* It displays text using a TextField, so there is no
* right-to-left text support in this view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class TextFieldViewBase implements IBeadView, ITextFieldView
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function TextFieldViewBase()
{
_textField = new CSSTextField();
}
private var _textField:CSSTextField;
/**
* @copy org.apache.flex.core.ITextModel#textField
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get textField() : CSSTextField
{
return _textField;
}
private var _textModel:ITextModel;
protected var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
_textModel = value.getBeadByType(ITextModel) as ITextModel;
_textModel.addEventListener("textChange", textChangeHandler);
_textModel.addEventListener("htmlChange", htmlChangeHandler);
IEventDispatcher(_strand).addEventListener("widthChanged", widthChangeHandler);
IEventDispatcher(_strand).addEventListener("heightChanged", heightChangeHandler);
IEventDispatcher(_strand).addEventListener("sizeChanged", sizeChangeHandler);
DisplayObjectContainer(value).addChild(_textField);
if (_textModel.text !== null)
text = _textModel.text;
if (_textModel.html !== null)
html = _textModel.html;
var ilc:ILayoutChild = host as ILayoutChild;
autoHeight = ilc.isHeightSizedToContent();
autoWidth = ilc.isWidthSizedToContent();
if (!autoWidth && !isNaN(ilc.explicitWidth))
{
widthChangeHandler(null);
}
if (!autoHeight && !isNaN(ilc.explicitHeight))
{
heightChangeHandler(null);
}
}
/**
* @private
*/
public function get host() : IUIBase
{
return _strand as IUIBase;
}
/**
* @copy org.apache.flex.core.ITextModel#text
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get text():String
{
return _textField.text;
}
/**
* @private
*/
public function set text(value:String):void
{
if (value == null)
value = "";
_textField.text = value;
autoSizeIfNeeded();
}
private function autoSizeIfNeeded():void
{
var host:UIBase = UIBase(_strand);
if (autoHeight)
{
if (textField.height != textField.textHeight + 4)
{
textField.height = textField.textHeight + 4;
inHeightChange = true;
host.dispatchEvent(new Event("heightChanged"));
inHeightChange = false;
}
}
if (autoWidth)
{
if (textField.width != textField.textWidth + 4)
{
textField.width = textField.textWidth + 4;
inWidthChange = true;
host.dispatchEvent(new Event("widthChanged"));
inWidthChange = false;
}
}
}
/**
* @copy org.apache.flex.core.ITextModel#html
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get html():String
{
return _textField.htmlText;
}
/**
* @private
*/
public function set html(value:String):void
{
_textField.htmlText = value;
autoSizeIfNeeded();
}
private function textChangeHandler(event:Event):void
{
text = _textModel.text;
}
private function htmlChangeHandler(event:Event):void
{
html = _textModel.html;
}
private var autoHeight:Boolean;
private var autoWidth:Boolean;
private var inHeightChange:Boolean = false;
private var inWidthChange:Boolean = false;
private function widthChangeHandler(event:Event):void
{
if (!inWidthChange)
{
textField.autoSize = "none";
autoWidth = false;
textField.width = DisplayObject(_strand).width;
if (autoHeight)
autoSizeIfNeeded()
else
textField.height = DisplayObject(_strand).height;
}
}
private function heightChangeHandler(event:Event):void
{
if (!inHeightChange)
{
textField.autoSize = "none";
autoHeight = false;
textField.height = DisplayObject(_strand).height;
if (autoWidth)
autoSizeIfNeeded();
else
textField.width = DisplayObject(_strand).width;
}
}
private function sizeChangeHandler(event:Event):void
{
var ilc:ILayoutChild = host as ILayoutChild;
autoHeight = ilc.isHeightSizedToContent();
if (!autoHeight)
{
textField.autoSize = "none";
textField.height = DisplayObject(_strand).height;
}
autoWidth = ilc.isWidthSizedToContent();
if (!autoWidth)
{
textField.autoSize = "none";
textField.width = DisplayObject(_strand).width;
}
}
/**
* @copy org.apache.flex.core.IBeadView#viewHeight
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get viewHeight():Number
{
// textfields with autosize collapse if no text
if (_textField.text == "" && autoHeight)
return ValuesManager.valuesImpl.getValue(_strand, "fontSize") + 4;
return _textField.height;
}
/**
* @copy org.apache.flex.core.IBeadView#viewWidth
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get viewWidth():Number
{
// textfields with autosize collapse if no text
if (_textField.text == "" && autoWidth)
return 0;
return _textField.width;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.beads
{
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.text.StyleSheet;
import org.apache.flex.core.CSSTextField;
import org.apache.flex.core.IBeadView;
import org.apache.flex.core.ILayoutChild;
import org.apache.flex.core.IStrand;
import org.apache.flex.core.ITextModel;
import org.apache.flex.core.IUIBase;
import org.apache.flex.core.UIBase;
import org.apache.flex.core.ValuesManager;
import org.apache.flex.events.Event;
import org.apache.flex.events.IEventDispatcher;
/**
* The TextFieldViewBase class is the base class for
* the components that display text.
* It displays text using a TextField, so there is no
* right-to-left text support in this view.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class TextFieldViewBase implements IBeadView, ITextFieldView
{
/**
* Constructor.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function TextFieldViewBase()
{
_textField = new CSSTextField();
}
private var _textField:CSSTextField;
/**
* @copy org.apache.flex.core.ITextModel#textField
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get textField() : CSSTextField
{
return _textField;
}
private var _textModel:ITextModel;
protected var _strand:IStrand;
/**
* @copy org.apache.flex.core.IBead#strand
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function set strand(value:IStrand):void
{
_strand = value;
_textModel = value.getBeadByType(ITextModel) as ITextModel;
_textModel.addEventListener("textChange", textChangeHandler);
_textModel.addEventListener("htmlChange", htmlChangeHandler);
IEventDispatcher(_strand).addEventListener("widthChanged", widthChangeHandler);
IEventDispatcher(_strand).addEventListener("heightChanged", heightChangeHandler);
IEventDispatcher(_strand).addEventListener("sizeChanged", sizeChangeHandler);
DisplayObjectContainer(value).addChild(_textField);
if (_textModel.text !== null)
text = _textModel.text;
if (_textModel.html !== null)
html = _textModel.html;
var ilc:ILayoutChild = host as ILayoutChild;
autoHeight = ilc.isHeightSizedToContent();
autoWidth = ilc.isWidthSizedToContent();
if (!autoWidth && !isNaN(ilc.explicitWidth))
{
widthChangeHandler(null);
}
if (!autoHeight && !isNaN(ilc.explicitHeight))
{
heightChangeHandler(null);
}
}
/**
* @private
*/
public function get host() : IUIBase
{
return _strand as IUIBase;
}
/**
* @copy org.apache.flex.core.ITextModel#text
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get text():String
{
return _textField.text;
}
/**
* @private
*/
public function set text(value:String):void
{
if (value == null)
value = "";
_textField.text = value;
autoSizeIfNeeded();
}
private function autoSizeIfNeeded():void
{
var host:UIBase = UIBase(_strand);
if (autoHeight)
{
if (textField.height != textField.textHeight + 4)
{
textField.height = textField.textHeight + 4;
inHeightChange = true;
host.dispatchEvent(new Event("heightChanged"));
inHeightChange = false;
}
}
if (autoWidth)
{
if (textField.width != textField.textWidth + 4)
{
textField.width = textField.textWidth + 4;
inWidthChange = true;
host.dispatchEvent(new Event("widthChanged"));
inWidthChange = false;
}
}
}
/**
* @copy org.apache.flex.core.ITextModel#html
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get html():String
{
return _textField.htmlText;
}
/**
* @private
*/
public function set html(value:String):void
{
convertToTextFieldHTML(value);
autoSizeIfNeeded();
}
private function convertToTextFieldHTML(input:String):void
{
var classCount:int = 0;
var ss:StyleSheet;
var c:int = input.indexOf("<span");
while (c != -1)
{
var c1:int = input.indexOf(">", c);
if (c1 == -1)
{
trace("did not parse span correctly");
return;
}
var tag:String = input.substring(c, c1 + 1);
var c2:int = tag.indexOf("style=");
if (c2 != -1)
{
var quote:String = tag.charAt(c2 + 6);
var c3:int = tag.indexOf(quote, c2 + 7);
if (c3 != -1)
{
var styles:String = tag.substring(c2 + 7, c3);
if (!ss)
ss = new StyleSheet();
var styleObject:Object = {};
var list:Array = styles.split(";");
for each (var pair:String in list)
{
var parts:Array = pair.split(":");
var name:String = parts[0];
var c4:int = name.indexOf("-");
if (c4 != -1)
{
var firstChar:String = name.charAt(c4 + 1);
firstChar = firstChar.toUpperCase();
var tail:String = name.substring(c4 + 2);
name = name.substring(0, c4) + firstChar + tail;
}
styleObject[name] = parts[1];
}
var className:String = "css" + classCount++;
ss.setStyle("." + className, styleObject);
var newTag:String = "<span class='" + className + "'>";
input = input.replace(tag, newTag);
c1 += newTag.length - tag.length;
}
}
c = input.indexOf("<span", c1);
}
_textField.styleSheet = ss;
_textField.htmlText = input;
}
private function textChangeHandler(event:Event):void
{
text = _textModel.text;
}
private function htmlChangeHandler(event:Event):void
{
html = _textModel.html;
}
private var autoHeight:Boolean;
private var autoWidth:Boolean;
private var inHeightChange:Boolean = false;
private var inWidthChange:Boolean = false;
private function widthChangeHandler(event:Event):void
{
if (!inWidthChange)
{
textField.autoSize = "none";
autoWidth = false;
textField.width = DisplayObject(_strand).width;
if (autoHeight)
autoSizeIfNeeded()
else
textField.height = DisplayObject(_strand).height;
}
}
private function heightChangeHandler(event:Event):void
{
if (!inHeightChange)
{
textField.autoSize = "none";
autoHeight = false;
textField.height = DisplayObject(_strand).height;
if (autoWidth)
autoSizeIfNeeded();
else
textField.width = DisplayObject(_strand).width;
}
}
private function sizeChangeHandler(event:Event):void
{
var ilc:ILayoutChild = host as ILayoutChild;
autoHeight = ilc.isHeightSizedToContent();
if (!autoHeight)
{
textField.autoSize = "none";
textField.height = DisplayObject(_strand).height;
}
autoWidth = ilc.isWidthSizedToContent();
if (!autoWidth)
{
textField.autoSize = "none";
textField.width = DisplayObject(_strand).width;
}
}
/**
* @copy org.apache.flex.core.IBeadView#viewHeight
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get viewHeight():Number
{
// textfields with autosize collapse if no text
if (_textField.text == "" && autoHeight)
return ValuesManager.valuesImpl.getValue(_strand, "fontSize") + 4;
return _textField.height;
}
/**
* @copy org.apache.flex.core.IBeadView#viewWidth
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function get viewWidth():Number
{
// textfields with autosize collapse if no text
if (_textField.text == "" && autoWidth)
return 0;
return _textField.width;
}
}
}
|
handle spans better in html
|
handle spans better in html
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
db2189d0e45261df83ce3a64fa8f87869aef0d23
|
as3/xobjas3/src/com/rpath/xobj/XObjMetadata.as
|
as3/xobjas3/src/com/rpath/xobj/XObjMetadata.as
|
/*
#
# Copyright (c) 2008 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.xobj
{
[RemoteClass] // tell the compiler we can be deep copied
public class XObjMetadata
{
public var attributes:Array;
public var elements:Array;
//public var namespaces:Array;
public static const METADATA_PROPERTY:String = "_xobj";
public function XObjMetadata()
{
super();
attributes = [];
elements = [];
//namespaces = [];
}
private static function getMetadata(target:*):XObjMetadata
{
var result:XObjMetadata = null;
if (METADATA_PROPERTY in target)
{
result = target[METADATA_PROPERTY];
}
else
{
// doesn't exist. Try creating it
try
{
target[METADATA_PROPERTY] = new XObjMetadata();
result = target[METADATA_PROPERTY];
}
catch (e:Error)
{
// must be nondynamic type
}
}
return result;
}
public static function setElements(target:*, elements:Array):void
{
var xobj:XObjMetadata = getMetadata(target);
if (xobj)
{
xobj.elements = elements;
}
}
public static function setAttributes(target:*, attributes:Array):void
{
var xobj:XObjMetadata = getMetadata(target);
if (xobj)
{
if (attributes.length == 0)
trace("damn!");
xobj.attributes = attributes;
}
}
public function addAttribute(entry:*):void
{
attributes.push(entry);
}
public function addElement(entry:*):void
{
elements.push(entry);
}
}
}
|
/*
#
# Copyright (c) 2008 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.xobj
{
[RemoteClass] // tell the compiler we can be deep copied
public class XObjMetadata
{
public var attributes:Array;
public var elements:Array;
//public var namespaces:Array;
public static const METADATA_PROPERTY:String = "_xobj";
public function XObjMetadata()
{
super();
attributes = [];
elements = [];
//namespaces = [];
}
private static function getMetadata(target:*):XObjMetadata
{
var result:XObjMetadata = null;
if (METADATA_PROPERTY in target)
{
result = target[METADATA_PROPERTY];
}
else
{
// doesn't exist. Try creating it
try
{
target[METADATA_PROPERTY] = new XObjMetadata();
target.setPropertyIsEnumerable(METADATA_PROPERTY, false);
result = target[METADATA_PROPERTY];
}
catch (e:Error)
{
// must be nondynamic type
}
}
return result;
}
public static function setElements(target:*, elements:Array):void
{
var xobj:XObjMetadata = getMetadata(target);
if (xobj)
{
xobj.elements = elements;
}
}
public static function setAttributes(target:*, attributes:Array):void
{
var xobj:XObjMetadata = getMetadata(target);
if (xobj)
{
if (attributes.length == 0)
trace("damn!");
xobj.attributes = attributes;
}
}
public function addAttribute(entry:*):void
{
attributes.push(entry);
}
public function addElement(entry:*):void
{
elements.push(entry);
}
}
}
|
Set the _xobj metadata property to be non-enumerable so that it does not contaminate for each (in) constructs
|
Set the _xobj metadata property to be non-enumerable so that it does not contaminate for each (in) constructs
|
ActionScript
|
apache-2.0
|
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
|
ce3f0808baa184afc325d2a2022af382778aad96
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/events/DragEvent.as
|
frameworks/as/projects/FlexJSUI/src/org/apache/flex/events/DragEvent.as
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.events
{
import flash.events.MouseEvent;
import org.apache.flex.core.IDragInitiator;
/**
* Drag and Drop Events.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class DragEvent extends MouseEvent
{
/**
* The <code>DragEvent.DRAG_START</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragStart</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragStart
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_START:String = "dragStart";
/**
* The <code>DragEvent.DRAG_MOVE</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragMove</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragMove
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_MOVE:String = "dragMove";
/**
* The <code>DragEvent.DRAG_END</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragEnd</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragEnd
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_END:String = "dragEnd";
/**
* The <code>DragEvent.DRAG_ENTER</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragEnter</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragEnter
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_ENTER:String = "dragEnter";
/**
* The <code>DragEvent.DRAG_OVER</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragOver</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragOver
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_OVER:String = "dragOver";
/**
* The <code>DragEvent.DRAG_EXIT</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragExit</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragExit
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_EXIT:String = "dragExit";
/**
* The <code>DragEvent.DRAG_DROP</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragDrop</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragDrop
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_DROP:String = "dragDrop";
/**
* Constructor.
*
* @param type The name of the event.
* @param bubbles Whether the event bubbles.
* @param cancelable Whether the event can be canceled.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function DragEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
/**
* The object that wants to know if a drop is accepted
*
* @param type The name of the event.
* @param bubbles Whether the event bubbles.
* @param cancelable Whether the event can be canceled.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var dragInitiator:IDragInitiator;
/**
* The data being dragged. Or an instance
* of an object describing the data.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var dragSource:Object;
public function copyMouseEventProperties(event:MouseEvent):void
{
localX = event.localX;
localY = event.localY;
altKey = event.altKey;
ctrlKey = event.ctrlKey;
shiftKey = event.shiftKey;
buttonDown = event.buttonDown;
delta = event.delta;
relatedObject = event.relatedObject;
}
}
}
|
////////////////////////////////////////////////////////////////////////////////
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.events
{
import flash.events.MouseEvent;
import org.apache.flex.core.IDragInitiator;
/**
* Drag and Drop Events.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public class DragEvent extends flash.events.MouseEvent
{
/**
* The <code>DragEvent.DRAG_START</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragStart</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragStart
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_START:String = "dragStart";
/**
* The <code>DragEvent.DRAG_MOVE</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragMove</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragMove
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_MOVE:String = "dragMove";
/**
* The <code>DragEvent.DRAG_END</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragEnd</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragEnd
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_END:String = "dragEnd";
/**
* The <code>DragEvent.DRAG_ENTER</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragEnter</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragEnter
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_ENTER:String = "dragEnter";
/**
* The <code>DragEvent.DRAG_OVER</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragOver</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragOver
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_OVER:String = "dragOver";
/**
* The <code>DragEvent.DRAG_EXIT</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragExit</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragExit
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_EXIT:String = "dragExit";
/**
* The <code>DragEvent.DRAG_DROP</code> constant defines the value of the
* event object's <code>type</code> property for a <code>dragDrop</code> event.
*
* <p>The properties of the event object have the following values:</p>
* <table class="innertable">
* <tr><th>Property</th><th>Value</th></tr>
* <tr><td><code>bubbles</code></td><td>false</td></tr>
* <tr><td><code>cancelable</code></td><td>false</td></tr>
* <tr><td><code>currentTarget</code></td><td>The Object that defines the
* event listener that handles the event. For example, if you use
* <code>myButton.addEventListener()</code> to register an event listener,
* myButton is the value of the <code>currentTarget</code>. </td></tr>
* <tr><td><code>target</code></td><td>The Object that dispatched the event;
* it is not always the Object listening for the event.
* Use the <code>currentTarget</code> property to always access the
* Object listening for the event.</td></tr>
* </table>
*
* @eventType dragDrop
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
public static const DRAG_DROP:String = "dragDrop";
/**
* Constructor.
*
* @param type The name of the event.
* @param bubbles Whether the event bubbles.
* @param cancelable Whether the event can be canceled.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public function DragEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
/**
* The object that wants to know if a drop is accepted
*
* @param type The name of the event.
* @param bubbles Whether the event bubbles.
* @param cancelable Whether the event can be canceled.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var dragInitiator:IDragInitiator;
/**
* The data being dragged. Or an instance
* of an object describing the data.
*
* @langversion 3.0
* @playerversion Flash 10.2
* @playerversion AIR 2.6
* @productversion FlexJS 0.0
*/
public var dragSource:Object;
public function copyMouseEventProperties(event:flash.events.MouseEvent):void
{
localX = event.localX;
localY = event.localY;
altKey = event.altKey;
ctrlKey = event.ctrlKey;
shiftKey = event.shiftKey;
buttonDown = event.buttonDown;
delta = event.delta;
relatedObject = event.relatedObject;
}
}
}
|
Remove ambiguity of MouseEvent reference.
|
Remove ambiguity of MouseEvent reference.
|
ActionScript
|
apache-2.0
|
greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs,greg-dove/flex-asjs
|
c06b593f11e700dca275f91ca89913686068ce83
|
flexEditor/src/org/arisgames/editor/view/CreateOrOpenGameSelectorView.as
|
flexEditor/src/org/arisgames/editor/view/CreateOrOpenGameSelectorView.as
|
package org.arisgames.editor.view
{
import flash.events.MouseEvent;
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import mx.containers.Panel;
import mx.controls.Alert;
import mx.controls.Button;
import mx.controls.DataGrid;
import mx.controls.TextArea;
import mx.controls.TextInput;
import mx.events.DynamicEvent;
import mx.events.FlexEvent;
import mx.rpc.Responder;
import mx.rpc.events.ResultEvent;
import org.arisgames.editor.data.Game;
import org.arisgames.editor.data.PlaceMark;
import org.arisgames.editor.data.arisserver.Item;
import org.arisgames.editor.data.arisserver.Media;
import org.arisgames.editor.data.arisserver.NPC;
import org.arisgames.editor.data.arisserver.Node;
import org.arisgames.editor.data.arisserver.WebPage;
import org.arisgames.editor.data.businessobjects.ObjectPaletteItemBO;
import org.arisgames.editor.models.GameModel;
import org.arisgames.editor.models.SecurityModel;
import org.arisgames.editor.models.StateModel;
import org.arisgames.editor.services.AppServices;
import org.arisgames.editor.util.AppConstants;
import org.arisgames.editor.util.AppDynamicEventManager;
import org.arisgames.editor.util.AppUtils;
public class CreateOrOpenGameSelectorView extends Panel
{
[Bindable] public var nameOfGame:TextInput;
[Bindable] public var gameDescription:TextArea;
[Bindable] public var createGameButton:Button;
[Bindable] public var gamesDataGrid:DataGrid;
[Bindable] public var loadGameButton:Button;
[Bindable] public var usersGames:ArrayCollection;
/**
* Constructor
*/
public function CreateOrOpenGameSelectorView()
{
super();
usersGames = new ArrayCollection();
this.addEventListener(FlexEvent.CREATION_COMPLETE, onComplete);
}
private function onComplete(event:FlexEvent): void
{
doubleClickEnabled = true;
createGameButton.addEventListener(MouseEvent.CLICK, onCreateButtonClick);
loadGameButton.addEventListener(MouseEvent.CLICK, onLoadButtonClick);
gamesDataGrid.addEventListener(MouseEvent.DOUBLE_CLICK, onDoubleClick);
AppServices.getInstance().loadGamesByUserId(SecurityModel.getInstance().getUserId(), new Responder(handleLoadUsersGames, handleFault));
AppDynamicEventManager.getInstance().addEventListener(AppConstants.APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED, handleCurrentStateChangedEvent);
}
private function handleCurrentStateChangedEvent(obj:Object):void
{
trace("CreateOrOpenGameSelectorView: handleCurrentStateChangedEvent");
if (StateModel.getInstance().currentState == StateModel.VIEWCREATEOROPENGAMEWINDOW){
trace("CreateOrOpenGameSelectorView: handleCurrentStateChangedEvent: Refreshing");
nameOfGame.text = "";
gameDescription.text = "";
usersGames.removeAll();
AppServices.getInstance().loadGamesByUserId(SecurityModel.getInstance().getUserId(), new Responder(handleLoadUsersGames, handleFault));
}
}
private function handleLoadUsersGames(obj:Object):void
{
trace("handleLoadUsersGames");
usersGames.removeAll();
if (obj.result.data == null)
{
trace("obj.result.data is NULL");
return;
}
for (var j:Number = 0; j < obj.result.data.list.length; j++)
{
var g:Game = new Game();
g.gameId = obj.result.data.list.getItemAt(j).game_id;
g.name = obj.result.data.list.getItemAt(j).name;
g.description = obj.result.data.list.getItemAt(j).description;
g.iconMediaId = obj.result.data.list.getItemAt(j).icon_media_id;
g.mediaId = obj.result.data.list.getItemAt(j).media_id;
g.pcMediaId = obj.result.data.list.getItemAt(j).pc_media_id;
g.introNodeId = obj.result.data.list.getItemAt(j).on_launch_node_id;
g.completeNodeId = obj.result.data.list.getItemAt(j).game_complete_node_id;
g.allowsPlayerCreatedLocations = obj.result.data.list.getItemAt(j).allow_player_created_locations;
g.resetDeletesPlayerCreatedLocations = obj.result.data.list.getItemAt(j).delete_player_locations_on_reset;
g.isLocational = obj.result.data.list.getItemAt(j).is_locational;
g.readyForPublic = obj.result.data.list.getItemAt(j).ready_for_public;
usersGames.addItem(g);
}
trace("done loading UsersGames.");
}
private function onCreateButtonClick(evt:MouseEvent):void
{
trace("create button clicked!");
var g:Game = new Game();
GameModel.getInstance().game = g;
g.name = nameOfGame.text;
g.description = gameDescription.text;
AppServices.getInstance().saveGame(g, new Responder(handleCreateGame, handleFault));
}
private function onLoadButtonClick(evt:MouseEvent):void
{
trace("load button clicked!");
//make sure something is happening
if(gamesDataGrid.selectedItem != null){
var g:Game = gamesDataGrid.selectedItem as Game;
trace("Selected game to load data for has Id = " + g.gameId);
// Load the game into the app's models
GameModel.getInstance().game = g;
GameModel.getInstance().game.placeMarks.removeAll();
GameModel.getInstance().game.gameObjects.removeAll();
GameModel.getInstance().loadLocations();
StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR;
}
}
private function onDoubleClick(evt:MouseEvent):void
{
trace("Double Click");
//make sure something is happening
if(gamesDataGrid.selectedItem != null){
var g:Game = gamesDataGrid.selectedItem as Game;
trace("Selected game to load data for has Id = " + g.gameId);
// Load the game into the app's models
GameModel.getInstance().game = g;
GameModel.getInstance().game.placeMarks.removeAll();
GameModel.getInstance().game.gameObjects.removeAll();
GameModel.getInstance().loadLocations();
StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR;
}
}
public function handleCreateGame(obj:Object):void
{
trace("Result called with obj = " + obj + "; Result = " + obj.result);
if (obj.result.returnCode != 0)
{
trace("Bad create game attempt... let's see what happened.");
var msg:String = obj.result.returnCodeDescription;
Alert.show("Error Was: " + msg, "Error While Creating Game");
}
else
{
trace("Game Creation was successfull");
GameModel.getInstance().game.gameId = obj.result.data;
GameModel.getInstance().game.name = nameOfGame.text;
GameModel.getInstance().game.description = gameDescription.text;
Alert.show("Your game was succesfully created. Please use the editor to start building it.", "Successfully Created Game");
//Clear everything from previous loads of other games
GameModel.getInstance().game.placeMarks.removeAll();
GameModel.getInstance().game.gameObjects.removeAll();
GameModel.getInstance().loadLocations();
StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR;
}
}
public function handleFault(obj:Object):void
{
trace("Fault called. The error is: " + obj.fault.faultString);
Alert.show("Error occurred: " + obj.fault.faultString, "More problems..");
}
}
}
|
package org.arisgames.editor.view
{
import flash.events.MouseEvent;
import flash.utils.Dictionary;
import mx.collections.ArrayCollection;
import mx.containers.Panel;
import mx.controls.Alert;
import mx.controls.Button;
import mx.controls.DataGrid;
import mx.controls.TextArea;
import mx.controls.TextInput;
import mx.events.DynamicEvent;
import mx.events.FlexEvent;
import mx.rpc.Responder;
import mx.rpc.events.ResultEvent;
import org.arisgames.editor.data.Game;
import org.arisgames.editor.data.PlaceMark;
import org.arisgames.editor.data.arisserver.Item;
import org.arisgames.editor.data.arisserver.Media;
import org.arisgames.editor.data.arisserver.NPC;
import org.arisgames.editor.data.arisserver.Node;
import org.arisgames.editor.data.arisserver.WebPage;
import org.arisgames.editor.data.businessobjects.ObjectPaletteItemBO;
import org.arisgames.editor.models.GameModel;
import org.arisgames.editor.models.SecurityModel;
import org.arisgames.editor.models.StateModel;
import org.arisgames.editor.services.AppServices;
import org.arisgames.editor.util.AppConstants;
import org.arisgames.editor.util.AppDynamicEventManager;
import org.arisgames.editor.util.AppUtils;
public class CreateOrOpenGameSelectorView extends Panel
{
[Bindable] public var nameOfGame:TextInput;
[Bindable] public var gameDescription:TextArea;
[Bindable] public var createGameButton:Button;
[Bindable] public var gamesDataGrid:DataGrid;
[Bindable] public var loadGameButton:Button;
[Bindable] public var usersGames:ArrayCollection;
/**
* Constructor
*/
public function CreateOrOpenGameSelectorView()
{
super();
usersGames = new ArrayCollection();
this.addEventListener(FlexEvent.CREATION_COMPLETE, onComplete);
}
private function onComplete(event:FlexEvent): void
{
doubleClickEnabled = true;
createGameButton.addEventListener(MouseEvent.CLICK, onCreateButtonClick);
loadGameButton.addEventListener(MouseEvent.CLICK, onLoadButtonClick);
gamesDataGrid.addEventListener(MouseEvent.DOUBLE_CLICK, onDoubleClick);
AppServices.getInstance().loadGamesByUserId(SecurityModel.getInstance().getUserId(), new Responder(handleLoadUsersGames, handleFault));
AppDynamicEventManager.getInstance().addEventListener(AppConstants.APPLICATIONDYNAMICEVENT_CURRENTSTATECHANGED, handleCurrentStateChangedEvent);
}
private function handleCurrentStateChangedEvent(obj:Object):void
{
trace("CreateOrOpenGameSelectorView: handleCurrentStateChangedEvent");
if (StateModel.getInstance().currentState == StateModel.VIEWCREATEOROPENGAMEWINDOW){
trace("CreateOrOpenGameSelectorView: handleCurrentStateChangedEvent: Refreshing");
nameOfGame.text = "";
gameDescription.text = "";
usersGames.removeAll();
AppServices.getInstance().loadGamesByUserId(SecurityModel.getInstance().getUserId(), new Responder(handleLoadUsersGames, handleFault));
}
}
private function handleLoadUsersGames(obj:Object):void
{
trace("handleLoadUsersGames");
usersGames.removeAll();
if (obj.result.data == null)
{
trace("obj.result.data is NULL");
return;
}
for (var j:Number = 0; j < obj.result.data.list.length; j++)
{
var g:Game = new Game();
g.gameId = obj.result.data.list.getItemAt(j).game_id;
g.name = obj.result.data.list.getItemAt(j).name;
g.description = obj.result.data.list.getItemAt(j).description;
g.iconMediaId = obj.result.data.list.getItemAt(j).icon_media_id;
g.mediaId = obj.result.data.list.getItemAt(j).media_id;
g.pcMediaId = obj.result.data.list.getItemAt(j).pc_media_id;
g.introNodeId = obj.result.data.list.getItemAt(j).on_launch_node_id;
g.completeNodeId = obj.result.data.list.getItemAt(j).game_complete_node_id;
g.allowsPlayerCreatedLocations = obj.result.data.list.getItemAt(j).allow_player_created_locations;
g.resetDeletesPlayerCreatedLocations = obj.result.data.list.getItemAt(j).delete_player_locations_on_reset;
g.isLocational = obj.result.data.list.getItemAt(j).is_locational;
g.readyForPublic = obj.result.data.list.getItemAt(j).ready_for_public;
usersGames.addItem(g);
}
trace("done loading UsersGames.");
}
private function onCreateButtonClick(evt:MouseEvent):void
{
trace("create button clicked!");
var g:Game = new Game();
GameModel.getInstance().game = g;
g.name = nameOfGame.text;
g.description = gameDescription.text;
AppServices.getInstance().saveGame(g, new Responder(handleCreateGame, handleFault));
}
private function onLoadButtonClick(evt:MouseEvent):void
{
trace("load button clicked!");
//make sure something is happening
if(gamesDataGrid.selectedItem != null){
var g:Game = gamesDataGrid.selectedItem as Game;
trace("Selected game to load data for has Id = " + g.gameId);
// Load the game into the app's models
GameModel.getInstance().game = g;
GameModel.getInstance().game.placeMarks.removeAll();
GameModel.getInstance().game.gameObjects.removeAll();
GameModel.getInstance().loadLocations();
StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR;
var de:DynamicEvent = new DynamicEvent(AppConstants.DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR);
AppDynamicEventManager.getInstance().dispatchEvent(de);
}
}
private function onDoubleClick(evt:MouseEvent):void
{
trace("Double Click");
//make sure something is happening
if(gamesDataGrid.selectedItem != null){
var g:Game = gamesDataGrid.selectedItem as Game;
trace("Selected game to load data for has Id = " + g.gameId);
// Load the game into the app's models
GameModel.getInstance().game = g;
GameModel.getInstance().game.placeMarks.removeAll();
GameModel.getInstance().game.gameObjects.removeAll();
GameModel.getInstance().loadLocations();
StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR;
var de:DynamicEvent = new DynamicEvent(AppConstants.DYNAMICEVENT_CLOSEOBJECTPALETTEITEMEDITOR);
AppDynamicEventManager.getInstance().dispatchEvent(de);
}
}
public function handleCreateGame(obj:Object):void
{
trace("Result called with obj = " + obj + "; Result = " + obj.result);
if (obj.result.returnCode != 0)
{
trace("Bad create game attempt... let's see what happened.");
var msg:String = obj.result.returnCodeDescription;
Alert.show("Error Was: " + msg, "Error While Creating Game");
}
else
{
trace("Game Creation was successfull");
GameModel.getInstance().game.gameId = obj.result.data;
GameModel.getInstance().game.name = nameOfGame.text;
GameModel.getInstance().game.description = gameDescription.text;
Alert.show("Your game was succesfully created. Please use the editor to start building it.", "Successfully Created Game");
//Clear everything from previous loads of other games
GameModel.getInstance().game.placeMarks.removeAll();
GameModel.getInstance().game.gameObjects.removeAll();
GameModel.getInstance().loadLocations();
StateModel.getInstance().currentState = StateModel.VIEWGAMEEDITOR;
}
}
public function handleFault(obj:Object):void
{
trace("Fault called. The error is: " + obj.fault.faultString);
Alert.show("Error occurred: " + obj.fault.faultString, "More problems..");
}
}
}
|
Delete modals on game switch
|
Delete modals on game switch
|
ActionScript
|
mit
|
ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames,ssdongdongwang/arisgames
|
116bc790ae50d9d9c1f52a52198922c0ff891fdb
|
HLSPlugin/src/com/kaltura/hls/m2ts/PESProcessor.as
|
HLSPlugin/src/com/kaltura/hls/m2ts/PESProcessor.as
|
package com.kaltura.hls.m2ts
{
import flash.utils.ByteArray;
import flash.net.ObjectEncoding;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import com.hurlant.util.Hex;
CONFIG::LOGGING
{
import org.osmf.logging.Logger;
import org.osmf.logging.Log;
}
/**
* Process packetized elementary streams and extract NALUs and other data.
*/
public class PESProcessor
{
CONFIG::LOGGING
{
private static const logger:Logger = Log.getLogger("com.kaltura.hls.m2ts.PESProcessor");
}
public var types:Object = {};
public var streams:Object = {};
public var lastVideoNALU:NALU = null;
public var transcoder:FLVTranscoder = new FLVTranscoder();
public var headerSent:Boolean = false;
public var pmtStreamId:int = -1;
protected var pendingBuffers:Vector.<Object> = new Vector.<Object>();
protected var pendingLastConvertedIndex:int = 0;
public var lastPTS:Number = 0, lastDTS:Number = 0;
/**
* Given a MPEG timestamp we've seen previously, determine if the new timestamp
* has wrapped and correct it to follow the old timestamp.
*/
static function handleMpegTimestampWrap(newTime:Number, oldTime:Number):Number
{
while (!isNaN(oldTime) && (Math.abs(newTime - oldTime) > 4294967296))
newTime += (oldTime < newTime) ? -8589934592 : 8589934592;
return newTime;
}
public function logStreams():void
{
CONFIG::LOGGING
{
logger.debug("----- PES state -----");
for(var k:* in streams)
{
logger.debug(" " + k + " has " + streams[k].buffer.length + " bytes, type=" + types[k]);
}
}
}
public function clear(clearAACConfig:Boolean = true):void
{
streams = {};
lastVideoNALU = null;
transcoder.clear(clearAACConfig);
// Reset PTS/DTS reference.
lastPTS = lastDTS = 0;
}
private function parseProgramAssociationTable(bytes:ByteArray, cursor:uint):Boolean
{
// Get the section length.
var sectionLen:uint = ((bytes[cursor+2] & 0x03) << 8) | bytes[cursor+3];
// Check the section length for a single PMT.
CONFIG::LOGGING
{
if (sectionLen > 13)
{
logger.debug("Saw multiple PMT entries in the PAT; blindly choosing first one.");
}
}
// Grab the PMT ID.
pmtStreamId = ((bytes[cursor+10] << 8) | bytes[cursor+11]) & 0x1FFF;
CONFIG::LOGGING
{
logger.debug("Saw PMT ID of " + pmtStreamId);
}
return true;
}
private function parseProgramMapTable(bytes:ByteArray, cursor:uint):Boolean
{
var sectionLength:uint;
var sectionLimit:uint;
var programInfoLength:uint;
var type:uint;
var pid:uint;
var esInfoLength:uint;
var seenPIDsByClass:Array;
var mediaClass:int;
var hasAudio:Boolean = false, hasVideo:Boolean = false;
// Set up types.
types = [];
seenPIDsByClass = [];
seenPIDsByClass[MediaClass.VIDEO] = Infinity;
seenPIDsByClass[MediaClass.AUDIO] = Infinity;
// Process section length and limit.
cursor++;
sectionLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1];
cursor += 2;
if(sectionLength + cursor > bytes.length)
{
CONFIG::LOGGING
{
logger.error("Not enough data to read. 1");
}
return false;
}
// Skip a few things we don't care about: program number, RSV, version, CNI, section, last_section, pcr_cid
sectionLimit = cursor + sectionLength;
cursor += 7;
// And get the program info length.
programInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1];
cursor += 2;
// If not enough data to proceed, bail.
if(programInfoLength + cursor > bytes.length)
{
CONFIG::LOGGING
{
logger.error("Not enough data to read. 2");
}
return false;
}
cursor += programInfoLength;
const CRC_SIZE:int = 4;
while(cursor < sectionLimit - CRC_SIZE)
{
type = bytes[cursor++];
pid = ((bytes[cursor] & 0x1f) << 8) + bytes[cursor + 1];
cursor += 2;
mediaClass = MediaClass.calculate(type);
if(mediaClass == MediaClass.VIDEO)
hasVideo = true
if(mediaClass == MediaClass.AUDIO)
hasAudio = true
// For video & audio, select the lowest PID for each kind.
if(mediaClass == MediaClass.OTHER
|| pid < seenPIDsByClass[mediaClass])
{
// Clear a higher PID if present.
if(mediaClass != MediaClass.OTHER
&& seenPIDsByClass[mediaClass] < Infinity)
types[seenPIDsByClass[mediaClass]] = -1;
types[pid] = type;
seenPIDsByClass[mediaClass] = pid;
}
// Skip the esInfo data.
esInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1];
cursor += 2;
cursor += esInfoLength;
}
// Cook out header to transcoder.
//transcoder.writeHeader(hasAudio, hasVideo);
headerSent = true;
return true;
}
public function append(packet:PESPacket):Boolean
{
// logger.debug("saw packet of " + packet.buffer.length);
var b:ByteArray = packet.buffer;
b.position = 0;
if(b.length < 8)
{
CONFIG::LOGGING
{
logger.error("Ignoring too short PES packet, length=" + b.length);
}
return true;
}
// Get the start code.
var startCode:uint = b.readUnsignedInt();
if((startCode & 0xFFFFFF00) != 0x00000100)
{
// It could be a program association table.
if((startCode & 0xFFFFFF00) == 0x0000b000)
{
parseProgramAssociationTable(b, 1);
return true;
}
// It could be the program map table.
if((startCode & 0xFFFFFC00) == 0x0002b000)
{
parseProgramMapTable(b, 1);
return true;
}
var tmp:ByteArray = new ByteArray();
tmp.writeInt(startCode);
CONFIG::LOGGING
{
logger.error("ES prefix was wrong, expected 00:00:01:xx but got " + Hex.fromArray(tmp, true));
}
return true;
}
// Get the stream ID.
var streamID:int = startCode & 0xFF;
// Get the length.
var packetLength:uint = b.readUnsignedShort();
if(packetLength)
{
if(b.length < packetLength )
{
CONFIG::LOGGING
{
logger.warn("WARNING: parsePESPacket - not enough bytes, expecting " + packetLength + ", but have " + b.length);
}
return false; // not enough bytes in packet
}
}
if(b.length < 9)
{
CONFIG::LOGGING
{
logger.warn("WARNING: parsePESPacket - too short to read header!");
}
return false;
}
// Read the rest of the header.
var cursor:uint = 6;
var dataAlignment:Boolean = (b[cursor] & 0x04) != 0;
cursor++;
var ptsDts:uint = (b[cursor] & 0xc0) >> 6;
cursor++;
var pesHeaderDataLength:uint = b[cursor];
cursor++;
//logger.debug(" PES align=" + dataAlignment + " ptsDts=" + ptsDts + " header=" + pesHeaderDataLength);
var pts:Number = 0, dts:Number = 0;
if(ptsDts & 0x02)
{
// has PTS at least
if(cursor + 5 > b.length)
return true;
pts = b[cursor] & 0x0e;
pts *= 128;
pts += b[cursor + 1];
pts *= 256;
pts += b[cursor + 2] & 0xfe;
pts *= 128;
pts += b[cursor + 3];
pts *= 256;
pts += b[cursor + 4] & 0xfe;
pts /= 2;
if(ptsDts & 0x01)
{
// DTS too!
if(cursor + 10 > b.length)
return true;
dts = b[cursor + 5] & 0x0e;
dts *= 128;
dts += b[cursor + 6];
dts *= 256;
dts += b[cursor + 7] & 0xfe;
dts *= 128;
dts += b[cursor + 8];
dts *= 256;
dts += b[cursor + 9] & 0xfe;
dts /= 2;
}
else
{
//logger.debug("Filling in DTS")
dts = pts;
}
}
// Condition PTS and DTS.
pts = handleMpegTimestampWrap(pts, lastPTS);
lastPTS = pts;
dts = handleMpegTimestampWrap(dts, lastDTS);
lastDTS = dts;
packet.pts = pts;
packet.dts = dts;
//logger.debug(" PTS=" + pts/90000 + " DTS=" + dts/90000);
cursor += pesHeaderDataLength;
if(cursor > b.length)
{
CONFIG::LOGGING
{
logger.warn("WARNING: parsePESPacket - ran out of bytes");
}
return true;
}
if(types[packet.packetID] == undefined)
{
CONFIG::LOGGING
{
logger.warn("WARNING: parsePESPacket - unknown type");
}
return true;
}
var pes:PESPacketStream;
if(streams[packet.packetID] == undefined)
{
if(dts < 0.0)
{
CONFIG::LOGGING
{
logger.warn("WARNING: parsePESPacket - invalid decode timestamp, skipping");
}
return true;
}
pes = new PESPacketStream();
streams[packet.packetID] = pes;
}
else
{
pes = streams[packet.packetID];
}
if(headerSent == false)
{
CONFIG::LOGGING
{
logger.warn("Skipping data that came before PMT");
}
return true;
}
// Note the type at this moment in time.
packet.type = types[packet.packetID];
packet.headerLength = cursor;
// And process.
if(MediaClass.calculate(types[packet.packetID]) == MediaClass.VIDEO)
{
var start:int = NALU.scan(b, cursor, true);
if(start == -1 && lastVideoNALU)
{
CONFIG::LOGGING
{
logger.debug("Stuff entire " + (b.length - cursor) + " bytes into previous NALU.");
}
lastVideoNALU.buffer.position = lastVideoNALU.buffer.length;
b.position = 0;
lastVideoNALU.buffer.writeBytes(b, cursor, b.length - cursor);
return true;
}
else if((start - cursor) > 0 && lastVideoNALU)
{
// Shove into previous buffer.
CONFIG::LOGGING
{
logger.debug("Stuffing first " + (start - cursor) + " bytes into previous NALU.");
}
lastVideoNALU.buffer.position = lastVideoNALU.buffer.length;
b.position = 0;
lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor);
cursor = start;
}
// If it's identical timestamps, accumulate it into the current unit and keep going.
if(lastVideoNALU && pts == lastVideoNALU.pts && dts == lastVideoNALU.dts)
{
CONFIG::LOGGING
{
logger.debug("Combining " + (start-cursor) + " bytes into previous NALU due to matching DTS/PTS.");
}
lastVideoNALU.buffer.position = lastVideoNALU.buffer.length;
b.position = 0;
lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor);
cursor = start;
}
else
{
// Submit previous data.
if(lastVideoNALU)
{
pendingBuffers.push(lastVideoNALU.clone());
}
// Update NALU state.
lastVideoNALU = new NALU();
lastVideoNALU.buffer = new ByteArray();
lastVideoNALU.pts = pts;
lastVideoNALU.dts = dts;
lastVideoNALU.type = packet.type;
lastVideoNALU.buffer.writeBytes(b, cursor);
}
}
else if(types[packet.packetID] == 0x0F)
{
// It's an AAC stream.
pendingBuffers.push(packet.clone());
}
else if(types[packet.packetID] == 0x03 || types[packet.packetID] == 0x04)
{
// It's an MP3 stream.
pendingBuffers.push(packet.clone());
}
else
{
CONFIG::LOGGING
{
logger.warn("Unknown packet ID type " + types[packet.packetID] + ", ignoring (A).");
}
}
bufferPendingNalus();
return true;
}
/**
* To avoid transcoding all content on flush, we buffer it into FLV
* tags as we go. However, they remain undelivered until we can gather
* final SPS/PPS information. This method is responsible for
* incrementally buffering in the FLV transcoder as we go.
*/
public function bufferPendingNalus():void
{
// Iterate and buffer new NALUs.
for(var i:int=pendingLastConvertedIndex; i<pendingBuffers.length; i++)
{
if(pendingBuffers[i] is NALU)
{
transcoder.convert(pendingBuffers[i] as NALU);
}
else if(pendingBuffers[i] is PESPacket)
{
var packet:PESPacket = pendingBuffers[i] as PESPacket;
if(packet.type == 0x0F)
{
// It's an AAC stream.
transcoder.convertAAC(packet);
}
else if(packet.type == 0x03 || packet.type == 0x04)
{
// It's an MP3 stream. Pass through directly.
transcoder.convertMP3(packet);
}
else
{
CONFIG::LOGGING
{
logger.warn("Unknown packet ID type " + packet.type + ", ignoring (B).");
}
}
}
}
// Note the last item we converted so we can avoid duplicating work.
pendingLastConvertedIndex = pendingBuffers.length;
}
public function processAllNalus():void
{
// Consume any unposted video NALUs.
if(lastVideoNALU)
{
pendingBuffers.push(lastVideoNALU.clone());
lastVideoNALU = null;
}
// First walk all the video NALUs and get the correct SPS/PPS
if(pendingBuffers.length == 0)
return;
// Then emit SPS/PPS
transcoder.emitSPSPPSUnbuffered();
// Complete buffering and emit it all.
bufferPendingNalus();
transcoder.emitBufferedTags();
// Don't forget to clear the pending list.
pendingBuffers.length = 0;
pendingLastConvertedIndex = 0;
}
}
}
|
package com.kaltura.hls.m2ts
{
import flash.utils.ByteArray;
import flash.net.ObjectEncoding;
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.IDataInput;
import flash.utils.IDataOutput;
import com.hurlant.util.Hex;
CONFIG::LOGGING
{
import org.osmf.logging.Logger;
import org.osmf.logging.Log;
}
/**
* Process packetized elementary streams and extract NALUs and other data.
*/
public class PESProcessor
{
CONFIG::LOGGING
{
private static const logger:Logger = Log.getLogger("com.kaltura.hls.m2ts.PESProcessor");
}
public var types:Object = {};
public var streams:Object = {};
public var lastVideoNALU:NALU = null;
public var transcoder:FLVTranscoder = new FLVTranscoder();
public var headerSent:Boolean = false;
public var pmtStreamId:int = -1;
protected var pendingBuffers:Vector.<Object> = new Vector.<Object>();
protected var pendingLastConvertedIndex:int = 0;
public var lastPTS:Number = 0, lastDTS:Number = 0;
/**
* Given a MPEG timestamp we've seen previously, determine if the new timestamp
* has wrapped and correct it to follow the old timestamp.
*/
static function handleMpegTimestampWrap(newTime:Number, oldTime:Number):Number
{
while (!isNaN(oldTime) && (Math.abs(newTime - oldTime) > 4294967296))
newTime += (oldTime < newTime) ? -8589934592 : 8589934592;
return newTime;
}
public function logStreams():void
{
CONFIG::LOGGING
{
logger.debug("----- PES state -----");
for(var k:* in streams)
{
logger.debug(" " + k + " has " + streams[k].buffer.length + " bytes, type=" + types[k]);
}
}
}
public function clear(clearAACConfig:Boolean = true):void
{
streams = {};
lastVideoNALU = null;
transcoder.clear(clearAACConfig);
// Reset PTS/DTS reference.
lastPTS = lastDTS = 0;
}
private function parseProgramAssociationTable(bytes:ByteArray, cursor:uint):Boolean
{
// Get the section length.
var sectionLen:uint = ((bytes[cursor+2] & 0x03) << 8) | bytes[cursor+3];
// Check the section length for a single PMT.
CONFIG::LOGGING
{
if (sectionLen > 13)
{
logger.debug("Saw multiple PMT entries in the PAT; blindly choosing first one.");
}
}
// Grab the PMT ID.
pmtStreamId = ((bytes[cursor+10] << 8) | bytes[cursor+11]) & 0x1FFF;
CONFIG::LOGGING
{
logger.debug("Saw PMT ID of " + pmtStreamId);
}
return true;
}
private function parseProgramMapTable(bytes:ByteArray, cursor:uint):Boolean
{
var sectionLength:uint;
var sectionLimit:uint;
var programInfoLength:uint;
var type:uint;
var pid:uint;
var esInfoLength:uint;
var seenPIDsByClass:Array;
var mediaClass:int;
var hasAudio:Boolean = false, hasVideo:Boolean = false;
// Set up types.
types = [];
seenPIDsByClass = [];
seenPIDsByClass[MediaClass.VIDEO] = Infinity;
seenPIDsByClass[MediaClass.AUDIO] = Infinity;
// Process section length and limit.
cursor++;
sectionLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1];
cursor += 2;
if(sectionLength + cursor > bytes.length)
{
CONFIG::LOGGING
{
logger.error("Not enough data to read. 1");
}
return false;
}
// Skip a few things we don't care about: program number, RSV, version, CNI, section, last_section, pcr_cid
sectionLimit = cursor + sectionLength;
cursor += 7;
// And get the program info length.
programInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1];
cursor += 2;
// If not enough data to proceed, bail.
if(programInfoLength + cursor > bytes.length)
{
CONFIG::LOGGING
{
logger.error("Not enough data to read. 2");
}
return false;
}
cursor += programInfoLength;
const CRC_SIZE:int = 4;
while(cursor < sectionLimit - CRC_SIZE)
{
type = bytes[cursor++];
pid = ((bytes[cursor] & 0x1f) << 8) + bytes[cursor + 1];
cursor += 2;
mediaClass = MediaClass.calculate(type);
if(mediaClass == MediaClass.VIDEO)
hasVideo = true
if(mediaClass == MediaClass.AUDIO)
hasAudio = true
// For video & audio, select the lowest PID for each kind.
if(mediaClass == MediaClass.OTHER
|| pid < seenPIDsByClass[mediaClass])
{
// Clear a higher PID if present.
if(mediaClass != MediaClass.OTHER
&& seenPIDsByClass[mediaClass] < Infinity)
types[seenPIDsByClass[mediaClass]] = -1;
types[pid] = type;
seenPIDsByClass[mediaClass] = pid;
}
// Skip the esInfo data.
esInfoLength = ((bytes[cursor] & 0x0f) << 8) + bytes[cursor + 1];
cursor += 2;
cursor += esInfoLength;
}
// Cook out header to transcoder.
//transcoder.writeHeader(hasAudio, hasVideo);
headerSent = true;
return true;
}
public function append(packet:PESPacket):Boolean
{
// logger.debug("saw packet of " + packet.buffer.length);
var b:ByteArray = packet.buffer;
b.position = 0;
if(b.length < 8)
{
CONFIG::LOGGING
{
logger.error("Ignoring too short PES packet, length=" + b.length);
}
return true;
}
// Get the start code.
var startCode:uint = b.readUnsignedInt();
if((startCode & 0xFFFFFF00) != 0x00000100)
{
// It could be a program association table.
if((startCode & 0xFFFFFF00) == 0x0000b000)
{
parseProgramAssociationTable(b, 1);
return true;
}
// It could be the program map table.
if((startCode & 0xFFFFFC00) == 0x0002b000)
{
parseProgramMapTable(b, 1);
return true;
}
var tmp:ByteArray = new ByteArray();
tmp.writeInt(startCode);
CONFIG::LOGGING
{
logger.error("ES prefix was wrong, expected 00:00:01:xx but got " + Hex.fromArray(tmp, true));
}
return true;
}
// Get the stream ID.
var streamID:int = startCode & 0xFF;
// Get the length.
var packetLength:uint = b.readUnsignedShort();
if(packetLength)
{
if(b.length < packetLength )
{
CONFIG::LOGGING
{
logger.warn("WARNING: parsePESPacket - not enough bytes, expecting " + packetLength + ", but have " + b.length);
}
return false; // not enough bytes in packet
}
}
if(b.length < 9)
{
CONFIG::LOGGING
{
logger.warn("WARNING: parsePESPacket - too short to read header!");
}
return false;
}
// Read the rest of the header.
var cursor:uint = 6;
var dataAlignment:Boolean = (b[cursor] & 0x04) != 0;
cursor++;
var ptsDts:uint = (b[cursor] & 0xc0) >> 6;
cursor++;
var pesHeaderDataLength:uint = b[cursor];
cursor++;
//logger.debug(" PES align=" + dataAlignment + " ptsDts=" + ptsDts + " header=" + pesHeaderDataLength);
var pts:Number = 0, dts:Number = 0;
if(ptsDts & 0x02)
{
// has PTS at least
if(cursor + 5 > b.length)
return true;
pts = b[cursor] & 0x0e;
pts *= 128;
pts += b[cursor + 1];
pts *= 256;
pts += b[cursor + 2] & 0xfe;
pts *= 128;
pts += b[cursor + 3];
pts *= 256;
pts += b[cursor + 4] & 0xfe;
pts /= 2;
if(ptsDts & 0x01)
{
// DTS too!
if(cursor + 10 > b.length)
return true;
dts = b[cursor + 5] & 0x0e;
dts *= 128;
dts += b[cursor + 6];
dts *= 256;
dts += b[cursor + 7] & 0xfe;
dts *= 128;
dts += b[cursor + 8];
dts *= 256;
dts += b[cursor + 9] & 0xfe;
dts /= 2;
}
else
{
//logger.debug("Filling in DTS")
dts = pts;
}
}
// Condition PTS and DTS.
pts = handleMpegTimestampWrap(pts, lastPTS);
lastPTS = pts;
dts = handleMpegTimestampWrap(dts, lastDTS);
lastDTS = dts;
packet.pts = pts;
packet.dts = dts;
//logger.debug(" PTS=" + pts/90000 + " DTS=" + dts/90000);
cursor += pesHeaderDataLength;
if(cursor > b.length)
{
CONFIG::LOGGING
{
logger.warn("WARNING: parsePESPacket - ran out of bytes");
}
return true;
}
if(types[packet.packetID] == undefined)
{
CONFIG::LOGGING
{
logger.warn("WARNING: parsePESPacket - unknown type");
}
return true;
}
var pes:PESPacketStream;
if(streams[packet.packetID] == undefined)
{
if(dts < 0.0)
{
CONFIG::LOGGING
{
logger.warn("WARNING: parsePESPacket - invalid decode timestamp? DTS=" + dts);
}
//return true;
}
pes = new PESPacketStream();
streams[packet.packetID] = pes;
}
else
{
pes = streams[packet.packetID];
}
if(headerSent == false)
{
CONFIG::LOGGING
{
logger.warn("Skipping data that came before PMT");
}
return true;
}
// Note the type at this moment in time.
packet.type = types[packet.packetID];
packet.headerLength = cursor;
// And process.
if(MediaClass.calculate(types[packet.packetID]) == MediaClass.VIDEO)
{
var start:int = NALU.scan(b, cursor, true);
if(start == -1 && lastVideoNALU)
{
CONFIG::LOGGING
{
logger.debug("Stuff entire " + (b.length - cursor) + " bytes into previous NALU.");
}
lastVideoNALU.buffer.position = lastVideoNALU.buffer.length;
b.position = 0;
lastVideoNALU.buffer.writeBytes(b, cursor, b.length - cursor);
return true;
}
else if((start - cursor) > 0 && lastVideoNALU)
{
// Shove into previous buffer.
CONFIG::LOGGING
{
logger.debug("Stuffing first " + (start - cursor) + " bytes into previous NALU.");
}
lastVideoNALU.buffer.position = lastVideoNALU.buffer.length;
b.position = 0;
lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor);
cursor = start;
}
// If it's identical timestamps, accumulate it into the current unit and keep going.
if(lastVideoNALU && pts == lastVideoNALU.pts && dts == lastVideoNALU.dts)
{
CONFIG::LOGGING
{
logger.debug("Combining " + (start-cursor) + " bytes into previous NALU due to matching DTS/PTS.");
}
lastVideoNALU.buffer.position = lastVideoNALU.buffer.length;
b.position = 0;
lastVideoNALU.buffer.writeBytes(b, cursor, start - cursor);
cursor = start;
}
else
{
// Submit previous data.
if(lastVideoNALU)
{
pendingBuffers.push(lastVideoNALU.clone());
}
// Update NALU state.
lastVideoNALU = new NALU();
lastVideoNALU.buffer = new ByteArray();
lastVideoNALU.pts = pts;
lastVideoNALU.dts = dts;
lastVideoNALU.type = packet.type;
lastVideoNALU.buffer.writeBytes(b, cursor);
}
}
else if(types[packet.packetID] == 0x0F)
{
// It's an AAC stream.
pendingBuffers.push(packet.clone());
}
else if(types[packet.packetID] == 0x03 || types[packet.packetID] == 0x04)
{
// It's an MP3 stream.
pendingBuffers.push(packet.clone());
}
else
{
CONFIG::LOGGING
{
logger.warn("Unknown packet ID type " + types[packet.packetID] + ", ignoring (A).");
}
}
bufferPendingNalus();
return true;
}
/**
* To avoid transcoding all content on flush, we buffer it into FLV
* tags as we go. However, they remain undelivered until we can gather
* final SPS/PPS information. This method is responsible for
* incrementally buffering in the FLV transcoder as we go.
*/
public function bufferPendingNalus():void
{
// Iterate and buffer new NALUs.
for(var i:int=pendingLastConvertedIndex; i<pendingBuffers.length; i++)
{
if(pendingBuffers[i] is NALU)
{
transcoder.convert(pendingBuffers[i] as NALU);
}
else if(pendingBuffers[i] is PESPacket)
{
var packet:PESPacket = pendingBuffers[i] as PESPacket;
if(packet.type == 0x0F)
{
// It's an AAC stream.
transcoder.convertAAC(packet);
}
else if(packet.type == 0x03 || packet.type == 0x04)
{
// It's an MP3 stream. Pass through directly.
transcoder.convertMP3(packet);
}
else
{
CONFIG::LOGGING
{
logger.warn("Unknown packet ID type " + packet.type + ", ignoring (B).");
}
}
}
}
// Note the last item we converted so we can avoid duplicating work.
pendingLastConvertedIndex = pendingBuffers.length;
}
public function processAllNalus():void
{
// Consume any unposted video NALUs.
if(lastVideoNALU)
{
pendingBuffers.push(lastVideoNALU.clone());
lastVideoNALU = null;
}
// First walk all the video NALUs and get the correct SPS/PPS
if(pendingBuffers.length == 0)
return;
// Then emit SPS/PPS
transcoder.emitSPSPPSUnbuffered();
// Complete buffering and emit it all.
bufferPendingNalus();
transcoder.emitBufferedTags();
// Don't forget to clear the pending list.
pendingBuffers.length = 0;
pendingLastConvertedIndex = 0;
}
}
}
|
Fix issue with unwrapped negative DTS dropping PES packets.
|
Fix issue with unwrapped negative DTS dropping PES packets.
|
ActionScript
|
agpl-3.0
|
kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF,kaltura/HLS-OSMF
|
b1c5db214f402fb865bbf24d1fc3c67dbc3ca449
|
src/org/mangui/hls/HLS.as
|
src/org/mangui/hls/HLS.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.model.AudioTrack;
import flash.display.Stage;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.URLStream;
import flash.events.EventDispatcher;
import flash.events.Event;
import org.mangui.hls.model.Level;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.loader.ManifestLoader;
import org.mangui.hls.controller.AudioTrackController;
import org.mangui.hls.loader.FragmentLoader;
import org.mangui.hls.stream.HLSNetStream;
import org.hola.WorkerUtils;
import org.hola.HSettings;
import flash.external.ExternalInterface;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that manages the streaming process. **/
public class HLS extends EventDispatcher {
public var _fragmentLoader : FragmentLoader;
private var _manifestLoader : ManifestLoader;
private var _audioTrackController : AudioTrackController;
/** HLS NetStream **/
private var _hlsNetStream : HLSNetStream;
/** HLS URLStream **/
private var _hlsURLStream : Class;
private var _client : Object = {};
private var _stage : Stage;
private var _url:String;
private static var hola_api_inited:Boolean;
private static var g_curr_id:Number = 0;
private static var g_curr_hls:HLS;
private static function hola_version() : Object
{
return {
flashls_version: '0.3.5',
patch_version: '1.0.7'
};
}
private static function hola_hls_get_video_url() : String {
return g_curr_hls._url;
}
private static function hola_hls_get_position() : Number {
return g_curr_hls.position;
}
private static function hola_hls_get_duration() : Number {
return g_curr_hls.duration;
}
private static function hola_hls_get_buffer_sec() : Number {
return g_curr_hls.bufferLength;
}
private static function hola_hls_call(method:String, args:Array):Object{
return g_curr_hls[method].apply(g_curr_hls, args);
}
private static function hola_hls_get_state() : String {
return g_curr_hls.playbackState;
}
private static function hola_hls_get_levels() : Object {
return g_curr_hls.levels
}
private static function hola_hls_get_level() : Number {
return g_curr_hls.level
}
/** Create and connect all components. **/
public function HLS() {
HSettings.init();
WorkerUtils.start_worker();
if (!hola_api_inited && ExternalInterface.available)
{
ExternalInterface.call('console.log', 'HLS hola_api_inited');
hola_api_inited = true;
ExternalInterface.addCallback("hola_hls_call", HLS.hola_hls_call);
ExternalInterface.addCallback("hola_version", HLS.hola_version);
ExternalInterface.addCallback("hola_hls_get_video_url", HLS.hola_hls_get_video_url);
ExternalInterface.addCallback("hola_hls_get_position", HLS.hola_hls_get_position);
ExternalInterface.addCallback("hola_hls_get_duration", HLS.hola_hls_get_duration);
ExternalInterface.addCallback("hola_hls_get_buffer_sec", HLS.hola_hls_get_buffer_sec);
ExternalInterface.addCallback("hola_hls_get_state", HLS.hola_hls_get_state);
ExternalInterface.addCallback("hola_hls_get_levels", HLS.hola_hls_get_levels);
ExternalInterface.addCallback("hola_hls_get_level", HLS.hola_hls_get_level);
}
g_curr_id++;
g_curr_hls = this;
if (ExternalInterface.available)
{
ExternalInterface.call('console.log', 'HLS new ', g_curr_id);
ExternalInterface.call('window.postMessage',
{id: 'flashls.hlsNew', hls_id: g_curr_id}, '*');
}
var connection : NetConnection = new NetConnection();
connection.connect(null);
_manifestLoader = new ManifestLoader(this);
_audioTrackController = new AudioTrackController(this);
_hlsURLStream = URLStream as Class;
// default loader
_fragmentLoader = new FragmentLoader(this, _audioTrackController);
_hlsNetStream = new HLSNetStream(connection, this, _fragmentLoader);
add_event(HLSEvent.MANIFEST_LOADING);
add_event(HLSEvent.MANIFEST_PARSED);
add_event(HLSEvent.MANIFEST_LOADED);
add_event(HLSEvent.LEVEL_LOADING);
add_event(HLSEvent.LEVEL_LOADED);
add_event(HLSEvent.LEVEL_SWITCH);
add_event(HLSEvent.LEVEL_ENDLIST);
add_event(HLSEvent.FRAGMENT_LOADING);
add_event(HLSEvent.FRAGMENT_LOADED);
add_event(HLSEvent.FRAGMENT_PLAYING);
add_event(HLSEvent.AUDIO_TRACKS_LIST_CHANGE);
add_event(HLSEvent.AUDIO_TRACK_CHANGE);
add_event(HLSEvent.TAGS_LOADED);
add_event(HLSEvent.LAST_VOD_FRAGMENT_LOADED);
add_event(HLSEvent.ERROR);
add_event(HLSEvent.MEDIA_TIME);
add_event(HLSEvent.PLAYBACK_STATE);
add_event(HLSEvent.SEEK_STATE);
add_event(HLSEvent.PLAYBACK_COMPLETE);
add_event(HLSEvent.PLAYLIST_DURATION_UPDATED);
add_event(HLSEvent.ID3_UPDATED);
};
private function add_event(name:String):void{
this.addEventListener(name, event_handler_func('flashls.'+name));
}
private function event_handler_func(name:String):Function{
return function(event:HLSEvent):void{
if (!ExternalInterface.available)
return;
ExternalInterface.call('window.postMessage',
{id: name, hls_id: g_curr_id, url: event.url,
level: event.level, duration: event.duration,
levels: event.levels, error: event.error,
loadMetrics: event.loadMetrics,
playMetrics: event.playMetrics, mediatime: event.mediatime,
state: event.state, audioTrack: event.audioTrack}, '*');
}
}
/** Forward internal errors. **/
override public function dispatchEvent(event : Event) : Boolean {
if (event.type == HLSEvent.ERROR) {
CONFIG::LOGGING {
Log.error((event as HLSEvent).error);
}
_hlsNetStream.close();
}
return super.dispatchEvent(event);
};
public function dispose() : void {
if (ExternalInterface.available)
{
ExternalInterface.call('window.postMessage',
{id: 'flashls.hlsDispose', hls_id: g_curr_id}, '*');
}
_fragmentLoader.dispose();
_manifestLoader.dispose();
_audioTrackController.dispose();
_hlsNetStream.dispose_();
_fragmentLoader = null;
_manifestLoader = null;
_audioTrackController = null;
_hlsNetStream = null;
_client = null;
_stage = null;
_hlsNetStream = null;
}
/** Return the quality level used when starting a fresh playback **/
public function get startlevel() : int {
return _manifestLoader.startlevel;
};
/** Return the quality level used after a seek operation **/
public function get seeklevel() : int {
return _manifestLoader.seeklevel;
};
/** Return the quality level of the currently played fragment **/
public function get playbacklevel() : int {
return _hlsNetStream.playbackLevel;
};
/** Return the quality level of last loaded fragment **/
public function get level() : int {
return _fragmentLoader.level;
};
/* set quality level for next loaded fragment (-1 for automatic level selection) */
public function set level(level : int) : void {
_fragmentLoader.level = level;
};
/* check if we are in automatic level selection mode */
public function get autolevel() : Boolean {
return _fragmentLoader.autolevel;
};
/** Return a Vector of quality level **/
public function get levels() : Vector.<Level> {
return _manifestLoader.levels;
};
/** Return the current playback position. **/
public function get position() : Number {
return _hlsNetStream.position;
};
public function get video_url() : String {
return _url;
};
public function get duration() : Number {
return _hlsNetStream.duration;
};
/** Return the current playback state. **/
public function get playbackState() : String {
return _hlsNetStream.playbackState;
};
/** Return the current seek state. **/
public function get seekState() : String {
return _hlsNetStream.seekState;
};
/** Return the type of stream (VOD/LIVE). **/
public function get type() : String {
return _manifestLoader.type;
};
/** Load and parse a new HLS URL **/
public function load(url : String) : void {
_hlsNetStream.close();
_url = url;
_manifestLoader.load(url);
};
/** return HLS NetStream **/
public function get stream() : NetStream {
return _hlsNetStream;
}
public function get client() : Object {
return _client;
}
public function set client(value : Object) : void {
_client = value;
}
/** get current Buffer Length **/
public function get bufferLength() : Number {
return _hlsNetStream.bufferLength;
};
/** get audio tracks list**/
public function get audioTracks() : Vector.<AudioTrack> {
return _audioTrackController.audioTracks;
};
/** get alternate audio tracks list from playlist **/
public function get altAudioTracks() : Vector.<AltAudioTrack> {
return _manifestLoader.altAudioTracks;
};
/** get index of the selected audio track (index in audio track lists) **/
public function get audioTrack() : int {
return _audioTrackController.audioTrack;
};
/** select an audio track, based on its index in audio track lists**/
public function set audioTrack(val : int) : void {
_audioTrackController.audioTrack = val;
}
/* set stage */
public function set stage(stage : Stage) : void {
_stage = stage;
}
/* get stage */
public function get stage() : Stage {
return _stage;
}
/* set URL stream loader */
public function set URLstream(urlstream : Class) : void {
_hlsURLStream = urlstream;
}
/* retrieve URL stream loader */
public function get URLstream() : Class {
return _hlsURLStream;
}
};
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.hls {
import org.mangui.hls.model.AudioTrack;
import flash.display.Stage;
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.net.URLStream;
import flash.events.EventDispatcher;
import flash.events.Event;
import org.mangui.hls.model.Level;
import org.mangui.hls.event.HLSEvent;
import org.mangui.hls.playlist.AltAudioTrack;
import org.mangui.hls.loader.ManifestLoader;
import org.mangui.hls.controller.AudioTrackController;
import org.mangui.hls.loader.FragmentLoader;
import org.mangui.hls.stream.HLSNetStream;
import org.hola.WorkerUtils;
import org.hola.HSettings;
import flash.external.ExternalInterface;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
/** Class that manages the streaming process. **/
public class HLS extends EventDispatcher {
public var _fragmentLoader : FragmentLoader;
private var _manifestLoader : ManifestLoader;
private var _audioTrackController : AudioTrackController;
/** HLS NetStream **/
private var _hlsNetStream : HLSNetStream;
/** HLS URLStream **/
private var _hlsURLStream : Class;
private var _client : Object = {};
private var _stage : Stage;
private var _url:String;
private static var hola_api_inited:Boolean;
private static var g_curr_id:Number = 0;
private static var g_curr_hls:HLS;
private static function hola_version() : Object
{
return {
flashls_version: '0.3.5',
patch_version: '1.0.7',
have_worker: CONFIG::HAVE_WORKER
};
}
private static function hola_hls_get_video_url() : String {
return g_curr_hls._url;
}
private static function hola_hls_get_position() : Number {
return g_curr_hls.position;
}
private static function hola_hls_get_duration() : Number {
return g_curr_hls.duration;
}
private static function hola_hls_get_buffer_sec() : Number {
return g_curr_hls.bufferLength;
}
private static function hola_hls_call(method:String, args:Array):Object{
return g_curr_hls[method].apply(g_curr_hls, args);
}
private static function hola_hls_get_state() : String {
return g_curr_hls.playbackState;
}
private static function hola_hls_get_levels() : Object {
return g_curr_hls.levels
}
private static function hola_hls_get_level() : Number {
return g_curr_hls.level
}
/** Create and connect all components. **/
public function HLS() {
HSettings.init();
WorkerUtils.start_worker();
if (!hola_api_inited && ExternalInterface.available)
{
ExternalInterface.call('console.log', 'HLS hola_api_inited');
hola_api_inited = true;
ExternalInterface.addCallback("hola_hls_call", HLS.hola_hls_call);
ExternalInterface.addCallback("hola_version", HLS.hola_version);
ExternalInterface.addCallback("hola_hls_get_video_url", HLS.hola_hls_get_video_url);
ExternalInterface.addCallback("hola_hls_get_position", HLS.hola_hls_get_position);
ExternalInterface.addCallback("hola_hls_get_duration", HLS.hola_hls_get_duration);
ExternalInterface.addCallback("hola_hls_get_buffer_sec", HLS.hola_hls_get_buffer_sec);
ExternalInterface.addCallback("hola_hls_get_state", HLS.hola_hls_get_state);
ExternalInterface.addCallback("hola_hls_get_levels", HLS.hola_hls_get_levels);
ExternalInterface.addCallback("hola_hls_get_level", HLS.hola_hls_get_level);
}
g_curr_id++;
g_curr_hls = this;
if (ExternalInterface.available)
{
ExternalInterface.call('console.log', 'HLS new ', g_curr_id);
ExternalInterface.call('window.postMessage',
{id: 'flashls.hlsNew', hls_id: g_curr_id}, '*');
}
var connection : NetConnection = new NetConnection();
connection.connect(null);
_manifestLoader = new ManifestLoader(this);
_audioTrackController = new AudioTrackController(this);
_hlsURLStream = URLStream as Class;
// default loader
_fragmentLoader = new FragmentLoader(this, _audioTrackController);
_hlsNetStream = new HLSNetStream(connection, this, _fragmentLoader);
add_event(HLSEvent.MANIFEST_LOADING);
add_event(HLSEvent.MANIFEST_PARSED);
add_event(HLSEvent.MANIFEST_LOADED);
add_event(HLSEvent.LEVEL_LOADING);
add_event(HLSEvent.LEVEL_LOADED);
add_event(HLSEvent.LEVEL_SWITCH);
add_event(HLSEvent.LEVEL_ENDLIST);
add_event(HLSEvent.FRAGMENT_LOADING);
add_event(HLSEvent.FRAGMENT_LOADED);
add_event(HLSEvent.FRAGMENT_PLAYING);
add_event(HLSEvent.AUDIO_TRACKS_LIST_CHANGE);
add_event(HLSEvent.AUDIO_TRACK_CHANGE);
add_event(HLSEvent.TAGS_LOADED);
add_event(HLSEvent.LAST_VOD_FRAGMENT_LOADED);
add_event(HLSEvent.ERROR);
add_event(HLSEvent.MEDIA_TIME);
add_event(HLSEvent.PLAYBACK_STATE);
add_event(HLSEvent.SEEK_STATE);
add_event(HLSEvent.PLAYBACK_COMPLETE);
add_event(HLSEvent.PLAYLIST_DURATION_UPDATED);
add_event(HLSEvent.ID3_UPDATED);
};
private function add_event(name:String):void{
this.addEventListener(name, event_handler_func('flashls.'+name));
}
private function event_handler_func(name:String):Function{
return function(event:HLSEvent):void{
if (!ExternalInterface.available)
return;
ExternalInterface.call('window.postMessage',
{id: name, hls_id: g_curr_id, url: event.url,
level: event.level, duration: event.duration,
levels: event.levels, error: event.error,
loadMetrics: event.loadMetrics,
playMetrics: event.playMetrics, mediatime: event.mediatime,
state: event.state, audioTrack: event.audioTrack}, '*');
}
}
/** Forward internal errors. **/
override public function dispatchEvent(event : Event) : Boolean {
if (event.type == HLSEvent.ERROR) {
CONFIG::LOGGING {
Log.error((event as HLSEvent).error);
}
_hlsNetStream.close();
}
return super.dispatchEvent(event);
};
public function dispose() : void {
if (ExternalInterface.available)
{
ExternalInterface.call('window.postMessage',
{id: 'flashls.hlsDispose', hls_id: g_curr_id}, '*');
}
_fragmentLoader.dispose();
_manifestLoader.dispose();
_audioTrackController.dispose();
_hlsNetStream.dispose_();
_fragmentLoader = null;
_manifestLoader = null;
_audioTrackController = null;
_hlsNetStream = null;
_client = null;
_stage = null;
_hlsNetStream = null;
}
/** Return the quality level used when starting a fresh playback **/
public function get startlevel() : int {
return _manifestLoader.startlevel;
};
/** Return the quality level used after a seek operation **/
public function get seeklevel() : int {
return _manifestLoader.seeklevel;
};
/** Return the quality level of the currently played fragment **/
public function get playbacklevel() : int {
return _hlsNetStream.playbackLevel;
};
/** Return the quality level of last loaded fragment **/
public function get level() : int {
return _fragmentLoader.level;
};
/* set quality level for next loaded fragment (-1 for automatic level selection) */
public function set level(level : int) : void {
_fragmentLoader.level = level;
};
/* check if we are in automatic level selection mode */
public function get autolevel() : Boolean {
return _fragmentLoader.autolevel;
};
/** Return a Vector of quality level **/
public function get levels() : Vector.<Level> {
return _manifestLoader.levels;
};
/** Return the current playback position. **/
public function get position() : Number {
return _hlsNetStream.position;
};
public function get video_url() : String {
return _url;
};
public function get duration() : Number {
return _hlsNetStream.duration;
};
/** Return the current playback state. **/
public function get playbackState() : String {
return _hlsNetStream.playbackState;
};
/** Return the current seek state. **/
public function get seekState() : String {
return _hlsNetStream.seekState;
};
/** Return the type of stream (VOD/LIVE). **/
public function get type() : String {
return _manifestLoader.type;
};
/** Load and parse a new HLS URL **/
public function load(url : String) : void {
_hlsNetStream.close();
_url = url;
_manifestLoader.load(url);
};
/** return HLS NetStream **/
public function get stream() : NetStream {
return _hlsNetStream;
}
public function get client() : Object {
return _client;
}
public function set client(value : Object) : void {
_client = value;
}
/** get current Buffer Length **/
public function get bufferLength() : Number {
return _hlsNetStream.bufferLength;
};
/** get audio tracks list**/
public function get audioTracks() : Vector.<AudioTrack> {
return _audioTrackController.audioTracks;
};
/** get alternate audio tracks list from playlist **/
public function get altAudioTracks() : Vector.<AltAudioTrack> {
return _manifestLoader.altAudioTracks;
};
/** get index of the selected audio track (index in audio track lists) **/
public function get audioTrack() : int {
return _audioTrackController.audioTrack;
};
/** select an audio track, based on its index in audio track lists**/
public function set audioTrack(val : int) : void {
_audioTrackController.audioTrack = val;
}
/* set stage */
public function set stage(stage : Stage) : void {
_stage = stage;
}
/* get stage */
public function get stage() : Stage {
return _stage;
}
/* set URL stream loader */
public function set URLstream(urlstream : Class) : void {
_hlsURLStream = urlstream;
}
/* retrieve URL stream loader */
public function get URLstream() : Class {
return _hlsURLStream;
}
};
}
|
return CONFIG::HAVE_WORKER in hola_version()
|
return CONFIG::HAVE_WORKER in hola_version()
|
ActionScript
|
mpl-2.0
|
hola/flashls,hola/flashls
|
515c8f934899b68a814d2505491f014e4be70151
|
WEB-INF/lps/lfc/services/LzModeManager.as
|
WEB-INF/lps/lfc/services/LzModeManager.as
|
/******************************************************************************
* LzModeManager.as
*****************************************************************************/
//* A_LZ_COPYRIGHT_BEGIN ******************************************************
//* Copyright 2001-2004 Laszlo Systems, Inc. All Rights Reserved. *
//* Use is subject to license terms. *
//* A_LZ_COPYRIGHT_END ********************************************************
//=============================================================================
// DEFINE OBJECT: LzModeManager
// Manages the modal states of views and also notifies views ( that have
// registered with it ) when their focus has changed.
//=============================================================================
LzModeManager = new Object();
//@event onmode: Sent when the mode changes.
LzModeManager.onmode = null;
LzModeManager.modeArray = new Array();
LzModeManager.clickStream = new Array();
LzModeManager.clstDel = new LzDelegate( LzModeManager , "checkClickStream" );
LzModeManager.clstDict ={ onmouseup : 1 , onmousedown: 2 };
LzModeManager.toString = function (){
return "mode manager";
}
//=============================================================================
// The global mouse service sends onmouse*** and onclick events when the mouse
// rollover or button state changes. The argument sent with the events is the
// view that was clicked. If no view was clicked, the argument is null.
//=============================================================================
LzGlobalMouse = new Object;
//------------------------------------------------------------------------------
// @keywords private
//------------------------------------------------------------------------------
/*
LzGlobalMouse.fakemethod = function (){
//@field onmouseup: Event sent by the LzGlobalMouse when a mouseup is
//trapped that did not originate from a clickable view.
//@field onmousedown: Event sent by the LzGlobalMouse when a mousedown is
//trapped that did not originate from a clickable view.
}
*/
//-----------------------------------------------------------------------------
// Pushes the view onto the stack of modal views
// @param LzView view: The view intending to have modal iteraction
//-----------------------------------------------------------------------------
LzModeManager.makeModal = function ( view ) {
this.modeArray.push( view );
this.onmode.sendEvent( view );
if ( ! _root.LzFocus.getFocus().childOf( view ) ){
_root.LzFocus.clearFocus();
}
}
//-----------------------------------------------------------------------------
// Removes the view (and all the views below it) from the stack of modal views
// @param LzView view: The view to be released of modal interaction
//-----------------------------------------------------------------------------
LzModeManager.release = function ( view ) {
//releases all views past this one in the modelist as well
for ( var i = this.modeArray.length-1 ; i >=0 ; i-- ){
if ( this.modeArray[ i ] == view ){
this.modeArray.splice( i , this.modeArray.length - i );
var newmode = this.modeArray[ i - 1 ];
this.onmode.sendEvent( newmode || null );
if ( newmode && ! _root.LzFocus.getFocus().childOf( newmode ) ){
_root.LzFocus.clearFocus();
}
return;
}
}
}
//-----------------------------------------------------------------------------
// Clears all modal views from the stack
//-----------------------------------------------------------------------------
LzModeManager.releaseAll = function ( ) {
// reset array to remove all views
this.modeArray = new Array();
this.onmode.sendEvent( null );
}
//------------------------------------------------------------------------------
// Called by clickable movieclip
// @keywords private
//------------------------------------------------------------------------------
LzModeManager.handleMouseButton = function ( view , eventStr){
this.clickStream.push( this.clstDict[ eventStr ] + 2);
this.handleMouseEvent( view , eventStr );
this.callNext();
}
//-----------------------------------------------------------------------------
// Check to see if the current event should be passed to its intended view
// @keywords private
//
// @param LzView view: the view that received the event
// @param String eventStr: the event string
//-----------------------------------------------------------------------------
LzModeManager.handleMouseEvent= function ( view, eventStr ) {
//_root.Debug.warn(view + ', ' + eventStr);
if (eventStr == "onmouseup") _root.LzTrack.__LZmouseup();
_root.LzGlobalMouse[ eventStr ].sendEvent( view );
if ( this.eventsLocked == true ){
return;
}
var dosend = true;
var isinputtext = false;
if (view == null ) { // check if the mouse event is in a inputtext
var ss = Selection.getFocus();
if ( ss != null ){
var focusview = eval( ss.substring( 0 , ss.lastIndexOf( '.' ) )
+ ".view");
if ( focusview ) view = focusview;
}
}
var i = this.modeArray.length-1;
while( dosend && i >= 0 ){
var mView = this.modeArray[ i-- ];
// exclude the debugger from the mode
if ($debug) {
if (view.childOf(_root.Debug))
break;
}
if (view.childOf( mView ) ){
break;
} else {
dosend = mView.passModeEvent( eventStr , view );
}
}
if ( dosend ){
//check for double-click
if ( eventStr == "onclick" ){
if ( this.__LZlastclick == view &&
view.ondblclick && !view.ondblclick.hasNoDelegates &&
(getTimer() - this.__LZlastClickTime)< view.DOUBLE_CLICK_TIME ){
//this is a double-click
eventStr = "ondblclick";
this.__LZlastclick = null;
} else {
this.__LZlastclick = view;
this.__LZlastClickTime = getTimer();
}
}
view[ eventStr ].sendEvent( view );
if ( eventStr == "onmousedown" ){
_root.LzFocus.__LZcheckFocusChange( view );
}
}
//this on matters for onmouseup and onmousedown, but it's easier to just
//set it regardless
this[ "haveGlobal" + eventStr ] = false;
}
//-----------------------------------------------------------------------------
// return true if the given view is allowed to receive the focus
// any view that is a child of the view that has the mode may be focused
// other views may not
// @keywords private
//-----------------------------------------------------------------------------
LzModeManager.__LZallowFocus= function ( view ) {
var len = this.modeArray.length;
return len == 0 || view.childOf ( this.modeArray[len-1] );
}
//-----------------------------------------------------------------------------
// Called when any mousedown or mouseup event is received by canvas to try and
// match up mouse events with non-clickable view. Not reliable - could happen
// after any number of frames.
//
// A Timer is then activated to call
// the cleanup method in the next frame
//
// @keywords private
//-----------------------------------------------------------------------------
LzModeManager.rawMouseEvent = function ( eName ) {
//_root.Debug.warn("rawmouseevent %w", eName);
//assume this happens before handleMouseEvent though order is
//not guaranteed
this.clickStream.push( this.clstDict[ eName ] );
//call the cleanup delegate
this.callNext();
}
LzModeManager.WAIT_FOR_CLICK = 4;
//-----------------------------------------------------------------------------
// Cleanup method for raw mouseup
//
// @keywords private
//-----------------------------------------------------------------------------
LzModeManager.checkClickStream = function (){
this.willCall = false;
//clickstream that looks like this
//1 , 3 , 2, 0 , ....
//raw mup , view mup , raw down , frame -- ok to check next for pair
//but then stop.
var i = 0;
var cl = this.clickStream;
var cllen = this.clickStream.length;
while( i < cllen -1 ){
if ( !( cl[i] == 1 || cl[i]==2 )){
//if we encounter a button mouse event here, it means we sent
//a global mouse event too soon
if ( cl[i] != 0 ) {
_root.Debug.write( "WARNING: Sent extra global mouse event" );
}
//advance pointer
i++;
continue;
}
var nextp = i + 1;
var maxnext = this.WAIT_FOR_CLICK + i;
while ( cl[ nextp ] == 0 && nextp < maxnext ){
nextp++;
}
if ( nextp >= cllen ){
//it's not here, so wait till next frame
break;
}
if ( cl[ i ] == cl[ nextp ] - 2 ){
//this is a pair -- simple case. just advance pointer
i = nextp+1;
} else {
//this is unpaired
if ( cl[i] == 1 ){
var me= "onmouseup";
}else{
var me="onmousedown";
}
this.handleMouseEvent( null , me );
i++;
}
}
while( cl[ i ] == 0 ){ i++; }
cl.splice( 0 , i ); //remove up to i
if ( cl.length > 0 ){
this.clickStream.push( 0 );
this.callNext();
}
}
//------------------------------------------------------------------------------
// @keywords private
//------------------------------------------------------------------------------
LzModeManager.callNext = function (){
if ( !this.willCall ){
this.willCall = true;
_root.LzIdle.callOnIdle( this.clstDel );
}
}
//-----------------------------------------------------------------------------
// Prevents all mouse events from firing.
//
//-----------------------------------------------------------------------------
LzModeManager.globalLockMouseEvents = function (){
this.eventsLocked = true;
}
//-----------------------------------------------------------------------------
// Restore normal mouse event firing.
//
//-----------------------------------------------------------------------------
LzModeManager.globalUnlockMouseEvents = function (){
this.eventsLocked = false;
}
//-----------------------------------------------------------------------------
// Tests whether the given view is in the modelist.
// @param LzView view: The mode to be tested to see if it is in the modelist
// @return Boolean: true if the view is in the modelist
//
//-----------------------------------------------------------------------------
LzModeManager.hasMode = function ( view ){
for ( var i = this.modeArray.length -1 ; i >= 0; i-- ){
if ( view == this.modeArray[ i ] ){
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
LzModeManager.getModalView = function ( ){
return this.modeArray[ this.modeArray.length - 1] || null;
}
|
/******************************************************************************
* LzModeManager.as
*****************************************************************************/
//* A_LZ_COPYRIGHT_BEGIN ******************************************************
//* Copyright 2001-2007 Laszlo Systems, Inc. All Rights Reserved. *
//* Use is subject to license terms. *
//* A_LZ_COPYRIGHT_END ********************************************************
//=============================================================================
// DEFINE OBJECT: LzModeManager
// Manages the modal states of views and also notifies views ( that have
// registered with it ) when their focus has changed.
//=============================================================================
LzModeManager = new Object();
//@event onmode: Sent when the mode changes.
LzModeManager.onmode = null;
LzModeManager.modeArray = new Array();
LzModeManager.clickStream = new Array();
LzModeManager.clstDel = new LzDelegate( LzModeManager , "checkClickStream" );
LzModeManager.clstDict ={ onmouseup : 1 , onmousedown: 2 };
LzModeManager.toString = function (){
return "mode manager";
}
//=============================================================================
// The global mouse service sends onmouse*** and onclick events when the mouse
// rollover or button state changes. The argument sent with the events is the
// view that was clicked. If no view was clicked, the argument is null.
//=============================================================================
LzGlobalMouse = new Object;
//------------------------------------------------------------------------------
// @keywords private
//------------------------------------------------------------------------------
/*
LzGlobalMouse.fakemethod = function (){
//@field onmouseup: Event sent by the LzGlobalMouse when a mouseup is
//trapped that did not originate from a clickable view.
//@field onmousedown: Event sent by the LzGlobalMouse when a mousedown is
//trapped that did not originate from a clickable view.
}
*/
//-----------------------------------------------------------------------------
// Pushes the view onto the stack of modal views
// @param LzView view: The view intending to have modal iteraction
//-----------------------------------------------------------------------------
LzModeManager.makeModal = function ( view ) {
this.modeArray.push( view );
this.onmode.sendEvent( view );
if ( ! _root.LzFocus.getFocus().childOf( view ) ){
_root.LzFocus.clearFocus();
}
}
//-----------------------------------------------------------------------------
// Removes the view (and all the views below it) from the stack of modal views
// @param LzView view: The view to be released of modal interaction
//-----------------------------------------------------------------------------
LzModeManager.release = function ( view ) {
//releases all views past this one in the modelist as well
for ( var i = this.modeArray.length-1 ; i >=0 ; i-- ){
if ( this.modeArray[ i ] == view ){
this.modeArray.splice( i , this.modeArray.length - i );
var newmode = this.modeArray[ i - 1 ];
this.onmode.sendEvent( newmode || null );
if ( newmode && ! _root.LzFocus.getFocus().childOf( newmode ) ){
_root.LzFocus.clearFocus();
}
return;
}
}
}
//-----------------------------------------------------------------------------
// Clears all modal views from the stack
//-----------------------------------------------------------------------------
LzModeManager.releaseAll = function ( ) {
// reset array to remove all views
this.modeArray = new Array();
this.onmode.sendEvent( null );
}
//------------------------------------------------------------------------------
// Called by clickable movieclip
// @keywords private
//------------------------------------------------------------------------------
LzModeManager.handleMouseButton = function ( view , eventStr){
this.clickStream.push( this.clstDict[ eventStr ] + 2);
this.handleMouseEvent( view , eventStr );
this.callNext();
}
//-----------------------------------------------------------------------------
// Check to see if the current event should be passed to its intended view
// @keywords private
//
// @param LzView view: the view that received the event
// @param String eventStr: the event string
//-----------------------------------------------------------------------------
LzModeManager.handleMouseEvent= function ( view, eventStr ) {
//_root.Debug.warn("%w, %w", view , eventStr);
if (eventStr == "onmouseup") _root.LzTrack.__LZmouseup();
var dosend = true;
var isinputtext = false;
if (view == null ) { // check if the mouse event is in a inputtext
var ss = Selection.getFocus();
if ( ss != null ){
var focusview = eval(ss + '.__lzview');
//_root.Debug.warn("Selection.getFocus: %w, %w, %w", focusview, ss);
if ( focusview != undefined ) {
view = focusview;
}
}
}
_root.LzGlobalMouse[ eventStr ].sendEvent( view );
if ( this.eventsLocked == true ){
return;
}
var i = this.modeArray.length-1;
while( dosend && i >= 0 ){
var mView = this.modeArray[ i-- ];
// exclude the debugger from the mode
if ($debug) {
if (view.childOf(_root.Debug))
break;
}
if (view.childOf( mView ) ){
break;
} else {
dosend = mView.passModeEvent( eventStr , view );
}
}
if ( dosend ){
//check for double-click
if ( eventStr == "onclick" ){
if ( this.__LZlastclick == view &&
view.ondblclick && !view.ondblclick.hasNoDelegates &&
(getTimer() - this.__LZlastClickTime)< view.DOUBLE_CLICK_TIME ){
//this is a double-click
eventStr = "ondblclick";
this.__LZlastclick = null;
} else {
this.__LZlastclick = view;
this.__LZlastClickTime = getTimer();
}
}
//_root.Debug.warn("sending %w, %w", view , eventStr);
view[ eventStr ].sendEvent( view );
if ( eventStr == "onmousedown" ){
_root.LzFocus.__LZcheckFocusChange( view );
}
}
//this on matters for onmouseup and onmousedown, but it's easier to just
//set it regardless
this[ "haveGlobal" + eventStr ] = false;
}
//-----------------------------------------------------------------------------
// return true if the given view is allowed to receive the focus
// any view that is a child of the view that has the mode may be focused
// other views may not
// @keywords private
//-----------------------------------------------------------------------------
LzModeManager.__LZallowFocus= function ( view ) {
var len = this.modeArray.length;
return len == 0 || view.childOf ( this.modeArray[len-1] );
}
//-----------------------------------------------------------------------------
// Called when any mousedown or mouseup event is received by canvas to try and
// match up mouse events with non-clickable view. Not reliable - could happen
// after any number of frames.
//
// A Timer is then activated to call
// the cleanup method in the next frame
//
// @keywords private
//-----------------------------------------------------------------------------
LzModeManager.rawMouseEvent = function ( eName ) {
//_root.Debug.warn("rawmouseevent %w", eName);
//assume this happens before handleMouseEvent though order is
//not guaranteed
this.clickStream.push( this.clstDict[ eName ] );
//call the cleanup delegate
this.callNext();
}
LzModeManager.WAIT_FOR_CLICK = 4;
//-----------------------------------------------------------------------------
// Cleanup method for raw mouseup
//
// @keywords private
//-----------------------------------------------------------------------------
LzModeManager.checkClickStream = function (){
this.willCall = false;
//clickstream that looks like this
//1 , 3 , 2, 0 , ....
//raw mup , view mup , raw down , frame -- ok to check next for pair
//but then stop.
var i = 0;
var cl = this.clickStream;
var cllen = this.clickStream.length;
while( i < cllen -1 ){
if ( !( cl[i] == 1 || cl[i]==2 )){
//if we encounter a button mouse event here, it means we sent
//a global mouse event too soon
if ( cl[i] != 0 ) {
_root.Debug.write( "WARNING: Sent extra global mouse event" );
}
//advance pointer
i++;
continue;
}
var nextp = i + 1;
var maxnext = this.WAIT_FOR_CLICK + i;
while ( cl[ nextp ] == 0 && nextp < maxnext ){
nextp++;
}
if ( nextp >= cllen ){
//it's not here, so wait till next frame
break;
}
if ( cl[ i ] == cl[ nextp ] - 2 ){
//this is a pair -- simple case. just advance pointer
i = nextp+1;
} else {
//this is unpaired
if ( cl[i] == 1 ){
var me= "onmouseup";
}else{
var me="onmousedown";
}
this.handleMouseEvent( null , me );
i++;
}
}
while( cl[ i ] == 0 ){ i++; }
cl.splice( 0 , i ); //remove up to i
if ( cl.length > 0 ){
this.clickStream.push( 0 );
this.callNext();
}
}
//------------------------------------------------------------------------------
// @keywords private
//------------------------------------------------------------------------------
LzModeManager.callNext = function (){
if ( !this.willCall ){
this.willCall = true;
_root.LzIdle.callOnIdle( this.clstDel );
}
}
//-----------------------------------------------------------------------------
// Prevents all mouse events from firing.
//
//-----------------------------------------------------------------------------
LzModeManager.globalLockMouseEvents = function (){
this.eventsLocked = true;
}
//-----------------------------------------------------------------------------
// Restore normal mouse event firing.
//
//-----------------------------------------------------------------------------
LzModeManager.globalUnlockMouseEvents = function (){
this.eventsLocked = false;
}
//-----------------------------------------------------------------------------
// Tests whether the given view is in the modelist.
// @param LzView view: The mode to be tested to see if it is in the modelist
// @return Boolean: true if the view is in the modelist
//
//-----------------------------------------------------------------------------
LzModeManager.hasMode = function ( view ){
for ( var i = this.modeArray.length -1 ; i >= 0; i-- ){
if ( view == this.modeArray[ i ] ){
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// @keywords private
//-----------------------------------------------------------------------------
LzModeManager.getModalView = function ( ){
return this.modeArray[ this.modeArray.length - 1] || null;
}
|
Change 20070323-sallen-0 by sallen@sallen-new on 2007-03-23 13:08:03 PDT in /cygdrive/c/laszlo/svn/openlaszlo/trunk for http://svn.openlaszlo.org/openlaszlo/trunk
|
Change 20070323-sallen-0 by sallen@sallen-new on 2007-03-23 13:08:03 PDT
in /cygdrive/c/laszlo/svn/openlaszlo/trunk
for http://svn.openlaszlo.org/openlaszlo/trunk
Summary: missed from last change (sorry about that)
Bugs Fixed: LPP-3753 (goes with change 4468)
Technical Reviewer: [email protected]
QA Reviewer: (pending)
Doc Reviewer: (pending)
Documentation:
Release Notes:
Details: sorry, I'm still getting the hang of svn
Tests:
git-svn-id: d62bde4b5aa582fdf07c8d403e53e0399a7ed285@4472 fa20e4f9-1d0a-0410-b5f3-dc9c16b8b17c
|
ActionScript
|
epl-1.0
|
mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo,mcarlson/openlaszlo
|
0309aacbf61955e14c2376c6f600622e238458aa
|
src/com/rails2u/debug/ExportJS.as
|
src/com/rails2u/debug/ExportJS.as
|
package com.rails2u.debug {
import flash.errors.IllegalOperationError;
import flash.external.ExternalInterface;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class ExportJS {
private static var inited:Boolean = false;
public static var objects:Object = {};
public static function init():void {
if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
if (inited) return;
ExternalInterface.addCallback('updateProperty', updateProperty);
ExternalInterface.addCallback('callMethod', callMethod);
ExternalInterface.addCallback('reloadObject', reloadObject);
inited = true;
}
public static function updateProperty(jsName:String, chainProperties:Array, value:Object):void {
var obj:Object = objects[jsName];
while (chainProperties.length > 1) {
var prop:String = chainProperties.shift();
obj = obj[prop];
}
obj[chainProperties.shift()] = value;
}
public static function callMethod(jsName:String, chainProperties:Array, args:Object):void {
var obj:Object = objects[jsName];
while (chainProperties.length > 1) {
var prop:String = chainProperties.shift();
obj = obj[prop];
}
var func:Function = obj[chainProperties.shift()] as Function;
if (func is Function) func.apply(obj, args);
}
public static function reloadObject(jsName:String) {
export(objects[jsName], jsName);
}
private static var cNum:uint = 0;
private static function nonameCounter():uint {
return cNum++;
}
public static function export(targetObject:*, jsName:String = undefined):String {
init();
if (!jsName) jsName = '__swf__' + nonameCounter();
var b:ByteArray = new ByteArray();
b.writeObject(targetObject);
b.position = 0;
var obj:Object = b.readObject();
// custom for Sprite/Shape
if (!obj.hasOwnProperty('graphics') && targetObject.hasOwnProperty('graphics'))
obj.graphics = {};
objects[jsName] = targetObject;
ExternalInterface.call(<><![CDATA[
(function(target, objectID, jsName, klassName) {
var swfObject = document.getElementsByName(objectID)[0];
var defineAttr = function(obj, parentProperties) {
var tmp = {};
for (var i in obj) {
if (obj[i] && (typeof(obj[i]) == "object" || typeof(obj[i]) == "array")) {
var pp = parentProperties.slice();
pp.push(i);
defineAttr(obj[i], pp);
continue;
}
tmp[i] = obj[i];
obj.__defineGetter__(i,
(function(attrName) {
return function() {
return this.__tmpProperties__[attrName]
}
})(i)
);
obj.__defineSetter__(i,
(function(attrName) {
return function(val) {
swfObject.updateProperty(jsName, [].concat(parentProperties).concat(attrName), val);
return this.__tmpProperties__[attrName] = val;
}
})(i)
);
}
obj.__noSuchMethod__ = function(attrName, args) {
swfObject.callMethod(jsName, [].concat(parentProperties).concat(attrName), args);
}
obj.__tmpProperties__ = tmp;
}
defineAttr(target, []);
target.__reload = function() { return swfObject.reloadObject(jsName) };
target.toString = function() { return klassName };
window[jsName] = target;
;})
]]></>.toString(), obj, ExternalInterface.objectID, jsName, getQualifiedClassName(targetObject));
return jsName;
}
}
}
|
package com.rails2u.debug {
import flash.errors.IllegalOperationError;
import flash.external.ExternalInterface;
import flash.utils.ByteArray;
import flash.utils.getQualifiedClassName;
public class ExportJS {
private static var inited:Boolean = false;
public static var objects:Object = {};
public static function init():void {
if (!ExternalInterface.available) throw (new IllegalOperationError('ExternalInterface.available should be true.'));
if (inited) return;
ExternalInterface.addCallback('updateProperty', updateProperty);
ExternalInterface.addCallback('callMethod', callMethod);
ExternalInterface.addCallback('reloadObject', reloadObject);
inited = true;
}
public static function updateProperty(jsName:String, chainProperties:Array, value:Object):Boolean {
var obj:Object = objects[jsName];
while (chainProperties.length > 1) {
var prop:String = chainProperties.shift();
obj = obj[prop];
}
try {
obj[chainProperties.shift()] = value;
} catch(e:Error) {
ExternalInterface.call('console.error', e.message);
return false;
}
return true;
}
public static function callMethod(jsName:String, chainProperties:Array, args:Object):* {
var obj:Object = objects[jsName];
while (chainProperties.length > 1) {
var prop:String = chainProperties.shift();
obj = obj[prop];
}
var func:Function = obj[chainProperties.shift()] as Function;
try {
if (func is Function) return func.apply(obj, args);
} catch(e:Error) {
ExternalInterface.call('console.error', e.message);
}
}
public static function reloadObject(jsName:String) {
export(objects[jsName], jsName);
ExternalInterface.call('console.info', 'reloaded: ' + jsName);
}
private static var cNum:uint = 0;
private static function nonameCounter():uint {
return cNum++;
}
public static function export(targetObject:*, jsName:String = undefined):String {
init();
if (!jsName) jsName = '__swf__' + nonameCounter();
var b:ByteArray = new ByteArray();
b.writeObject(targetObject);
b.position = 0;
var obj:Object = b.readObject();
// custom for Sprite/Shape
if (!obj.hasOwnProperty('graphics') && targetObject.hasOwnProperty('graphics'))
obj.graphics = {};
objects[jsName] = targetObject;
ExternalInterface.call(<><![CDATA[
(function(target, objectID, jsName, klassName) {
var swfObject = document.getElementsByName(objectID)[0];
var defineAttr = function(obj, parentProperties) {
var tmp = {};
for (var i in obj) {
if (obj[i] && (typeof(obj[i]) == "object" || typeof(obj[i]) == "array")) {
var pp = parentProperties.slice();
pp.push(i);
defineAttr(obj[i], pp);
continue;
}
tmp[i] = obj[i];
obj.__defineGetter__(i,
(function(attrName) {
return function() {
return this.__tmpProperties__[attrName]
}
})(i)
);
obj.__defineSetter__(i,
(function(attrName) {
return function(val) {
if (swfObject.updateProperty(jsName, [].concat(parentProperties).concat(attrName), val)) {
return this.__tmpProperties__[attrName] = val;
} else {
return this.__tmpProperties__[attrName];
}
}
})(i)
);
}
obj.__noSuchMethod__ = function(attrName, args) {
swfObject.callMethod(jsName, [].concat(parentProperties).concat(attrName), args);
}
obj.__tmpProperties__ = tmp;
}
defineAttr(target, []);
target.__reload = function() { return swfObject.reloadObject(jsName) };
if (!target.hasOwnProperty('reload')) target.reload = target.__reload;
target.toString = function() { return klassName };
window[jsName] = target;
;})
]]></>.toString(), obj, ExternalInterface.objectID, jsName, getQualifiedClassName(targetObject));
return jsName;
}
}
}
|
fix sum bugs
|
fix sum bugs
git-svn-id: 864080e30cc358c5edb906449bbf014f90258007@50 96db6a20-122f-0410-8d9f-89437bbe4005
|
ActionScript
|
mit
|
hotchpotch/as3rails2u,hotchpotch/as3rails2u
|
2754b6497a0cf4999fdd4f2ade4cf8f033ac866a
|
src/org/mangui/osmf/plugins/traits/HLSPlayTrait.as
|
src/org/mangui/osmf/plugins/traits/HLSPlayTrait.as
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.osmf.plugins.traits {
import org.mangui.hls.HLS;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.event.HLSEvent;
import org.osmf.traits.PlayState;
import org.osmf.traits.PlayTrait;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSPlayTrait extends PlayTrait
{
private var _hls : HLS;
private var streamStarted : Boolean = false;
public function HLSPlayTrait(hls : HLS)
{
CONFIG::LOGGING {
Log.debug("HLSPlayTrait()");
}
super();
_hls = hls;
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateChangedHandler);
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _playbackComplete);
}
override public function dispose() : void
{
CONFIG::LOGGING {
Log.debug("HLSPlayTrait:dispose");
}
_hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateChangedHandler);
_hls.removeEventListener(HLSEvent.PLAYBACK_COMPLETE, _playbackComplete);
super.dispose();
}
override protected function playStateChangeStart(newPlayState:String):void
{
CONFIG::LOGGING
{
Log.info("HLSPlayTrait:playStateChangeStart:" + newPlayState);
}
switch (newPlayState)
{
case PlayState.PLAYING:
if (!streamStarted)
{
_hls.stream.play();
streamStarted = true;
}
else
{
_hls.stream.resume();
}
break;
case PlayState.PAUSED:
_hls.stream.pause();
break;
case PlayState.STOPPED:
streamStarted = false;
_hls.stream.close();
break;
}
}
/** state changed handler **/
private function _stateChangedHandler(event:HLSEvent):void {
switch (event.state) {
case HLSPlayStates.PLAYING:
CONFIG::LOGGING {
Log.debug("HLSPlayTrait:_stateChangedHandler:setBuffering(true)");
}
if (!streamStarted) {
streamStarted = true;
play();
}
default:
}
}
/** playback complete handler **/
private function _playbackComplete(event : HLSEvent) : void {
stop();
}
}
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mangui.osmf.plugins.traits {
import org.mangui.hls.HLS;
import org.mangui.hls.constant.HLSPlayStates;
import org.mangui.hls.event.HLSEvent;
import org.osmf.traits.PlayState;
import org.osmf.traits.PlayTrait;
CONFIG::LOGGING {
import org.mangui.hls.utils.Log;
}
public class HLSPlayTrait extends PlayTrait {
private var _hls : HLS;
private var streamStarted : Boolean = false;
public function HLSPlayTrait(hls : HLS) {
CONFIG::LOGGING {
Log.debug("HLSPlayTrait()");
}
super();
_hls = hls;
_hls.addEventListener(HLSEvent.PLAYBACK_STATE, _stateChangedHandler);
_hls.addEventListener(HLSEvent.PLAYBACK_COMPLETE, _playbackComplete);
}
override public function dispose() : void {
CONFIG::LOGGING {
Log.debug("HLSPlayTrait:dispose");
}
_hls.removeEventListener(HLSEvent.PLAYBACK_STATE, _stateChangedHandler);
_hls.removeEventListener(HLSEvent.PLAYBACK_COMPLETE, _playbackComplete);
super.dispose();
}
override protected function playStateChangeStart(newPlayState:String):void {
CONFIG::LOGGING {
Log.info("HLSPlayTrait:playStateChangeStart:" + newPlayState);
}
switch (newPlayState) {
case PlayState.PLAYING:
if (!streamStarted) {
_hls.stream.play();
streamStarted = true;
}
else {
_hls.stream.resume();
}
break;
case PlayState.PAUSED:
_hls.stream.pause();
break;
case PlayState.STOPPED:
streamStarted = false;
_hls.stream.close();
break;
}
}
/** state changed handler **/
private function _stateChangedHandler(event:HLSEvent):void {
switch (event.state) {
case HLSPlayStates.PLAYING:
CONFIG::LOGGING {
Log.debug("HLSPlayTrait:_stateChangedHandler:setBuffering(true)");
}
if (!streamStarted) {
streamStarted = true;
play();
}
default:
}
}
/** playback complete handler **/
private function _playbackComplete(event : HLSEvent) : void {
stop();
}
}
}
|
fix indents and spaces
|
fix indents and spaces
|
ActionScript
|
mpl-2.0
|
vidible/vdb-flashls,mangui/flashls,fixedmachine/flashls,hola/flashls,thdtjsdn/flashls,neilrackett/flashls,NicolasSiver/flashls,NicolasSiver/flashls,tedconf/flashls,vidible/vdb-flashls,codex-corp/flashls,thdtjsdn/flashls,jlacivita/flashls,neilrackett/flashls,mangui/flashls,fixedmachine/flashls,hola/flashls,jlacivita/flashls,codex-corp/flashls,tedconf/flashls,clappr/flashls,clappr/flashls,loungelogic/flashls,loungelogic/flashls
|
bc48fa180462d8f6cf17da8926924165223a595c
|
exporter/src/main/as/flump/export/FlumpApp.as
|
exporter/src/main/as/flump/export/FlumpApp.as
|
//
// flump-exporter
package flump.export {
import com.threerings.util.Arrays;
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import flash.desktop.InvokeEventReason;
import flash.desktop.NativeApplication;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.filesystem.File;
import spark.components.Window;
public class FlumpApp
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
public static function get app () :FlumpApp {
return _app;
}
public function FlumpApp () {
if (_app != null) {
throw new Error("FlumpApp is a singleton");
}
_app = this;
}
public function run () :void {
Log.setLevel("", Log.INFO);
var launched :Boolean = false;
NA.addEventListener(InvokeEvent.INVOKE, function (event :InvokeEvent) :void {
if (event.arguments.length > 0) {
// A project file has been double-clicked. Open it.
openProject(new File(event.arguments[0]));
} else if (!launched) {
// The app has been launched directly. Open the last-opened project if
// it exists; else open a new project.
openProject(FlumpSettings.hasConfigFilePath ?
new File(FlumpSettings.configFilePath) : null);
} else if (_projects.length == 0) {
// The app has been resumed. We have no open projects; create a new one.
openProject();
}
launched = true;
});
}
public function openProject (configFile :File = null) :void {
// This project may already be open.
for each (var ctrl :ProjectController in _projects) {
if (ctrl.configFile == configFile) {
ctrl.win.visible = false;
if (!ctrl.win.orderToFront()) {
ctrl.win.restore();
ctrl.win.orderToFront();
}
return;
}
}
var controller :ProjectController = new ProjectController(configFile);
controller.win.addEventListener(Event.CLOSE, F.callbackOnce(closeProject, controller));
_projects.push(controller);
}
protected function closeProject (controller :ProjectController) :void {
Arrays.removeFirst(_projects, controller);
}
protected var _projects :Array = [];
protected static var _app :FlumpApp;
}
}
|
//
// flump-exporter
package flump.export {
import com.threerings.util.Arrays;
import com.threerings.util.F;
import com.threerings.util.Log;
import com.threerings.util.Map;
import com.threerings.util.Maps;
import flash.desktop.InvokeEventReason;
import flash.desktop.NativeApplication;
import flash.events.Event;
import flash.events.InvokeEvent;
import flash.filesystem.File;
import spark.components.Window;
public class FlumpApp
{
public static const NA :NativeApplication = NativeApplication.nativeApplication;
public static function get app () :FlumpApp {
return _app;
}
public function FlumpApp () {
if (_app != null) {
throw new Error("FlumpApp is a singleton");
}
_app = this;
}
public function run () :void {
Log.setLevel("", Log.INFO);
var launched :Boolean = false;
NA.addEventListener(InvokeEvent.INVOKE, function (event :InvokeEvent) :void {
if (event.arguments.length > 0) {
// A project file has been double-clicked. Open it.
openProject(new File(event.arguments[0]));
} else if (!launched) {
// The app has been launched directly. Open the last-opened project if
// it exists; else open a new project.
openProject(FlumpSettings.hasConfigFilePath ?
new File(FlumpSettings.configFilePath) : null);
} else if (_projects.length == 0) {
// The app has been resumed. We have no open projects; create a new one.
openProject();
}
launched = true;
});
}
public function openProject (configFile :File = null) :void {
// This project may already be open.
for each (var ctrl :ProjectController in _projects) {
if (ctrl.configFile != null && ctrl.configFile.nativePath == configFile.nativePath) {
ctrl.win.activate();
return;
}
}
var controller :ProjectController = new ProjectController(configFile);
controller.win.addEventListener(Event.CLOSE, F.callbackOnce(closeProject, controller));
_projects.push(controller);
}
protected function closeProject (controller :ProjectController) :void {
Arrays.removeFirst(_projects, controller);
}
protected var _projects :Array = [];
protected static var _app :FlumpApp;
}
}
|
Fix opening already-open projects
|
Fix opening already-open projects
|
ActionScript
|
mit
|
mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,mathieuanthoine/flump
|
adaffc2d2800cfe7f7632dc6e2cbb2012f147202
|
src/battlecode/client/viewer/render/DrawMap.as
|
src/battlecode/client/viewer/render/DrawMap.as
|
package battlecode.client.viewer.render {
import battlecode.client.viewer.MatchController;
import battlecode.common.MapLocation;
import battlecode.common.Team;
import battlecode.common.TerrainTile;
import battlecode.events.MatchEvent;
import battlecode.world.GameMap;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.ColorTransform;
import flash.geom.Rectangle;
import mx.containers.Canvas;
import mx.core.UIComponent;
public class DrawMap extends Canvas {
private var controller:MatchController;
private var origin:MapLocation;
// various canvases for layering and quick toggling of features
private var mapCanvas:UIComponent;
private var gridCanvas:UIComponent;
private var neutralCanvas:UIComponent;
private var groundUnitCanvas:UIComponent;
// optimizations for caching
private var lastRound:uint = 0;
public function DrawMap(controller:MatchController) {
super();
this.controller = controller;
this.controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange);
this.controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange);
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
this.mapCanvas = new UIComponent();
this.gridCanvas = new UIComponent();
this.neutralCanvas = new UIComponent();
this.groundUnitCanvas = new UIComponent();
this.mapCanvas.cacheAsBitmap = true;
this.gridCanvas.cacheAsBitmap = true;
this.addChild(mapCanvas);
this.addChild(gridCanvas);
this.addChild(neutralCanvas);
this.addChild(groundUnitCanvas);
}
///////////////////////////////////////////////////////
////////////////// UTILITY METHODS ////////////////////
///////////////////////////////////////////////////////
public function getMapWidth():uint {
if (controller.match)
return controller.match.getMap().getWidth() * RenderConfiguration.GRID_SIZE;
return 0;
}
public function getMapHeight():uint {
if (controller.match)
return controller.match.getMap().getHeight() * RenderConfiguration.GRID_SIZE + 5;
return 0;
}
private function getGridSize():Number {
return RenderConfiguration.getGridSize();
}
///////////////////////////////////////////////////////
////////////////// DRAWING METHODS ////////////////////
///////////////////////////////////////////////////////
public function redrawAll():void {
drawMap();
drawGridlines();
drawUnits();
drawCows();
var o:DrawObject;
for each (o in controller.currentState.getGroundRobots()) {
o.draw(true);
}
this.scrollRect = new Rectangle(this.mapCanvas.x, this.mapCanvas.y,
getMapWidth() * RenderConfiguration.getScalingFactor(),
getMapHeight() * RenderConfiguration.getScalingFactor());
}
private function drawMap():void {
var i:uint, j:uint, tile:TerrainTile;
var map:GameMap = controller.match.getMap();
var terrain:Array = map.getTerrainTiles();
var colorTransform:ColorTransform, scalar:uint;
origin = map.getOrigin();
this.mapCanvas.graphics.clear();
for (i = 0; i < map.getHeight(); i++) {
for (j = 0; j < map.getWidth(); j++) {
tile = terrain[i][j] as TerrainTile;
if (tile.getType() == TerrainTile.LAND) {
scalar = 0xFF * 0.9;
colorTransform = new ColorTransform(0, 0, 0, 1, scalar, scalar, scalar, 0);
this.mapCanvas.graphics.beginFill(colorTransform.color, 1.0);
this.mapCanvas.graphics.drawRect(j * getGridSize(), i * getGridSize(), getGridSize(), getGridSize());
this.mapCanvas.graphics.endFill();
} else if (tile.getType() == TerrainTile.ROAD) {
scalar = 0xFF * 0.7;
colorTransform = new ColorTransform(0, 0, 0, 1, scalar, scalar, scalar, 0);
this.mapCanvas.graphics.beginFill(colorTransform.color, 1.0);
this.mapCanvas.graphics.drawRect(j * getGridSize(), i * getGridSize(), getGridSize(), getGridSize());
this.mapCanvas.graphics.endFill();
} else {
colorTransform = new ColorTransform(0, 0, 0, 1, 0x00, 0x00, 0x99, 0);
this.mapCanvas.graphics.beginFill(colorTransform.color, 1.0);
this.mapCanvas.graphics.drawRect(j * getGridSize(), i * getGridSize(), getGridSize(), getGridSize());
this.mapCanvas.graphics.endFill();
}
}
}
}
private function drawGridlines():void {
var i:uint, j:uint;
var map:GameMap = controller.match.getMap();
this.gridCanvas.graphics.clear();
for (i = 0; i < map.getHeight(); i++) {
for (j = 0; j < map.getWidth(); j++) {
this.gridCanvas.graphics.lineStyle(.5, 0x999999, 0.3);
this.gridCanvas.graphics.drawRect(j * getGridSize(), i * getGridSize(), getGridSize(), getGridSize());
}
}
}
private function drawCows():void {
var cows:Array = controller.currentState.getNeutralDensities();
var cowsTeams:Array = controller.currentState.getNeutralTeams();
var i:uint, j:uint, team:String;
this.neutralCanvas.graphics.clear();
var g:Number = getGridSize();
for (i = 0; i < cows.length; i++) {
for (j = 0; j < cows[i].length; j++) {
var density:Number = cows[i][j] / 8000.0;
var color:Number = Team.cowColor(Team.valueOf(cowsTeams[i][j]));
this.neutralCanvas.graphics.lineStyle(1, color, 0.8);
this.neutralCanvas.graphics.beginFill(color, 0.4);
this.neutralCanvas.graphics.drawCircle((i + .5) * g, (j + .5) * g, g * density / 2);
this.neutralCanvas.graphics.endFill();
}
}
}
private function drawUnits():void {
var loc:MapLocation, i:uint, j:uint, robot:DrawRobot;
var groundRobots:Object = controller.currentState.getGroundRobots();
while (groundUnitCanvas.numChildren > 0)
groundUnitCanvas.removeChildAt(0);
for each (robot in groundRobots) {
loc = robot.getLocation();
j = (loc.getX() - origin.getX());
i = (loc.getY() - origin.getY());
robot.x = j * getGridSize() + getGridSize() / 2;
robot.y = i * getGridSize() + getGridSize() / 2;
robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true);
groundUnitCanvas.addChild(robot);
robot.draw();
}
}
private function updateUnits():void {
var loc:MapLocation, i:uint, j:uint, robot:DrawRobot;
var groundRobots:Object = controller.currentState.getGroundRobots();
for each (robot in groundRobots) {
loc = robot.getLocation();
j = (loc.getX() - origin.getX());
i = (loc.getY() - origin.getY());
robot.x = j * getGridSize() + getGridSize() / 2;
robot.y = i * getGridSize() + getGridSize() / 2;
if (!robot.parent && robot.isAlive()) {
robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true);
groundUnitCanvas.addChild(robot);
}
robot.draw();
}
}
///////////////////////////////////////////////////////
//////////////////// EVENT HANDLERS ///////////////////
///////////////////////////////////////////////////////
private function onEnterFrame(e:Event):void {
gridCanvas.visible = RenderConfiguration.showGridlines();
groundUnitCanvas.visible = RenderConfiguration.showGround();
neutralCanvas.visible = RenderConfiguration.showCows();
}
private function onRoundChange(e:MatchEvent):void {
if (e.currentRound < lastRound) {
drawUnits();
}
updateUnits();
drawCows();
lastRound = e.currentRound;
this.visible = (e.currentRound != 0);
}
private function onMatchChange(e:MatchEvent):void {
redrawAll();
}
private function onRobotSelect(e:MouseEvent):void {
var x:Number, y:Number;
if (RenderConfiguration.isTournament())
return;
if (controller.selectedRobot && controller.selectedRobot.parent) {
controller.selectedRobot.setSelected(false);
x = controller.selectedRobot.x;
y = controller.selectedRobot.y;
controller.selectedRobot.draw(true);
controller.selectedRobot.x = x;
controller.selectedRobot.y = y;
}
var robot:DrawRobot = e.currentTarget as DrawRobot;
robot.setSelected(true);
x = robot.x;
y = robot.y;
robot.draw(true);
robot.x = x;
robot.y = y;
controller.selectedRobot = robot;
}
}
}
|
package battlecode.client.viewer.render {
import battlecode.client.viewer.MatchController;
import battlecode.common.MapLocation;
import battlecode.common.Team;
import battlecode.common.TerrainTile;
import battlecode.events.MatchEvent;
import battlecode.world.GameMap;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.ColorTransform;
import flash.geom.Rectangle;
import mx.containers.Canvas;
import mx.core.UIComponent;
public class DrawMap extends Canvas {
private var controller:MatchController;
private var origin:MapLocation;
// various canvases for layering and quick toggling of features
private var mapCanvas:UIComponent;
private var gridCanvas:UIComponent;
private var neutralCanvas:UIComponent;
private var groundUnitCanvas:UIComponent;
// optimizations for caching
private var lastRound:uint = 0;
public function DrawMap(controller:MatchController) {
super();
this.controller = controller;
this.controller.addEventListener(MatchEvent.ROUND_CHANGE, onRoundChange);
this.controller.addEventListener(MatchEvent.MATCH_CHANGE, onMatchChange);
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);
this.mapCanvas = new UIComponent();
this.gridCanvas = new UIComponent();
this.neutralCanvas = new UIComponent();
this.groundUnitCanvas = new UIComponent();
this.mapCanvas.cacheAsBitmap = true;
this.gridCanvas.cacheAsBitmap = true;
this.addChild(mapCanvas);
this.addChild(gridCanvas);
this.addChild(neutralCanvas);
this.addChild(groundUnitCanvas);
}
///////////////////////////////////////////////////////
////////////////// UTILITY METHODS ////////////////////
///////////////////////////////////////////////////////
public function getMapWidth():uint {
if (controller.match)
return controller.match.getMap().getWidth() * RenderConfiguration.GRID_SIZE;
return 0;
}
public function getMapHeight():uint {
if (controller.match)
return controller.match.getMap().getHeight() * RenderConfiguration.GRID_SIZE + 5;
return 0;
}
private function getGridSize():Number {
return RenderConfiguration.getGridSize();
}
///////////////////////////////////////////////////////
////////////////// DRAWING METHODS ////////////////////
///////////////////////////////////////////////////////
public function redrawAll():void {
drawMap();
drawGridlines();
drawUnits();
drawCows();
var o:DrawObject;
for each (o in controller.currentState.getGroundRobots()) {
o.draw(true);
}
this.scrollRect = new Rectangle(this.mapCanvas.x, this.mapCanvas.y,
getMapWidth() * RenderConfiguration.getScalingFactor(),
getMapHeight() * RenderConfiguration.getScalingFactor());
}
private function drawMap():void {
var i:uint, j:uint, tile:TerrainTile;
var map:GameMap = controller.match.getMap();
var terrain:Array = map.getTerrainTiles();
var colorTransform:ColorTransform, scalar:uint;
origin = map.getOrigin();
this.mapCanvas.graphics.clear();
for (i = 0; i < map.getHeight(); i++) {
for (j = 0; j < map.getWidth(); j++) {
tile = terrain[i][j] as TerrainTile;
if (tile.getType() == TerrainTile.LAND) {
scalar = 0xFF * 0.9;
colorTransform = new ColorTransform(0, 0, 0, 1, scalar, scalar, scalar, 0);
this.mapCanvas.graphics.beginFill(colorTransform.color, 1.0);
this.mapCanvas.graphics.drawRect(j * getGridSize(), i * getGridSize(), getGridSize(), getGridSize());
this.mapCanvas.graphics.endFill();
} else if (tile.getType() == TerrainTile.ROAD) {
scalar = 0xFF * 0.7;
colorTransform = new ColorTransform(0, 0, 0, 1, scalar, scalar, scalar, 0);
this.mapCanvas.graphics.beginFill(colorTransform.color, 1.0);
this.mapCanvas.graphics.drawRect(j * getGridSize(), i * getGridSize(), getGridSize(), getGridSize());
this.mapCanvas.graphics.endFill();
} else {
colorTransform = new ColorTransform(0, 0, 0, 1, 0x00, 0x00, 0x99, 0);
this.mapCanvas.graphics.beginFill(colorTransform.color, 1.0);
this.mapCanvas.graphics.drawRect(j * getGridSize(), i * getGridSize(), getGridSize(), getGridSize());
this.mapCanvas.graphics.endFill();
}
}
}
}
private function drawGridlines():void {
var i:uint, j:uint;
var map:GameMap = controller.match.getMap();
this.gridCanvas.graphics.clear();
for (i = 0; i < map.getHeight(); i++) {
for (j = 0; j < map.getWidth(); j++) {
this.gridCanvas.graphics.lineStyle(.5, 0x999999, 0.3);
this.gridCanvas.graphics.drawRect(j * getGridSize(), i * getGridSize(), getGridSize(), getGridSize());
}
}
}
private function drawCows():void {
var cows:Array = controller.currentState.getNeutralDensities();
var cowsTeams:Array = controller.currentState.getNeutralTeams();
var i:uint, j:uint, team:String;
this.neutralCanvas.graphics.clear();
var g:Number = getGridSize();
for (i = 0; i < cows.length; i++) {
for (j = 0; j < cows[i].length; j++) {
var density:Number = cows[i][j] / 8000.0;
var color:Number = Team.cowColor(Team.valueOf(cowsTeams[i][j]));
this.neutralCanvas.graphics.lineStyle(1, color, 0.8);
this.neutralCanvas.graphics.beginFill(color, 0.4);
this.neutralCanvas.graphics.drawCircle((i + .5) * g, (j + .5) * g, g * Math.sqrt(density) / 2);
this.neutralCanvas.graphics.endFill();
}
}
}
private function drawUnits():void {
var loc:MapLocation, i:uint, j:uint, robot:DrawRobot;
var groundRobots:Object = controller.currentState.getGroundRobots();
while (groundUnitCanvas.numChildren > 0)
groundUnitCanvas.removeChildAt(0);
for each (robot in groundRobots) {
loc = robot.getLocation();
j = (loc.getX() - origin.getX());
i = (loc.getY() - origin.getY());
robot.x = j * getGridSize() + getGridSize() / 2;
robot.y = i * getGridSize() + getGridSize() / 2;
robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true);
groundUnitCanvas.addChild(robot);
robot.draw();
}
}
private function updateUnits():void {
var loc:MapLocation, i:uint, j:uint, robot:DrawRobot;
var groundRobots:Object = controller.currentState.getGroundRobots();
for each (robot in groundRobots) {
loc = robot.getLocation();
j = (loc.getX() - origin.getX());
i = (loc.getY() - origin.getY());
robot.x = j * getGridSize() + getGridSize() / 2;
robot.y = i * getGridSize() + getGridSize() / 2;
if (!robot.parent && robot.isAlive()) {
robot.addEventListener(MouseEvent.CLICK, onRobotSelect, false, 0, true);
groundUnitCanvas.addChild(robot);
}
robot.draw();
}
}
///////////////////////////////////////////////////////
//////////////////// EVENT HANDLERS ///////////////////
///////////////////////////////////////////////////////
private function onEnterFrame(e:Event):void {
gridCanvas.visible = RenderConfiguration.showGridlines();
groundUnitCanvas.visible = RenderConfiguration.showGround();
neutralCanvas.visible = RenderConfiguration.showCows();
}
private function onRoundChange(e:MatchEvent):void {
if (e.currentRound < lastRound) {
drawUnits();
}
updateUnits();
drawCows();
lastRound = e.currentRound;
this.visible = (e.currentRound != 0);
}
private function onMatchChange(e:MatchEvent):void {
redrawAll();
}
private function onRobotSelect(e:MouseEvent):void {
var x:Number, y:Number;
if (RenderConfiguration.isTournament())
return;
if (controller.selectedRobot && controller.selectedRobot.parent) {
controller.selectedRobot.setSelected(false);
x = controller.selectedRobot.x;
y = controller.selectedRobot.y;
controller.selectedRobot.draw(true);
controller.selectedRobot.x = x;
controller.selectedRobot.y = y;
}
var robot:DrawRobot = e.currentTarget as DrawRobot;
robot.setSelected(true);
x = robot.x;
y = robot.y;
robot.draw(true);
robot.x = x;
robot.y = y;
controller.selectedRobot = robot;
}
}
}
|
Change cow circle radii
|
Change cow circle radii
This changes cow circle radii from being proportional to the number of
cows in a square to being proportional to the square root of the
number of cows in a square. Since the circle area is proportional to
the square of the radius, this makes the area of circles proportional
to the number of cows, instead of the square of the number of cows.
|
ActionScript
|
mit
|
trun/battlecode-webclient
|
cab4e2eac82992bc5ceeee646575612903e25124
|
src/as/com/threerings/parlor/game/data/GameConfig.as
|
src/as/com/threerings/parlor/game/data/GameConfig.as
|
//
// $Id: GameConfig.java 4026 2006-04-18 01:32:41Z mdb $
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.parlor.game.data {
import com.threerings.util.ClassUtil;
import com.threerings.util.Cloneable;
import com.threerings.util.Hashable;
import com.threerings.util.Name;
import com.threerings.util.StringUtil;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.TypedArray;
import com.threerings.crowd.data.PlaceConfig;
import com.threerings.parlor.client.TableConfigurator;
import com.threerings.parlor.game.client.GameConfigurator;
/**
* The game config class encapsulates the configuration information for a
* particular type of game. The hierarchy of game config objects mimics the
* hierarchy of game managers and controllers. Both the game manager and game
* controller are provided with the game config object when the game is
* created.
*
* <p> The game config object is also the mechanism used to instantiate the
* appropriate game manager and controller. Every game must have an associated
* game config derived class that overrides {@link #createController} and
* {@link #getManagerClassName}, returning the appropriate game controller and
* manager class for that game. Thus the entire chain of events that causes a
* particular game to be created is the construction of the appropriate game
* config instance which is provided to the server as part of an invitation or
* via some other matchmaking mechanism.
*/
public /*abstract*/ class GameConfig extends PlaceConfig
implements Cloneable, Hashable
{
/** The usernames of the players involved in this game, or an empty
* array if such information is not needed by this particular game. */
public var players :TypedArray = TypedArray.create(Name);
/** Indicates whether or not this game is rated. */
public var rated :Boolean = true;
/** Configurations for AIs to be used in this game. Slots with real
* players should be null and slots with AIs should contain
* configuration for those AIs. A null array indicates no use of AIs
* at all. */
public var ais :TypedArray = TypedArray.create(GameAI);
/**
* Returns the message bundle identifier for the bundle that should be
* used to translate the translatable strings used to describe the
* game config parameters.
*/
public /*abstract*/ function getBundleName () :String
{
throw new Error("abstract");
}
/**
* Creates a configurator that can be used to create a user interface
* for configuring this instance prior to starting the game. If no
* configuration is necessary, this method should return null.
*/
public /*abstract*/ function createConfigurator () :GameConfigurator
{
throw new Error("abstract");
}
/**
* Creates a table configurator for initializing 'table' properties
* of the game. The default implementation returns null.
*/
public function createTableConfigurator () :TableConfigurator
{
return null;
}
/**
* Returns a translatable label describing this game.
*/
public function getGameName () :String
{
// the whole getRatingTypeId(), getGameName(), getBundleName()
// business should be cleaned up. we should have getGameIdent()
// and everything should have a default implementation using that
return "m." + getBundleName();
}
/**
* Returns the game rating type, if the system uses such things.
*/
public function getRatingTypeId () :int
{
return -1;
}
/**
* Returns an Array of strings that describe the configuration of this
* game. Default implementation returns an empty array.
*/
public function getDescription () :Array
{
return new Array(); // nothing by default
}
/**
* Returns true if this game config object is equal to the supplied
* object (meaning it is also a game config object and its
* configuration settings are the same as ours).
*/
public function equals (other :Object) :Boolean
{
// make sure they're of the same class
if (ClassUtil.getClassName(other) == ClassUtil.getClassName(this)) {
var that :GameConfig = GameConfig(other);
return this.rated == that.rated;
} else {
return false;
}
}
/**
* Computes a hashcode for this game config object that supports our
* {@link #equals} implementation. Objects that are equal should have
* the same hashcode.
*/
public function hashCode () :int
{
// look ma, it's so sophisticated!
return StringUtil.hashCode(ClassUtil.getClassName(this)) +
(rated ? 1 : 0);
}
// from Cloneable
public function clone () :Object
{
var copy :GameConfig = (ClassUtil.newInstance(this) as GameConfig);
copy.players = this.players;
copy.rated = this.rated;
copy.ais = this.ais;
return copy;
}
override public function writeObject (out :ObjectOutputStream) :void
{
super.writeObject(out);
out.writeObject(players);
out.writeBoolean(rated);
out.writeObject(ais);
}
override public function readObject (ins :ObjectInputStream) :void
{
super.readObject(ins);
players = (ins.readObject() as TypedArray);
rated = ins.readBoolean();
ais = (ins.readObject() as TypedArray);
}
}
}
|
//
// $Id: GameConfig.java 4026 2006-04-18 01:32:41Z mdb $
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2004 Three Rings Design, Inc., All Rights Reserved
// http://www.threerings.net/code/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.parlor.game.data {
import com.threerings.util.ClassUtil;
import com.threerings.util.Cloneable;
import com.threerings.util.Hashable;
import com.threerings.util.Name;
import com.threerings.util.StringUtil;
import com.threerings.io.ObjectInputStream;
import com.threerings.io.ObjectOutputStream;
import com.threerings.io.TypedArray;
import com.threerings.crowd.data.PlaceConfig;
import com.threerings.parlor.client.TableConfigurator;
import com.threerings.parlor.game.client.GameConfigurator;
/**
* The game config class encapsulates the configuration information for a
* particular type of game. The hierarchy of game config objects mimics the
* hierarchy of game managers and controllers. Both the game manager and game
* controller are provided with the game config object when the game is
* created.
*
* <p> The game config object is also the mechanism used to instantiate the
* appropriate game manager and controller. Every game must have an associated
* game config derived class that overrides {@link #createController} and
* {@link #getManagerClassName}, returning the appropriate game controller and
* manager class for that game. Thus the entire chain of events that causes a
* particular game to be created is the construction of the appropriate game
* config instance which is provided to the server as part of an invitation or
* via some other matchmaking mechanism.
*/
public /*abstract*/ class GameConfig extends PlaceConfig
implements Cloneable, Hashable
{
/** The usernames of the players involved in this game, or an empty
* array if such information is not needed by this particular game. */
public var players :TypedArray = TypedArray.create(Name);
/** Indicates whether or not this game is rated. */
public var rated :Boolean = true;
/** Configurations for AIs to be used in this game. Slots with real
* players should be null and slots with AIs should contain
* configuration for those AIs. A null array indicates no use of AIs
* at all. */
public var ais :TypedArray = TypedArray.create(GameAI);
/**
* Returns the message bundle identifier for the bundle that should be
* used to translate the translatable strings used to describe the
* game config parameters.
*/
public /*abstract*/ function getBundleName () :String
{
throw new Error("abstract");
}
/**
* Creates a configurator that can be used to create a user interface
* for configuring this instance prior to starting the game. If no
* configuration is necessary, this method should return null.
*/
public /*abstract*/ function createConfigurator () :GameConfigurator
{
throw new Error("abstract");
}
/**
* Creates a table configurator for initializing 'table' properties
* of the game. The default implementation returns null.
*/
public function createTableConfigurator () :TableConfigurator
{
return null;
}
/**
* Returns a translatable label describing this game.
*/
public function getGameName () :String
{
// the whole getRatingTypeId(), getGameName(), getBundleName()
// business should be cleaned up. we should have getGameIdent()
// and everything should have a default implementation using that
return "m." + getBundleName();
}
/**
* Returns the game rating type, if the system uses such things.
*/
public function getRatingTypeId () :int
{
return -1;
}
/**
* Returns an Array of strings that describe the configuration of this
* game. Default implementation returns an empty array.
*/
public function getDescription () :Array
{
return new Array(); // nothing by default
}
/**
* Returns true if this game config object is equal to the supplied
* object (meaning it is also a game config object and its
* configuration settings are the same as ours).
*/
public function equals (other :Object) :Boolean
{
// make sure they're of the same class
if (ClassUtil.isSameClass(other, this)) {
var that :GameConfig = GameConfig(other);
return this.rated == that.rated;
} else {
return false;
}
}
/**
* Computes a hashcode for this game config object that supports our
* {@link #equals} implementation. Objects that are equal should have
* the same hashcode.
*/
public function hashCode () :int
{
// look ma, it's so sophisticated!
return StringUtil.hashCode(ClassUtil.getClassName(this)) +
(rated ? 1 : 0);
}
// from Cloneable
public function clone () :Object
{
var copy :GameConfig = (ClassUtil.newInstance(this) as GameConfig);
copy.players = this.players;
copy.rated = this.rated;
copy.ais = this.ais;
return copy;
}
override public function writeObject (out :ObjectOutputStream) :void
{
super.writeObject(out);
out.writeObject(players);
out.writeBoolean(rated);
out.writeObject(ais);
}
override public function readObject (ins :ObjectInputStream) :void
{
super.readObject(ins);
players = (ins.readObject() as TypedArray);
rated = ins.readBoolean();
ais = (ins.readObject() as TypedArray);
}
}
}
|
Use ClassUtil.isSameClass().
|
Use ClassUtil.isSameClass().
git-svn-id: a3e1eb16dde062992de22c830ed8045c8013209a@40 c613c5cb-e716-0410-b11b-feb51c14d237
|
ActionScript
|
lgpl-2.1
|
threerings/vilya,threerings/vilya
|
676d1e594e32a245f3eff1cfb7c2ccf41a6e9659
|
src/com/google/analytics/campaign/CampaignManager.as
|
src/com/google/analytics/campaign/CampaignManager.as
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.campaign
{
import com.google.analytics.core.Buffer;
import com.google.analytics.core.OrganicReferrer;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.VisualDebugMode;
import com.google.analytics.utils.Protocols;
import com.google.analytics.utils.URL;
import com.google.analytics.utils.Variables;
import com.google.analytics.v4.Configuration;
/**
* The CampaignManager class.
*/
public class CampaignManager
{
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _buffer:Buffer;
private var _domainHash:Number;
private var _referrer:String;
private var _timeStamp:Number;
/**
* Delimiter for campaign tracker.
*/
public static const trackingDelimiter:String = "|";
/**
* Creates a new CampaignManager instance.
*/
public function CampaignManager( config:Configuration, debug:DebugConfiguration, buffer:Buffer,
domainHash:Number, referrer:String, timeStamp:Number )
{
_config = config;
_debug = debug;
_buffer = buffer;
_domainHash = domainHash;
_referrer = referrer;
_timeStamp = timeStamp;
}
/**
* This method will return true if and only document referrer is invalid.
* Document referrer is considered to be invalid when it's empty (undefined,
* empty string, "-", or "0"), or it's not a valid URL (doesn't have protocol)
*
* @private
* @param {String} docRef Document referrer to be evaluated for validity.
*
* @return {Boolean} True if and only if document referrer is invalid.
*/
public static function isInvalidReferrer( referrer:String ):Boolean
{
if( (referrer == "") ||
(referrer == "-") ||
(referrer == "0") )
{
return true;
}
if( referrer.indexOf("://") > -1 )
{
var url:URL = new URL( referrer );
if( (url.protocol == Protocols.file) ||
(url.protocol == Protocols.none) )
{
return true;
}
}
return false;
}
/**
* Checks if the document referrer is from the google custom search engine.
* @private
* @return <code class="prettyprint">true</code> if the referrer is from google custom search engine.
*/
public static function isFromGoogleCSE( referrer:String, config:Configuration ):Boolean
{
var url:URL = new URL( referrer );
// verify that the referrer is google cse search query.
if( url.hostName.indexOf( config.google ) > -1 )
{
if( url.search.indexOf( config.googleSearchParam+"=" ) > -1 )
{
// check if this is google custom search engine.
if( url.path == "/"+config.googleCsePath )
{
return true;
}
}
}
return false;
}
/**
* Retrieves campaign information. If linker functionality is allowed, and
* the cookie parsed from search string is valid (hash matches), then load the
* __utmz value form search string, and write the value to cookie, then return
* "". Otherwise, attempt to retrieve __utmz value from cookie. Then
* retrieve campaign information from search string. If that fails, try
* organic campaigns next. If that fails, try referral campaigns next. If
* that fails, try direct campaigns next. If it still fails, return nothing.
* Finally, determine whether the campaign is duplicated. If the campaign is
* not duplicated, then write campaign information to cookie, and indicate
* there is a new campaign for gif hit. Else, just indicate this is a
* repeated click for campaign.
*
* @private
* @param {_gat.GA_Cookie_} inCookie GA_Cookie instance containing cookie
* values parsed in from URL (linker). This value should never be
* undefined.
* @param {Boolean} noSession Indicating whether a session has been
* initialized. If __utmb and/or __utmc cookies are not set, then session
* has either timed-out or havn't been initialized yet.
*
* @return {String} Gif hit key-value pair indicating wether this is a repeated
* click, or a brand new campaign for the visitor.
*/
public function getCampaignInformation( search:String, noSessionInformation:Boolean ):CampaignInfo
{
var campInfo:CampaignInfo = new CampaignInfo();
var campaignTracker:CampaignTracker;
var duplicateCampaign:Boolean = false;
var campNoOverride:Boolean = false;
var responseCount:int = 0;
/* Allow linker functionality, and cookie is parsed from URL, and the cookie
hash matches.
*/
if( _config.allowLinker && _buffer.isGenuine() )
{
if( !_buffer.hasUTMZ() )
{
return campInfo;
}
}
// retrieves tracker from search string
campaignTracker = getTrackerFromSearchString( search );
if( isValid( campaignTracker ) )
{
// check for no override flag in search string
campNoOverride = hasNoOverride( search );
// if no override is true, and there is a utmz value, then do nothing now
if( campNoOverride && !_buffer.hasUTMZ() )
{
return campInfo;
}
}
// Get organic campaign if there is no campaign tracker from search string.
if( !isValid( campaignTracker ) )
{
campaignTracker = getOrganicCampaign();
//If there is utmz cookie value, and organic keyword is being ignored, do nothing.
if( !_buffer.hasUTMZ() && isIgnoredKeyword( campaignTracker ) )
{
return campInfo;
}
}
/* Get referral campaign if there is no campaign tracker from search string
and organic campaign, and either utmb or utmc is missing (no session).
*/
if( !isValid( campaignTracker ) && noSessionInformation )
{
campaignTracker = getReferrerCampaign();
//If there is utmz cookie value, and referral domain is being ignored, do nothing
if( !_buffer.hasUTMZ() && isIgnoredReferral( campaignTracker ) )
{
return campInfo;
}
}
/* Get direct campaign if there is no campaign tracker from search string,
organic campaign, or referral campaign.
*/
if( !isValid( campaignTracker ) )
{
/* Only get direct campaign when there is no utmz cookie value, and there is
no session. (utmb or utmc is missing value)
*/
if( !_buffer.hasUTMZ() && noSessionInformation )
{
campaignTracker = getDirectCampaign();
}
}
//Give up (do nothing) if still cannot get campaign tracker.
if( !isValid( campaignTracker ) )
{
return campInfo;
}
//utmz cookie have value, check whether campaign is duplicated.
if( _buffer.hasUTMZ() && !_buffer.utmz.isEmpty() )
{
var oldTracker:CampaignTracker = new CampaignTracker();
oldTracker.fromTrackerString( _buffer.utmz.campaignTracking );
duplicateCampaign = ( oldTracker.toTrackerString() == campaignTracker.toTrackerString() );
responseCount = _buffer.utmz.responseCount;
}
/* Record as new campaign if and only if campaign is not duplicated, or there
is no session information.
*/
if( !duplicateCampaign || noSessionInformation )
{
var sessionCount:int = _buffer.utma.sessionCount;
responseCount++;
// if there is no session number, increment
if( sessionCount == 0 )
{
sessionCount = 1;
}
// construct utmz cookie
_buffer.utmz.domainHash = _domainHash;
_buffer.utmz.campaignCreation = _timeStamp;
_buffer.utmz.campaignSessions = sessionCount;
_buffer.utmz.responseCount = responseCount;
_buffer.utmz.campaignTracking = campaignTracker.toTrackerString();
_debug.info( _buffer.utmz.toString(), VisualDebugMode.geek );
// indicate new campaign
campInfo = new CampaignInfo( false, true );
}
else
{
// indicate repeated campaign
campInfo = new CampaignInfo( false, false );
}
return campInfo;
}
/**
* This method returns the organic campaign information.
* @private
* @return {_gat.GA_Campaign_.Tracker_} Returns undefined if referrer is not
* a matching organic campaign source. Otherwise, returns the campaign tracker object.
*/
public function getOrganicCampaign():CampaignTracker
{
var camp:CampaignTracker;
// if there is no referrer, or referrer is not a valid URL, or the referrer
// is google custom search engine, return an empty tracker
if( isInvalidReferrer( _referrer ) || isFromGoogleCSE( _referrer, _config ) )
{
return camp;
}
var ref:URL = new URL( _referrer );
var name:String = "";
if( ref.hostName != "" )
{
if( ref.hostName.indexOf( "." ) > -1 )
{
var tmp:Array = ref.hostName.split( "." );
switch( tmp.length)
{
case 2:
// case: http://domain.com
name = tmp[0];
break;
case 3:
//case: http://www.domain.com
name = tmp[1];
break;
}
}
}
// organic source match
if( _config.organic.match( name ) )
{
var currentOrganicSource:OrganicReferrer = _config.organic.getReferrerByName( name );
// extract keyword value from query string
var keyword:String = _config.organic.getKeywordValue( currentOrganicSource, ref.search );
camp = new CampaignTracker();
camp.source = currentOrganicSource.engine;
camp.name = "(organic)";
camp.medium = "organic";
camp.term = keyword;
}
return camp;
}
/**
* This method returns the referral campaign information.
*
* @private
* @return {_gat.GA_Campaign_.Tracker_} Returns nothing if there is no
* referrer. Otherwise, return referrer campaign tracker.
*/
public function getReferrerCampaign():CampaignTracker
{
var camp:CampaignTracker;
// if there is no referrer, or referrer is not a valid URL, or the referrer
// is google custom search engine, return an empty tracker
if( isInvalidReferrer( _referrer ) || isFromGoogleCSE( _referrer, _config ) )
{
return camp;
}
// get host name from referrer
var ref:URL = new URL( _referrer );
var hostname:String = ref.hostName;
var content:String = ref.path;
if( hostname.indexOf( "www." ) == 0 )
{
hostname = hostname.substr( 4 );
}
camp = new CampaignTracker();
camp.source = hostname;
camp.name = "(referral)";
camp.medium = "referral";
camp.content = content;
return camp;
}
/**
* Returns the direct campaign tracker string.
* @private
* @return {_gat.GA_Campaign_.Tracker_} Direct campaign tracker object.
*/
public function getDirectCampaign():CampaignTracker
{
var camp:CampaignTracker = new CampaignTracker();
camp.source = "(direct)";
camp.name = "(direct)";
camp.medium = "(none)";
return camp;
}
/**
* Indicates if the manager has no override with the search value.
*/
public function hasNoOverride( search:String ):Boolean
{
var key:CampaignKey = _config.campaignKey;
if( search == "" )
{
return false;
}
var variables:Variables = new Variables( search );
var value:String = "";
if( variables.hasOwnProperty( key.UCNO ) )
{
value = variables[ key.UCNO ];
switch( value )
{
case "1":
return true;
case "":
case "0":
default:
return false;
}
}
return false;
}
/**
* This method returns true if and only if campaignTracker is a valid organic
* campaign tracker (utmcmd=organic), and the keyword (utmctr) is contained in
* the ignore watch list (ORGANIC_IGNORE).
*
* @private
* @param {_gat.GA_Campaign_.Tracker_} campaignTracker Campaign tracker
* reference.
*
* @return {Boolean} Return true if and only if the campaign tracker is a valid
* organic campaign tracker, and the keyword is contained in the ignored
* watch list.
*/
public function isIgnoredKeyword( tracker:CampaignTracker ):Boolean
{
// organic campaign, try to match ignored keywords
if( tracker && (tracker.medium == "organic") )
{
return _config.organic.isIgnoredKeyword( tracker.term );
}
return false;
}
/**
* This method returns true if and only if campaignTracker is a valid
* referreal campaign tracker (utmcmd=referral), and the domain (utmcsr) is
* contained in the ignore watch list (REFERRAL_IGNORE).
*
* @private
* @param {String} campaignTracker String representation of the campaign
* tracker.
*
* @return {Boolean} Return true if and only if the campaign tracker is a
* valid referral campaign tracker, and the domain is contained in the
* ignored watch list.
*/
public function isIgnoredReferral( tracker:CampaignTracker ):Boolean
{
// referral campaign, try to match ignored domains
if( tracker && (tracker.medium == "referral") )
{
return _config.organic.isIgnoredReferral( tracker.source );
}
return false;
}
public function isValid( tracker:CampaignTracker ):Boolean
{
if( tracker && tracker.isValid() )
{
return true;
}
return false;
}
/**
* Retrieves campaign tracker from search string.
*
* @param {String} searchString Search string to retrieve campaign tracker from.
* @return {String} Return campaign tracker retrieved from search string.
*/
public function getTrackerFromSearchString( search:String ):CampaignTracker
{
var organicCampaign:CampaignTracker = getOrganicCampaign();
var camp:CampaignTracker = new CampaignTracker();
var key:CampaignKey = _config.campaignKey;
if( search == "" )
{
return camp;
}
var variables:Variables = new Variables( search );
//id
if( variables.hasOwnProperty( key.UCID ) )
{
camp.id = variables[ key.UCID ];
}
//source
if( variables.hasOwnProperty( key.UCSR ) )
{
camp.source = variables[ key.UCSR ];
}
//click id
if( variables.hasOwnProperty( key.UGCLID ) )
{
camp.clickId = variables[ key.UGCLID ];
}
//name
if( variables.hasOwnProperty( key.UCCN ) )
{
camp.name = variables[ key.UCCN ];
}
else
{
camp.name = "(not set)";
}
//medium
if( variables.hasOwnProperty( key.UCMD ) )
{
camp.medium = variables[ key.UCMD ];
}
else
{
camp.medium = "(not set)";
}
//term
if( variables.hasOwnProperty( key.UCTR ) )
{
camp.term = variables[ key.UCTR ];
}
else if( organicCampaign && organicCampaign.term != "" )
{
camp.term = organicCampaign.term;
}
//content
if( variables.hasOwnProperty( key.UCCT ) )
{
camp.content = variables[ key.UCCT ];
}
return camp;
}
}
}
|
/*
* Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributor(s):
* Zwetan Kjukov <[email protected]>.
* Marc Alcaraz <[email protected]>.
*/
package com.google.analytics.campaign
{
import com.google.analytics.core.Buffer;
import com.google.analytics.core.OrganicReferrer;
import com.google.analytics.debug.DebugConfiguration;
import com.google.analytics.debug.VisualDebugMode;
import com.google.analytics.utils.Variables;
import com.google.analytics.v4.Configuration;
import core.uri;
/**
* The CampaignManager class.
*/
public class CampaignManager
{
private var _config:Configuration;
private var _debug:DebugConfiguration;
private var _buffer:Buffer;
private var _domainHash:Number;
private var _referrer:String;
private var _timeStamp:Number;
/**
* Delimiter for campaign tracker.
*/
public static const trackingDelimiter:String = "|";
/**
* Creates a new CampaignManager instance.
*/
public function CampaignManager( config:Configuration, debug:DebugConfiguration, buffer:Buffer,
domainHash:Number, referrer:String, timeStamp:Number )
{
_config = config;
_debug = debug;
_buffer = buffer;
_domainHash = domainHash;
_referrer = referrer;
_timeStamp = timeStamp;
}
/**
* This method will return true if and only document referrer is invalid.
* Document referrer is considered to be invalid when it's empty (undefined,
* empty string, "-", or "0"), or it's not a valid URL (doesn't have protocol)
*
* @private
* @param {String} docRef Document referrer to be evaluated for validity.
*
* @return {Boolean} True if and only if document referrer is invalid.
*/
public static function isInvalidReferrer( referrer:String ):Boolean
{
if( (referrer == "") ||
(referrer == "-") ||
(referrer == "0") )
{
return true;
}
var url:uri = new uri( referrer );
if( (url.scheme == "file") ||
(url.scheme == "") )
{
return true;
}
return false;
}
/**
* Checks if the document referrer is from the google custom search engine.
* @private
* @return <code class="prettyprint">true</code> if the referrer is from google custom search engine.
*/
public static function isFromGoogleCSE( referrer:String, config:Configuration ):Boolean
{
var url:uri = new uri( referrer );
if( url.host.indexOf( config.google ) > -1 )
{
if( (url.path == "/"+config.googleCsePath ) &&
(url.query.indexOf( config.googleSearchParam+"=" ) > -1) )
{
return true;
}
}
return false;
}
/**
* Retrieves campaign information. If linker functionality is allowed, and
* the cookie parsed from search string is valid (hash matches), then load the
* __utmz value form search string, and write the value to cookie, then return
* "". Otherwise, attempt to retrieve __utmz value from cookie. Then
* retrieve campaign information from search string. If that fails, try
* organic campaigns next. If that fails, try referral campaigns next. If
* that fails, try direct campaigns next. If it still fails, return nothing.
* Finally, determine whether the campaign is duplicated. If the campaign is
* not duplicated, then write campaign information to cookie, and indicate
* there is a new campaign for gif hit. Else, just indicate this is a
* repeated click for campaign.
*
* @private
* @param {_gat.GA_Cookie_} inCookie GA_Cookie instance containing cookie
* values parsed in from URL (linker). This value should never be
* undefined.
* @param {Boolean} noSession Indicating whether a session has been
* initialized. If __utmb and/or __utmc cookies are not set, then session
* has either timed-out or havn't been initialized yet.
*
* @return {String} Gif hit key-value pair indicating wether this is a repeated
* click, or a brand new campaign for the visitor.
*/
public function getCampaignInformation( search:String, noSessionInformation:Boolean ):CampaignInfo
{
var campInfo:CampaignInfo = new CampaignInfo();
var campaignTracker:CampaignTracker;
var duplicateCampaign:Boolean = false;
var campNoOverride:Boolean = false;
var responseCount:int = 0;
/* Allow linker functionality, and cookie is parsed from URL, and the cookie
hash matches.
*/
if( _config.allowLinker && _buffer.isGenuine() )
{
if( !_buffer.hasUTMZ() )
{
return campInfo;
}
}
// retrieves tracker from search string
campaignTracker = getTrackerFromSearchString( search );
if( isValid( campaignTracker ) )
{
// check for no override flag in search string
campNoOverride = hasNoOverride( search );
// if no override is true, and there is a utmz value, then do nothing now
if( campNoOverride && !_buffer.hasUTMZ() )
{
return campInfo;
}
}
// Get organic campaign if there is no campaign tracker from search string.
if( !isValid( campaignTracker ) )
{
campaignTracker = getOrganicCampaign();
//If there is utmz cookie value, and organic keyword is being ignored, do nothing.
if( !_buffer.hasUTMZ() && isIgnoredKeyword( campaignTracker ) )
{
return campInfo;
}
}
/* Get referral campaign if there is no campaign tracker from search string
and organic campaign, and either utmb or utmc is missing (no session).
*/
if( !isValid( campaignTracker ) && noSessionInformation )
{
campaignTracker = getReferrerCampaign();
//If there is utmz cookie value, and referral domain is being ignored, do nothing
if( !_buffer.hasUTMZ() && isIgnoredReferral( campaignTracker ) )
{
return campInfo;
}
}
/* Get direct campaign if there is no campaign tracker from search string,
organic campaign, or referral campaign.
*/
if( !isValid( campaignTracker ) )
{
/* Only get direct campaign when there is no utmz cookie value, and there is
no session. (utmb or utmc is missing value)
*/
if( !_buffer.hasUTMZ() && noSessionInformation )
{
campaignTracker = getDirectCampaign();
}
}
//Give up (do nothing) if still cannot get campaign tracker.
if( !isValid( campaignTracker ) )
{
return campInfo;
}
//utmz cookie have value, check whether campaign is duplicated.
if( _buffer.hasUTMZ() && !_buffer.utmz.isEmpty() )
{
var oldTracker:CampaignTracker = new CampaignTracker();
oldTracker.fromTrackerString( _buffer.utmz.campaignTracking );
duplicateCampaign = ( oldTracker.toTrackerString() == campaignTracker.toTrackerString() );
responseCount = _buffer.utmz.responseCount;
}
/* Record as new campaign if and only if campaign is not duplicated, or there
is no session information.
*/
if( !duplicateCampaign || noSessionInformation )
{
var sessionCount:int = _buffer.utma.sessionCount;
responseCount++;
// if there is no session number, increment
if( sessionCount == 0 )
{
sessionCount = 1;
}
// construct utmz cookie
_buffer.utmz.domainHash = _domainHash;
_buffer.utmz.campaignCreation = _timeStamp;
_buffer.utmz.campaignSessions = sessionCount;
_buffer.utmz.responseCount = responseCount;
_buffer.utmz.campaignTracking = campaignTracker.toTrackerString();
_debug.info( _buffer.utmz.toString(), VisualDebugMode.geek );
// indicate new campaign
campInfo = new CampaignInfo( false, true );
}
else
{
// indicate repeated campaign
campInfo = new CampaignInfo( false, false );
}
return campInfo;
}
/**
* This method returns the organic campaign information.
* @private
* @return {_gat.GA_Campaign_.Tracker_} Returns undefined if referrer is not
* a matching organic campaign source. Otherwise, returns the campaign tracker object.
*/
public function getOrganicCampaign():CampaignTracker
{
var camp:CampaignTracker;
// if there is no referrer, or referrer is not a valid URL, or the referrer
// is google custom search engine, return an empty tracker
if( isInvalidReferrer( _referrer ) || isFromGoogleCSE( _referrer, _config ) )
{
return camp;
}
var ref:uri = new uri( _referrer );
var name:String;
if( (ref.host != "") && (ref.host.indexOf(".") > -1) )
{
var tmp:Array = ref.host.split( "." );
switch( tmp.length )
{
case 2:
name = tmp[0];
break;
case 3:
name = tmp[1];
}
}
// organic source match
if( _config.organic.match( name ) )
{
var currentOrganicSource:OrganicReferrer = _config.organic.getReferrerByName( name );
// extract keyword value from query string
var keyword:String = _config.organic.getKeywordValue( currentOrganicSource, ref.query );
camp = new CampaignTracker();
camp.source = currentOrganicSource.engine;
camp.name = "(organic)";
camp.medium = "organic";
camp.term = keyword;
}
return camp;
}
/**
* This method returns the referral campaign information.
*
* @private
* @return {_gat.GA_Campaign_.Tracker_} Returns nothing if there is no
* referrer. Otherwise, return referrer campaign tracker.
*/
public function getReferrerCampaign():CampaignTracker
{
var camp:CampaignTracker;
// if there is no referrer, or referrer is not a valid URL, or the referrer
// is google custom search engine, return an empty tracker
if( isInvalidReferrer( _referrer ) || isFromGoogleCSE( _referrer, _config ) )
{
return camp;
}
// get host name from referrer
var ref:uri = new uri( _referrer );
var hostname:String = ref.host;
var content:String = ref.path;
if( content == "" ) { content = "/"; } //fix empty path
if( hostname.indexOf( "www." ) == 0 )
{
hostname = hostname.substr( 4 );
}
camp = new CampaignTracker();
camp.source = hostname;
camp.name = "(referral)";
camp.medium = "referral";
camp.content = content;
return camp;
}
/**
* Returns the direct campaign tracker string.
* @private
* @return {_gat.GA_Campaign_.Tracker_} Direct campaign tracker object.
*/
public function getDirectCampaign():CampaignTracker
{
var camp:CampaignTracker = new CampaignTracker();
camp.source = "(direct)";
camp.name = "(direct)";
camp.medium = "(none)";
return camp;
}
/**
* Indicates if the manager has no override with the search value.
*/
public function hasNoOverride( search:String ):Boolean
{
var key:CampaignKey = _config.campaignKey;
if( search == "" )
{
return false;
}
var variables:Variables = new Variables( search );
var value:String = "";
if( variables.hasOwnProperty( key.UCNO ) )
{
value = variables[ key.UCNO ];
switch( value )
{
case "1":
return true;
case "":
case "0":
default:
return false;
}
}
return false;
}
/**
* This method returns true if and only if campaignTracker is a valid organic
* campaign tracker (utmcmd=organic), and the keyword (utmctr) is contained in
* the ignore watch list (ORGANIC_IGNORE).
*
* @private
* @param {_gat.GA_Campaign_.Tracker_} campaignTracker Campaign tracker
* reference.
*
* @return {Boolean} Return true if and only if the campaign tracker is a valid
* organic campaign tracker, and the keyword is contained in the ignored
* watch list.
*/
public function isIgnoredKeyword( tracker:CampaignTracker ):Boolean
{
// organic campaign, try to match ignored keywords
if( tracker && (tracker.medium == "organic") )
{
return _config.organic.isIgnoredKeyword( tracker.term );
}
return false;
}
/**
* This method returns true if and only if campaignTracker is a valid
* referreal campaign tracker (utmcmd=referral), and the domain (utmcsr) is
* contained in the ignore watch list (REFERRAL_IGNORE).
*
* @private
* @param {String} campaignTracker String representation of the campaign
* tracker.
*
* @return {Boolean} Return true if and only if the campaign tracker is a
* valid referral campaign tracker, and the domain is contained in the
* ignored watch list.
*/
public function isIgnoredReferral( tracker:CampaignTracker ):Boolean
{
// referral campaign, try to match ignored domains
if( tracker && (tracker.medium == "referral") )
{
return _config.organic.isIgnoredReferral( tracker.source );
}
return false;
}
public function isValid( tracker:CampaignTracker ):Boolean
{
if( tracker && tracker.isValid() )
{
return true;
}
return false;
}
/**
* Retrieves campaign tracker from search string.
*
* @param {String} searchString Search string to retrieve campaign tracker from.
* @return {String} Return campaign tracker retrieved from search string.
*/
public function getTrackerFromSearchString( search:String ):CampaignTracker
{
var organicCampaign:CampaignTracker = getOrganicCampaign();
var camp:CampaignTracker = new CampaignTracker();
var key:CampaignKey = _config.campaignKey;
if( search == "" )
{
return camp;
}
var variables:Variables = new Variables( search );
//id
if( variables.hasOwnProperty( key.UCID ) )
{
camp.id = variables[ key.UCID ];
}
//source
if( variables.hasOwnProperty( key.UCSR ) )
{
camp.source = variables[ key.UCSR ];
}
//click id
if( variables.hasOwnProperty( key.UGCLID ) )
{
camp.clickId = variables[ key.UGCLID ];
}
//name
if( variables.hasOwnProperty( key.UCCN ) )
{
camp.name = variables[ key.UCCN ];
}
else
{
camp.name = "(not set)";
}
//medium
if( variables.hasOwnProperty( key.UCMD ) )
{
camp.medium = variables[ key.UCMD ];
}
else
{
camp.medium = "(not set)";
}
//term
if( variables.hasOwnProperty( key.UCTR ) )
{
camp.term = variables[ key.UCTR ];
}
else if( organicCampaign && organicCampaign.term != "" )
{
camp.term = organicCampaign.term;
}
//content
if( variables.hasOwnProperty( key.UCCT ) )
{
camp.content = variables[ key.UCCT ];
}
return camp;
}
}
}
|
replace URL class by core.uri
|
replace URL class by core.uri
|
ActionScript
|
apache-2.0
|
nsdevaraj/gaforflash,minimedj/gaforflash,minimedj/gaforflash,nsdevaraj/gaforflash
|
76de595c220f8eebf166560bb1a1f07e6ab9af7e
|
project_templates/pure_as3/src/TrivialDrive.as
|
project_templates/pure_as3/src/TrivialDrive.as
|
package {
import com.gerantech.extensions.iab.Purchase;
import core.Assets;
import core.BillingManager;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import objects.Car;
import objects.GasGauge;
[SWF(width=720, height=1280, frameRate=60, backgroundColor=0x000000)]
public class TrivialDrive extends Sprite
{
private var _billingManager:BillingManager;
private var _car:Car;
private var _title:Sprite;
private var _gauge:GasGauge;
private var _driveBtn:Sprite;
private var _buyGasBtn:Sprite;
private var _upgradeBtn:Sprite;
private var _infiniteGasBtn:Sprite;
private var _gasLevel:int;
private var _waitBackground:Sprite;
private var _waitIcon:Sprite;
public function TrivialDrive()
{
stage.color = 0x303030;
_billingManager = BillingManager.instance;
_billingManager.addEventListener(BillingManager.ON_INITIALIZED, onInitialized);
_title = new Sprite();
_title.addChild(Assets.getBitmap("title"));
_title.x = (stage.stageWidth - _title.width) * 0.5;
_title.y = 100;
addChild(_title);
_car = new Car();
_car.x = (stage.stageWidth - _car.width) * 0.5;
_car.y = 250;
addChild(_car);
_gauge = new GasGauge();
_gauge.x = (stage.stageWidth - _gauge.width) * 0.5;
_gauge.y = 500;
addChild(_gauge);
_driveBtn = new Sprite();
_driveBtn.addChild(Assets.getBitmap("drive"));
_driveBtn.x = stage.stageWidth * 0.25 - _driveBtn.width * 0.5;
_driveBtn.y = 700;
addChild(_driveBtn);
_buyGasBtn = new Sprite();
_buyGasBtn.addChild(Assets.getBitmap("buy_gas"));
_buyGasBtn.x = stage.stageWidth * 0.75 - _buyGasBtn.width * 0.5;
_buyGasBtn.y = 700;
addChild(_buyGasBtn);
_upgradeBtn = new Sprite();
_upgradeBtn.addChild(Assets.getBitmap("upgrade_app"));
_upgradeBtn.x = stage.stageWidth * 0.25 - _upgradeBtn.width * 0.5;
_upgradeBtn.y = 900;
addChild(_upgradeBtn);
_infiniteGasBtn = new Sprite();
_infiniteGasBtn.addChild(Assets.getBitmap("get_infinite_gas"));
_infiniteGasBtn.x = stage.stageWidth * 0.75 - _infiniteGasBtn.width * 0.5;
_infiniteGasBtn.y = 900;
addChild(_infiniteGasBtn);
_waitBackground = new Sprite();
_waitBackground.graphics.beginFill(0x000000, 0.75);
_waitBackground.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
_waitBackground.graphics.endFill();
addChild(_waitBackground);
_waitIcon = new Sprite();
_waitIcon.addChild(Assets.getBitmap("wait"));
_waitIcon.x = stage.stageWidth * 0.5 - _infiniteGasBtn.width * 0.5;
_waitIcon.y = stage.stageHeight * 0.5 - _infiniteGasBtn.height * 0.5;
addChild(_waitIcon);
}
protected function onInitialized(event:Event):void {
_billingManager.removeEventListener(BillingManager.ON_INITIALIZED, onInitialized);
// Add event listeners to buttons
_buyGasBtn.addEventListener(MouseEvent.CLICK, buyGas);
_driveBtn.addEventListener(MouseEvent.CLICK, drive);
_upgradeBtn.addEventListener(MouseEvent.CLICK, upgrade);
_infiniteGasBtn.addEventListener(MouseEvent.CLICK, subscribe);
// Check if client has bought the premium car (permanent product)
var premiumCar:Purchase = _billingManager.getPurchase("my.product.id2");
if( premiumCar ) {
trace("premiumCar >", premiumCar, premiumCar.itemType, premiumCar.packageName, premiumCar.sku, premiumCar.token, premiumCar.developerPayload);
_car.setToPremium();
}
// Check if client has infinite gas (subscribed)
var infiniteGas:Purchase = _billingManager.getPurchase("my.product.id3");
if( infiniteGas ) {
trace("infiniteGas >", infiniteGas, infiniteGas.itemType, infiniteGas.packageName, infiniteGas.sku, infiniteGas.token, infiniteGas.developerPayload);
_gasLevel = -1;
_gauge.setTo(_gasLevel);
}
// Remove wait assets
removeChild(_waitBackground);
removeChild(_waitIcon);
}
protected function buyGas(event:MouseEvent):void {
_billingManager.purchase("my.product.id1", true, "payload_for_gas");
_billingManager.addEventListener(BillingManager.ON_PURCHASE_SUCCESS, onPurchaseSuccess);
}
protected function onPurchaseSuccess(event:Event):void {
_billingManager.removeEventListener(BillingManager.ON_PURCHASE_SUCCESS, onPurchaseSuccess);
if (_gasLevel >= 0) // _gasLevel = -1 means infinite gas (subscribed user)
_gasLevel++;
_gauge.setTo(_gasLevel);
}
protected function drive(event:MouseEvent):void {
if (_gasLevel > 0)
_gasLevel--;
_gauge.setTo(_gasLevel);
}
protected function upgrade(event:MouseEvent):void {
_billingManager.addEventListener(BillingManager.ON_PURCHASE_SUCCESS, onUpgradeSuccess);
_billingManager.purchase("my.product.id2", false, "payload_for_upgrade");
}
protected function onUpgradeSuccess(event:Event):void {
_billingManager.removeEventListener(BillingManager.ON_PURCHASE_SUCCESS, onUpgradeSuccess);
_car.setToPremium();
}
protected function subscribe(event:MouseEvent):void {
_billingManager.addEventListener(BillingManager.ON_PURCHASE_SUCCESS, onSubscribtionSuccess);
_billingManager.subscribe("my.product.id3");
}
protected function onSubscribtionSuccess(event:Event):void {
_billingManager.removeEventListener(BillingManager.ON_PURCHASE_SUCCESS, onSubscribtionSuccess);
_gasLevel = -1;
_gauge.setTo(_gasLevel);
}
}
}
|
package {
import com.gerantech.extensions.iab.Purchase;
import core.Assets;
import core.BillingManager;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import objects.Car;
import objects.GasGauge;
[SWF(width=720, height=1280, frameRate=60, backgroundColor=0x000000)]
public class TrivialDrive extends Sprite
{
private var _billingManager:BillingManager;
private var _car:Car;
private var _title:Sprite;
private var _gauge:GasGauge;
private var _driveBtn:Sprite;
private var _buyGasBtn:Sprite;
private var _upgradeBtn:Sprite;
private var _infiniteGasBtn:Sprite;
private var _gasLevel:int;
private var _waitBackground:Sprite;
private var _waitIcon:Sprite;
public function TrivialDrive()
{
stage.color = 0x303030;
_billingManager = BillingManager.instance;
_billingManager.addEventListener(BillingManager.ON_INITIALIZED, onInitialized);
_title = new Sprite();
_title.addChild(Assets.getBitmap("title"));
_title.x = (stage.stageWidth - _title.width) * 0.5;
_title.y = 100;
addChild(_title);
_car = new Car();
_car.x = (stage.stageWidth - _car.width) * 0.5;
_car.y = 250;
addChild(_car);
_gauge = new GasGauge();
_gauge.x = (stage.stageWidth - _gauge.width) * 0.5;
_gauge.y = 500;
addChild(_gauge);
_driveBtn = new Sprite();
_driveBtn.addChild(Assets.getBitmap("drive"));
_driveBtn.x = stage.stageWidth * 0.25 - _driveBtn.width * 0.5;
_driveBtn.y = 700;
addChild(_driveBtn);
_buyGasBtn = new Sprite();
_buyGasBtn.addChild(Assets.getBitmap("buy_gas"));
_buyGasBtn.x = stage.stageWidth * 0.75 - _buyGasBtn.width * 0.5;
_buyGasBtn.y = 700;
addChild(_buyGasBtn);
_upgradeBtn = new Sprite();
_upgradeBtn.addChild(Assets.getBitmap("upgrade_app"));
_upgradeBtn.x = stage.stageWidth * 0.25 - _upgradeBtn.width * 0.5;
_upgradeBtn.y = 900;
addChild(_upgradeBtn);
_infiniteGasBtn = new Sprite();
_infiniteGasBtn.addChild(Assets.getBitmap("get_infinite_gas"));
_infiniteGasBtn.x = stage.stageWidth * 0.75 - _infiniteGasBtn.width * 0.5;
_infiniteGasBtn.y = 900;
addChild(_infiniteGasBtn);
_waitBackground = new Sprite();
_waitBackground.graphics.beginFill(0x000000, 0.75);
_waitBackground.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
_waitBackground.graphics.endFill();
addChild(_waitBackground);
_waitIcon = new Sprite();
_waitIcon.addChild(Assets.getBitmap("wait"));
_waitIcon.x = stage.stageWidth * 0.5 - _infiniteGasBtn.width * 0.5;
_waitIcon.y = stage.stageHeight * 0.5 - _infiniteGasBtn.height * 0.5;
addChild(_waitIcon);
}
protected function onInitialized(event:Event):void {
_billingManager.removeEventListener(BillingManager.ON_INITIALIZED, onInitialized);
// Add event listeners to buttons
_buyGasBtn.addEventListener(MouseEvent.CLICK, buyGas);
_driveBtn.addEventListener(MouseEvent.CLICK, drive);
_upgradeBtn.addEventListener(MouseEvent.CLICK, upgrade);
_infiniteGasBtn.addEventListener(MouseEvent.CLICK, subscribe);
// Check if client has bought the premium car (permanent product)
var premiumCar:Purchase = _billingManager.getPurchase("my.product.id2");
if( premiumCar ) {
trace("premiumCar >", premiumCar, premiumCar.itemType, premiumCar.packageName, premiumCar.sku, premiumCar.token, premiumCar.developerPayload);
_car.setToPremium();
}
// Check if client has infinite gas (subscribed)
var infiniteGas:Purchase = _billingManager.getPurchase("my.product.id3");
if( infiniteGas ) {
trace("infiniteGas >", infiniteGas, infiniteGas.itemType, infiniteGas.packageName, infiniteGas.sku, infiniteGas.token, infiniteGas.developerPayload);
_gasLevel = -1;
_gauge.setTo(_gasLevel);
}
// Read gas level from local storage
var sharedObj:SharedObject = SharedObject.getLocal("saveData");
_gasLevel = sharedObj.data.gasLevel;
_gauge.setTo(_gasLevel);
// Remove wait assets
removeChild(_waitBackground);
removeChild(_waitIcon);
}
protected function buyGas(event:MouseEvent):void {
_billingManager.purchase("my.product.id1", true, "payload_for_gas");
_billingManager.addEventListener(BillingManager.ON_PURCHASE_SUCCESS, onPurchaseSuccess);
}
protected function onPurchaseSuccess(event:Event):void {
_billingManager.removeEventListener(BillingManager.ON_PURCHASE_SUCCESS, onPurchaseSuccess);
if (_gasLevel >= 0) // _gasLevel = -1 means infinite gas (subscribed user)
_gasLevel++;
_gauge.setTo(_gasLevel);
// save gas level locally
saveGasLevel();
}
protected function drive(event:MouseEvent):void {
if (_gasLevel > 0)
_gasLevel--;
_gauge.setTo(_gasLevel);
// save gas level locally
saveGasLevel();
}
private function saveGasLevel():void {
var sharedObj:SharedObject = SharedObject.getLocal("saveData");
sharedObj.data.gasLevel = _gasLevel;
sharedObj.flush();
}
protected function upgrade(event:MouseEvent):void {
_billingManager.addEventListener(BillingManager.ON_PURCHASE_SUCCESS, onUpgradeSuccess);
_billingManager.purchase("my.product.id2", false, "payload_for_upgrade");
}
protected function onUpgradeSuccess(event:Event):void {
_billingManager.removeEventListener(BillingManager.ON_PURCHASE_SUCCESS, onUpgradeSuccess);
_car.setToPremium();
}
protected function subscribe(event:MouseEvent):void {
_billingManager.addEventListener(BillingManager.ON_PURCHASE_SUCCESS, onSubscribtionSuccess);
_billingManager.subscribe("my.product.id3");
}
protected function onSubscribtionSuccess(event:Event):void {
_billingManager.removeEventListener(BillingManager.ON_PURCHASE_SUCCESS, onSubscribtionSuccess);
_gasLevel = -1;
_gauge.setTo(_gasLevel);
}
}
}
|
Update TrivialDrive.as
|
Update TrivialDrive.as
added local save of gas level
|
ActionScript
|
mit
|
manjav/air-extension-inappbilling
|
81b0221453a6f4cc1993292b77e7a4b3d4893ee0
|
as3/xobjas3/src/com/rpath/xobj/FilterTerm.as
|
as3/xobjas3/src/com/rpath/xobj/FilterTerm.as
|
/*
# Copyright (c) 2008-2010 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 warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
#
*/
package com.rpath.xobj
{
[Bindable]
public class FilterTerm
{
public function FilterTerm(name:String,
value:String,
operator:String = EQUAL)
{
super();
this.name = name;
this.operator = operator;
this.value = value;
}
/**
* The field/property to filter on (LHS)
*/
public var name:String;
/**
* The logical operator to apply (see static consts below)
*/
public var operator:String;
/**
* The value to test the field against (RHS)
*/
public var value:String;
public static const EQUAL:String = "EQUAL";
public static const NOT_EQUAL:String = "NOT_EQUAL";
public static const LESS_THAN:String = "LESS_THAN";
public static const LESS_THAN_OR_EQUAL:String = "LESS_THAN_OR_EQUAL";
public static const GREATER_THAN:String = "GREATER_THAN";
public static const GREATER_THAN_OR_EQUAL:String = "GREATER_THAN_OR_EQUAL";
public static const LIKE:String = "LIKE";
public static const NOT_LIKE:String = "NOT_LIKE";
public static const IN:String = "IN";
public static const NOT_IN:String = "NOT_IN";
public static const MATCHING:String = "MATCHING";
public static const NOT_MATCHING:String = "NOT_MATCHING";
public static const YES:String = "YES";
public static const NO:String = "NO";
}
}
|
/*
# Copyright (c) 2008-2010 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 warranty; without even the implied warranty of merchantability
# or fitness for a particular purpose. See the MIT License for full details.
#
*/
package com.rpath.xobj
{
[RemoteClass]
[Bindable]
public class FilterTerm
{
public function FilterTerm(name:String,
value:String,
operator:String = EQUAL)
{
super();
this.name = name;
this.operator = operator;
this.value = value;
}
/**
* The field/property to filter on (LHS)
*/
public var name:String;
/**
* The logical operator to apply (see static consts below)
*/
public var operator:String;
/**
* The value to test the field against (RHS)
*/
public var value:String;
public static const EQUAL:String = "EQUAL";
public static const NOT_EQUAL:String = "NOT_EQUAL";
public static const LESS_THAN:String = "LESS_THAN";
public static const LESS_THAN_OR_EQUAL:String = "LESS_THAN_OR_EQUAL";
public static const GREATER_THAN:String = "GREATER_THAN";
public static const GREATER_THAN_OR_EQUAL:String = "GREATER_THAN_OR_EQUAL";
public static const LIKE:String = "LIKE";
public static const NOT_LIKE:String = "NOT_LIKE";
public static const IN:String = "IN";
public static const NOT_IN:String = "NOT_IN";
public static const MATCHING:String = "MATCHING";
public static const NOT_MATCHING:String = "NOT_MATCHING";
public static const YES:String = "YES";
public static const NO:String = "NO";
}
}
|
Make FilterTerm [RemoteClass] to enable clone() to work
|
Make FilterTerm [RemoteClass] to enable clone() to work
|
ActionScript
|
apache-2.0
|
sassoftware/xobj,sassoftware/xobj,sassoftware/xobj,sassoftware/xobj
|
5e130bb95fc3582aa95eb9875e75d9737f53fcff
|
sAS3Cam.as
|
sAS3Cam.as
|
/**
* jQuery AS3 Webcam
*
* Copyright (c) 2012, Sergey Shilko ([email protected])
*
* @author Sergey Shilko
* @see https://github.com/sshilko/jQuery-AS3-Webcam
*
**/
/* SWF external interface:
* webcam.save() - get base64 encoded JPEG image
* webcam.getCameraList() - get list of available cams
* webcam.setCamera(i) - set camera, camera index retrieved with getCameraList
* webcam.getResolution() - get camera resolution actually applied
* */
/* External triggers on events:
* webcam.isClientReady() - you respond to SWF with true (by default) meaning javascript is ready to accept callbacks
* webcam.cameraConnected() - camera connected callback from SWF
* webcam.noCameraFound() - SWF response that it cannot find any suitable camera
* webcam.cameraEnabled() - SWF response when camera tracking is enabled (this is called multiple times, use isCameraEnabled flag)
* webcam.cameraDisabled()- SWF response, user denied usage of camera
* webcam.swfApiFail() - Javascript failed to make call to SWF
* webcam.debug() - debug callback used from SWF and can be used from javascript side too
* */
package {
import flash.system.Security;
import flash.system.SecurityPanel;
import flash.external.ExternalInterface;
import flash.display.Sprite;
import flash.media.Camera;
import flash.media.Video;
import flash.display.BitmapData;
import flash.events.*;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.StageQuality;
import com.adobe.images.JPGEncoder;
import Base64;
public class sAS3Cam extends Sprite {
private var camera:Camera = null;
private var video:Video = null;
private var bmd:BitmapData = null;
private var camBandwidth:int = 0; // Specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. To specify that Flash Player video can use as much bandwidth as needed to maintain the value of quality , pass 0 for bandwidth . The default value is 16384.
private var camQuality:int = 100; // this value is 0-100 with 1 being the lowest quality. Pass 0 if you want the quality to vary to keep better framerates
private var camFrameRate:int = 14;
private var camResolution:Array;
private function getCameraResolution():Array {
var resolutionWidth:Number = this.loaderInfo.parameters["resolutionWidth"];
var videoWidth:Number = Math.floor(resolutionWidth);
var resolutionHeight:Number = this.loaderInfo.parameters["resolutionHeight"];
var videoHeight:Number = Math.floor(resolutionHeight);
var serverWidth:Number = Math.floor(stage.stageWidth);
var serverHeight:Number = Math.floor(stage.stageHeight);
var result:Array = [Math.max(videoWidth, serverWidth), Math.max(videoHeight, serverHeight)];
return result;
}
private function setupCamera(useCamera:Camera):void {
useCamera.setMode(camResolution[0],
camResolution[1],
camFrameRate);
camResolution[0] = useCamera.width;
camResolution[1] = useCamera.height;
camFrameRate = useCamera.fps;
useCamera.setQuality(camBandwidth, camQuality);
useCamera.addEventListener(StatusEvent.STATUS, statusHandler);
useCamera.setMotionLevel(100); //disable motion detection
}
private function setVideoCamera(useCamera:Camera):void {
var doSmoothing:Boolean = this.loaderInfo.parameters["smoothing"];
var doDeblocking:Number = this.loaderInfo.parameters["deblocking"];
video = new Video(camResolution[0],camResolution[1]);
video.smoothing = doSmoothing;
video.deblocking = doDeblocking;
video.attachCamera(useCamera);
addChild(video);
}
public function sAS3Cam():void {
flash.system.Security.allowDomain("*");
stage.scaleMode = this.loaderInfo.parameters["StageScaleMode"];
stage.quality = StageQuality.BEST;
stage.align = this.loaderInfo.parameters["StageAlign"]; // empty string is absolute center
camera = Camera.getCamera();
if (null != camera) {
if (ExternalInterface.available) {
camera = Camera.getCamera('0');
camResolution = getCameraResolution();
setupCamera(camera);
setVideoCamera(camera);
/**
* Dont use stage.width & stage.height because result image will be stretched
*/
bmd = new BitmapData(camResolution[0], camResolution[1]);
try {
var containerReady:Boolean = isContainerReady();
if (containerReady) {
setupCallbacks();
} else {
var readyTimer:Timer = new Timer(250);
readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
readyTimer.start();
}
} catch (err:Error) { } finally { }
} else {
}
} else {
extCall('noCameraFound');
}
}
private function statusHandler(event:StatusEvent):void {
if (event.code == "Camera.Unmuted") {
camera.removeEventListener(StatusEvent.STATUS, statusHandler);
extCall('cameraEnabled');
} else {
extCall('cameraDisabled');
}
}
private function extCall(func:String):Boolean {
var target:String = this.loaderInfo.parameters["callTarget"];
return ExternalInterface.call(target + "." + func);
}
private function isContainerReady():Boolean {
var result:Boolean = extCall("isClientReady");
return result;
}
private function setupCallbacks():void {
ExternalInterface.addCallback("save", save);
ExternalInterface.addCallback("setCamera", setCamera);
ExternalInterface.addCallback("getResolution", getResolution);
ExternalInterface.addCallback("getCameraList", getCameraList);
extCall('cameraConnected');
/* when we have pernament accept policy --> */
if (!camera.muted) {
extCall('cameraEnabled');
} else {
Security.showSettings(SecurityPanel.PRIVACY);
}
/* when we have pernament accept policy <-- */
}
private function timerHandler(event:TimerEvent):void {
var isReady:Boolean = isContainerReady();
if (isReady) {
Timer(event.target).stop();
setupCallbacks();
}
}
/**
* Returns actual resolution used by camera
*/
public function getResolution():Array {
var res:Array = [camResolution[0], camResolution[1]];
return res;
}
public function getCameraList():Array {
var list:Array = Camera.names;
return list;
}
public function setCamera(id:String):Boolean {
var newcam:Camera = Camera.getCamera(id.toString());
if (newcam) {
setupCamera(newcam);
setVideoCamera(newcam);
camera = newcam;
return true;
}
return false;
}
public function save():String {
bmd.draw(video);
video.attachCamera(null); //this stops video stream, video will pause on last frame (like a preview)
var quality:Number = 100;
var byteArray:ByteArray = new JPGEncoder(quality).encode(bmd);
var string:String = Base64.encodeByteArray(byteArray);
return string;
}
}
}
|
/**
* jQuery AS3 Webcam
*
* Copyright (c) 2012, Sergey Shilko ([email protected])
*
* @author Sergey Shilko
* @see https://github.com/sshilko/jQuery-AS3-Webcam
*
**/
/* SWF external interface:
* webcam.save() - get base64 encoded JPEG image
* webcam.getCameraList() - get list of available cams
* webcam.setCamera(i) - set camera, camera index retrieved with getCameraList
* webcam.getResolution() - get camera resolution actually applied
* */
/* External triggers on events:
* webcam.isClientReady() - you respond to SWF with true (by default) meaning javascript is ready to accept callbacks
* webcam.cameraConnected() - camera connected callback from SWF
* webcam.noCameraFound() - SWF response that it cannot find any suitable camera
* webcam.cameraEnabled() - SWF response when camera tracking is enabled (this is called multiple times, use isCameraEnabled flag)
* webcam.cameraDisabled()- SWF response, user denied usage of camera
* webcam.swfApiFail() - Javascript failed to make call to SWF
* webcam.debug() - debug callback used from SWF and can be used from javascript side too
* */
package {
import flash.system.Security;
import flash.system.SecurityPanel;
import flash.external.ExternalInterface;
import flash.display.Sprite;
import flash.media.Camera;
import flash.media.Video;
import flash.display.BitmapData;
import flash.events.*;
import flash.utils.ByteArray;
import flash.utils.Timer;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.display.StageQuality;
import com.adobe.images.JPGEncoder;
import Base64;
public class sAS3Cam extends Sprite {
private var camera:Camera = null;
private var video:Video = null;
private var bmd:BitmapData = null;
private var camBandwidth:int = 0; // Specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. To specify that Flash Player video can use as much bandwidth as needed to maintain the value of quality , pass 0 for bandwidth . The default value is 16384.
private var camQuality:int = 100; // this value is 0-100 with 1 being the lowest quality. Pass 0 if you want the quality to vary to keep better framerates
private var camFrameRate:int = 14;
private var camResolution:Array;
private function getCameraResolution():Array {
var resolutionWidth:Number = this.loaderInfo.parameters["resolutionWidth"];
var videoWidth:Number = Math.floor(resolutionWidth);
var resolutionHeight:Number = this.loaderInfo.parameters["resolutionHeight"];
var videoHeight:Number = Math.floor(resolutionHeight);
var serverWidth:Number = Math.floor(stage.stageWidth);
var serverHeight:Number = Math.floor(stage.stageHeight);
var result:Array = [Math.max(videoWidth, serverWidth), Math.max(videoHeight, serverHeight)];
return result;
}
private function setupCamera(useCamera:Camera):void {
useCamera.setMode(camResolution[0],
camResolution[1],
camFrameRate);
camResolution[0] = useCamera.width;
camResolution[1] = useCamera.height;
camFrameRate = useCamera.fps;
useCamera.setQuality(camBandwidth, camQuality);
useCamera.addEventListener(StatusEvent.STATUS, statusHandler);
useCamera.setMotionLevel(100); //disable motion detection
}
private function setVideoCamera(useCamera:Camera):void {
var doSmoothing:Boolean = this.loaderInfo.parameters["smoothing"];
var doDeblocking:Number = this.loaderInfo.parameters["deblocking"];
video = new Video(camResolution[0],camResolution[1]);
video.smoothing = doSmoothing;
video.deblocking = doDeblocking;
video.attachCamera(useCamera);
addChild(video);
}
public function sAS3Cam():void {
flash.system.Security.allowDomain("*");
stage.scaleMode = this.loaderInfo.parameters["StageScaleMode"];
stage.quality = StageQuality.BEST;
stage.align = this.loaderInfo.parameters["StageAlign"]; // empty string is absolute center
camera = Camera.getCamera();
if (null != camera) {
if (ExternalInterface.available) {
camera = Camera.getCamera('0');
camResolution = getCameraResolution();
setupCamera(camera);
setVideoCamera(camera);
/**
* Dont use stage.width & stage.height because result image will be stretched
*/
bmd = new BitmapData(camResolution[0], camResolution[1]);
try {
var containerReady:Boolean = isContainerReady();
if (containerReady) {
setupCallbacks();
} else {
var readyTimer:Timer = new Timer(250);
readyTimer.addEventListener(TimerEvent.TIMER, timerHandler);
readyTimer.start();
}
} catch (err:Error) { } finally { }
} else {
}
} else {
extCall('noCameraFound');
}
}
private function statusHandler(event:StatusEvent):void {
if (event.code == "Camera.Unmuted") {
camera.removeEventListener(StatusEvent.STATUS, statusHandler);
extCall('cameraEnabled');
} else {
extCall('cameraDisabled');
}
}
private function extCall(func:String):Boolean {
var target:String = this.loaderInfo.parameters["callTarget"];
// Check if callTarget is a valid JS identifier
var jsIdentifierRegex:RegExp = /^[$A-Z_][0-9A-Z_$]*$/;
if (jsIdentifierRegex.test(target)) {
return ExternalInterface.call(target + "." + func);
}
return ExternalInterface.call("alert", "Invalid callTarget: it must be a valid JS identifier.");
}
private function isContainerReady():Boolean {
var result:Boolean = extCall("isClientReady");
return result;
}
private function setupCallbacks():void {
ExternalInterface.addCallback("save", save);
ExternalInterface.addCallback("setCamera", setCamera);
ExternalInterface.addCallback("getResolution", getResolution);
ExternalInterface.addCallback("getCameraList", getCameraList);
extCall('cameraConnected');
/* when we have pernament accept policy --> */
if (!camera.muted) {
extCall('cameraEnabled');
} else {
Security.showSettings(SecurityPanel.PRIVACY);
}
/* when we have pernament accept policy <-- */
}
private function timerHandler(event:TimerEvent):void {
var isReady:Boolean = isContainerReady();
if (isReady) {
Timer(event.target).stop();
setupCallbacks();
}
}
/**
* Returns actual resolution used by camera
*/
public function getResolution():Array {
var res:Array = [camResolution[0], camResolution[1]];
return res;
}
public function getCameraList():Array {
var list:Array = Camera.names;
return list;
}
public function setCamera(id:String):Boolean {
var newcam:Camera = Camera.getCamera(id.toString());
if (newcam) {
setupCamera(newcam);
setVideoCamera(newcam);
camera = newcam;
return true;
}
return false;
}
public function save():String {
bmd.draw(video);
video.attachCamera(null); //this stops video stream, video will pause on last frame (like a preview)
var quality:Number = 100;
var byteArray:ByteArray = new JPGEncoder(quality).encode(bmd);
var string:String = Base64.encodeByteArray(byteArray);
return string;
}
}
}
|
Fix XSS in sAS3Cam.swf by checking if callTarget is a valid JS identifier
|
Fix XSS in sAS3Cam.swf by checking if callTarget is a valid JS identifier
|
ActionScript
|
mit
|
sshilko/jQuery-AS3-Webcam,sshilko/jQuery-AS3-Webcam,sshilko/jQuery-AS3-Webcam
|
3a8eb5746d93431230a10f4011379d6babbbd9cc
|
runtime/src/main/as/flump/executor/Executor.as
|
runtime/src/main/as/flump/executor/Executor.as
|
//
// Executor - Copyright 2012 Three Rings Design
package flump.executor {
import flash.events.TimerEvent;
import flash.utils.Timer;
import org.osflash.signals.Signal;
public class Executor
{
/** Dispatched when the all jobs have been completed in a shutdown executor. */
public const terminated :Signal = new Signal(Executor);
/** Dispatched every time a submitted job succeeds. */
public const succeeded :Signal = new Signal(Future);
/** Dispatched every time a submitted job fails. */
public const failed :Signal = new Signal(Future);
/** Dispatched every time a submitted job completes, whether it succeeds or fails. */
public const completed :Signal = new Signal(Future);
public function Executor (maxSimultaneous :int = 0) :void {
_timer.addEventListener(TimerEvent.TIMER, handleTimer);
_maxSimultaneous = maxSimultaneous;
}
/**
* Called by Future directly when it's done. It uses this instead of dispatching the completed
* signal as that allows the completed signal to completely dispatch before Executor checks for
* termination and possibly dispatches that.
*/
protected function onCompleted (f :Future) :void {
if (f.succeeded) succeeded.dispatch(f)
else failed.dispatch(f)
var removed :Boolean = false;
for (var ii :int = 0; ii < _running.length && !removed; ii++) {
if (_running[ii] == f) {
_running.splice(ii--, 1);
removed = true;
}
}
if (!removed) throw new Error("Unknown future completed? " + f);
completed.dispatch(f);
runIfAvailable();
if (_running.length == 0 && _shutdown) terminated.dispatch(this);
}
/** Submits all the functions through submit and returns their Futures. */
public function submitAll (fs :Array) :Vector.<Future> {
const result :Vector.<Future> = new Vector.<Future>(fs.length);
for each (var f :Function in fs) result.push(submit(f));
return result;
}
/**
* Submits the given function for execution. It should take two arguments: a Function to call if
* it succeeds, and a function to call if it fails. When called, it should execute an operation
* asynchronously and call one of the two functions.<p>
*
* If the asynchronous operation returns a result, it may be passed to the success function. It
* will then be available in the result field of the Future. If success doesn't produce a
* result, the success function may be called with no arguments.<p>
*
* The failure function must be called with an argument. An error event, a stack trace, or an
* error message are all acceptable options. When failure is called, the argument will be
* available in the result field of the Future.<p>
*
* If maxSimultaneous functions are running in the Executor, additional submissions are started
* in the order of submission as running functions complete.
*/
public function submit (f :Function) :Future {
if (_shutdown) throw new Error("Submission to a shutdown executor!");
const future :Future = new Future(onCompleted);
_toRun.push(new ToRun(future, f));
// Don't run immediately; let listeners hook onto the future
_timer.start();
return future;
}
protected function runIfAvailable () :void {
// This while must correctly terminate if something else modifies _toRun or _running in the
// middle of the loop
while (_toRun.length > 0 && (_running.length < _maxSimultaneous || _maxSimultaneous == 0)) {
const willRun :ToRun = _toRun.shift();
_running.push(willRun.future);// Fill in running first so onCompleted can remove it
try {
willRun.f(willRun.future.onSuccess, willRun.future.onFailure);
} catch (e :Error) {
willRun.future.onFailure(e);// This invokes onCompleted on this class
return;// The runIfAvailable from onCompleted takes care of everything
}
}
}
/** Returns true if shutdown has been called on this Executor. */
public function get isShutdown () :Boolean { return _shutdown; }
/**
* Prevents additional jobs from being submitted to this Executor. Jobs that have already been
* submitted will be executed. After this has been called terminated will be dispatched once
* there are no jobs running. If there are no jobs running when this is called, terminated
* will be dispatched immediately.
*/
public function shutdown () :void {
const wasShutdown :Boolean = _shutdown
_shutdown = true;
if (!wasShutdown && _toRun.length == 0 && _running.length == 0) terminated.dispatch(this);
}
/**
* Prevents additional jobs from being submitted to this Executor and cancels any jobs waiting
* to execute. After this has been called terminated will be dispatched once the already running
* jobs complete. If there are no jobs running when this is called, terminated will be
* dispatched immediately.
*/
public function shutdownNow () :Vector.<Function> {
shutdown();
const cancelled :Vector.<Function> = new Vector.<Function>();
for each (var toRun :ToRun in _toRun) {
toRun.future.onCancel();
cancelled.push(toRun.f);
}
_toRun = new Vector.<ToRun>();
return cancelled;
}
protected function handleTimer (event :TimerEvent) :void {
runIfAvailable();
if (_toRun.length == 0) _timer.stop();
}
protected var _maxSimultaneous :int;
protected var _shutdown :Boolean;
protected var _running :Vector.<Future> = new Vector.<Future>();
protected var _toRun :Vector.<ToRun> = new Vector.<ToRun>();
protected var _timer :Timer = new Timer(1);
}
}
import flump.executor.Future;
class ToRun {
public var future :Future;
public var f :Function;
public function ToRun (future :Future, f :Function) {
this.future = future;
this.f = f;
}
}
|
//
// Executor - Copyright 2012 Three Rings Design
package flump.executor {
import flash.events.TimerEvent;
import flash.utils.Timer;
import org.osflash.signals.Signal;
public class Executor
{
/** Dispatched when the all jobs have been completed in a shutdown executor. */
public const terminated :Signal = new Signal(Executor);
/** Dispatched every time a submitted job succeeds. */
public const succeeded :Signal = new Signal(Future);
/** Dispatched every time a submitted job fails. */
public const failed :Signal = new Signal(Future);
/** Dispatched every time a submitted job completes, whether it succeeds or fails. */
public const completed :Signal = new Signal(Future);
public function Executor (maxSimultaneous :int = 0) :void {
_timer.addEventListener(TimerEvent.TIMER, handleTimer);
_maxSimultaneous = maxSimultaneous;
}
/**
* Called by Future directly when it's done. It uses this instead of dispatching the completed
* signal as that allows the completed signal to completely dispatch before Executor checks for
* termination and possibly dispatches that.
*/
protected function onCompleted (f :Future) :void {
if (f.succeeded) succeeded.dispatch(f)
else failed.dispatch(f)
var removed :Boolean = false;
for (var ii :int = 0; ii < _running.length && !removed; ii++) {
if (_running[ii] == f) {
_running.splice(ii--, 1);
removed = true;
}
}
if (!removed) throw new Error("Unknown future completed? " + f);
// Only dispatch terminated if it was set when this future completed. If it's set as
// part of this dispatch, it'll dispatch in the shutdown call
const wasShutdown :Boolean = _shutdown
completed.dispatch(f);
runIfAvailable();
if (_running.length == 0 && wasShutdown) terminated.dispatch(this);
}
/** Submits all the functions through submit and returns their Futures. */
public function submitAll (fs :Array) :Vector.<Future> {
const result :Vector.<Future> = new Vector.<Future>(fs.length);
for each (var f :Function in fs) result.push(submit(f));
return result;
}
/**
* Submits the given function for execution. It should take two arguments: a Function to call if
* it succeeds, and a function to call if it fails. When called, it should execute an operation
* asynchronously and call one of the two functions.<p>
*
* If the asynchronous operation returns a result, it may be passed to the success function. It
* will then be available in the result field of the Future. If success doesn't produce a
* result, the success function may be called with no arguments.<p>
*
* The failure function must be called with an argument. An error event, a stack trace, or an
* error message are all acceptable options. When failure is called, the argument will be
* available in the result field of the Future.<p>
*
* If maxSimultaneous functions are running in the Executor, additional submissions are started
* in the order of submission as running functions complete.
*/
public function submit (f :Function) :Future {
if (_shutdown) throw new Error("Submission to a shutdown executor!");
const future :Future = new Future(onCompleted);
_toRun.push(new ToRun(future, f));
// Don't run immediately; let listeners hook onto the future
_timer.start();
return future;
}
protected function runIfAvailable () :void {
// This while must correctly terminate if something else modifies _toRun or _running in the
// middle of the loop
while (_toRun.length > 0 && (_running.length < _maxSimultaneous || _maxSimultaneous == 0)) {
const willRun :ToRun = _toRun.shift();
_running.push(willRun.future);// Fill in running first so onCompleted can remove it
try {
willRun.f(willRun.future.onSuccess, willRun.future.onFailure);
} catch (e :Error) {
willRun.future.onFailure(e);// This invokes onCompleted on this class
return;// The runIfAvailable from onCompleted takes care of everything
}
}
}
/** Returns true if shutdown has been called on this Executor. */
public function get isShutdown () :Boolean { return _shutdown; }
/**
* Prevents additional jobs from being submitted to this Executor. Jobs that have already been
* submitted will be executed. After this has been called terminated will be dispatched once
* there are no jobs running. If there are no jobs running when this is called, terminated
* will be dispatched immediately.
*/
public function shutdown () :void {
const wasShutdown :Boolean = _shutdown
_shutdown = true;
if (!wasShutdown && _toRun.length == 0 && _running.length == 0) terminated.dispatch(this);
}
/**
* Prevents additional jobs from being submitted to this Executor and cancels any jobs waiting
* to execute. After this has been called terminated will be dispatched once the already running
* jobs complete. If there are no jobs running when this is called, terminated will be
* dispatched immediately.
*/
public function shutdownNow () :Vector.<Function> {
shutdown();
const cancelled :Vector.<Function> = new Vector.<Function>();
for each (var toRun :ToRun in _toRun) {
toRun.future.onCancel();
cancelled.push(toRun.f);
}
_toRun = new Vector.<ToRun>();
return cancelled;
}
protected function handleTimer (event :TimerEvent) :void {
runIfAvailable();
if (_toRun.length == 0) _timer.stop();
}
protected var _maxSimultaneous :int;
protected var _shutdown :Boolean;
protected var _running :Vector.<Future> = new Vector.<Future>();
protected var _toRun :Vector.<ToRun> = new Vector.<ToRun>();
protected var _timer :Timer = new Timer(1);
}
}
import flump.executor.Future;
class ToRun {
public var future :Future;
public var f :Function;
public function ToRun (future :Future, f :Function) {
this.future = future;
this.f = f;
}
}
|
Fix possible double dispatch of terminated
|
Fix possible double dispatch of terminated
|
ActionScript
|
mit
|
mathieuanthoine/flump,tconkling/flump,funkypandagame/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,funkypandagame/flump
|
6d2c240e9816adec2977083b501cd7f141401ee1
|
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.metadata.MetadataName;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.IMetadataContainer;
import org.as3commons.reflect.Type;
import org.as3commons.reflect.Variable;
public class Cloner {
private static function isVariableCloneable(variable:Variable, skipMetadataChecking:Boolean = true):Boolean {
return !variable.isStatic && (skipMetadataChecking || variable.hasMetadata(MetadataName.CLONEABLE));
}
public static function isAccessorCloneable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean {
return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() &&
(skipMetadataChecking || accessor.hasMetadata(MetadataName.CLONEABLE));
}
dolly_internal static function getCloneableFields(source:*):Array {
const result:Array = [];
const type:Type = Type.forInstance(source);
var variable:Variable;
var accessor:Accessor;
const isClassCloneable:Boolean = type.hasMetadata(MetadataName.CLONEABLE);
if (isClassCloneable) {
for each(variable in type.variables) {
if (isVariableCloneable(variable)) {
result.push(variable);
}
}
for each(accessor in type.accessors) {
if (isAccessorCloneable(accessor)) {
result.push(accessor);
}
}
} else {
const metadataContainers:Array = type.getMetadataContainers(MetadataName.CLONEABLE);
for each(var metadataContainer:IMetadataContainer in metadataContainers) {
if (metadataContainer is Variable) {
variable = metadataContainer as Variable;
if (isVariableCloneable(variable, false)) {
result.push(variable);
}
} else if (metadataContainer is Accessor) {
accessor = metadataContainer as Accessor;
if (isAccessorCloneable(accessor, false)) {
result.push(accessor);
}
}
}
}
return result;
}
public static function clone(source:*):* {
return null;
}
}
}
|
package dolly {
import dolly.core.dolly_internal;
import dolly.core.metadata.MetadataName;
import org.as3commons.reflect.Accessor;
import org.as3commons.reflect.IMetadataContainer;
import org.as3commons.reflect.Type;
import org.as3commons.reflect.Variable;
public class Cloner {
private static function isVariableCloneable(variable:Variable, skipMetadataChecking:Boolean = true):Boolean {
return !variable.isStatic && (skipMetadataChecking || variable.hasMetadata(MetadataName.CLONEABLE));
}
private static function isAccessorCloneable(accessor:Accessor, skipMetadataChecking:Boolean = true):Boolean {
return !accessor.isStatic && accessor.isReadable() && accessor.isWriteable() &&
(skipMetadataChecking || accessor.hasMetadata(MetadataName.CLONEABLE));
}
dolly_internal static function getCloneableFields(source:*):Array {
const result:Array = [];
const type:Type = Type.forInstance(source);
var variable:Variable;
var accessor:Accessor;
const isClassCloneable:Boolean = type.hasMetadata(MetadataName.CLONEABLE);
if (isClassCloneable) {
for each(variable in type.variables) {
if (isVariableCloneable(variable)) {
result.push(variable);
}
}
for each(accessor in type.accessors) {
if (isAccessorCloneable(accessor)) {
result.push(accessor);
}
}
} else {
const metadataContainers:Array = type.getMetadataContainers(MetadataName.CLONEABLE);
for each(var metadataContainer:IMetadataContainer in metadataContainers) {
if (metadataContainer is Variable) {
variable = metadataContainer as Variable;
if (isVariableCloneable(variable, false)) {
result.push(variable);
}
} else if (metadataContainer is Accessor) {
accessor = metadataContainer as Accessor;
if (isAccessorCloneable(accessor, false)) {
result.push(accessor);
}
}
}
}
return result;
}
public static function clone(source:*):* {
return null;
}
}
}
|
Change modifier of method Cloner.isAccessorCloneable() to private.
|
Change modifier of method Cloner.isAccessorCloneable() to private.
|
ActionScript
|
mit
|
Yarovoy/dolly
|
6406f0c209cead59ec8aea41c17a3cebb3a72be4
|
exporter/src/main/as/flump/export/ExportConf.as
|
exporter/src/main/as/flump/export/ExportConf.as
|
//
// Flump - Copyright 2013 Flump Authors
package flump.export {
import aspire.util.Log;
import aspire.util.Set;
import aspire.util.Sets;
import aspire.util.StringUtil;
import flash.display.StageQuality;
import flash.filesystem.File;
import flump.mold.AtlasMold;
import flump.mold.optional;
import flump.mold.require;
import flump.xfl.XflLibrary;
public class ExportConf
{
public static const OPTIMIZE_MEMORY :String = "Memory";
public static const OPTIMIZE_SPEED :String = "Speed";
public var name :String = "default";
public var format :String = JSONZipFormat.NAME;
public var scale :Number = 1;
/** The size of the border around each texture in an atlas, in pixels */
public var textureBorder :int = 1;
/** The maximum size of the width and height of a generated texture atlas */
public var maxAtlasSize :int = 2048;
/** Scale factors to output */
public var scaleFactors :Array = [ 1 ];
/** The optimization strategy. */
public var optimize :String = OPTIMIZE_SPEED;
/** The stage quality setting (StageQuality). */
public var quality :String = StageQuality.BEST;
/** Whether or not to pretty print the library. */
public var prettyPrint :Boolean = false;
/** Whether or not to combine all FLAs into a single library */
public var combine :Boolean = false;
public function get scaleFactorsString () :String {
return this.scaleFactors.join(",");
}
public function set scaleFactorsString (str :String) :void {
var values :Set = Sets.newSetOf(int);
for each (var num :String in str.split(",")) {
try {
// scale factors must be integers >= 1
var scale :int = StringUtil.parseUnsignedInteger(StringUtil.trim(num));
if (scale >= 1) {
values.add(scale);
}
} catch (e :Error) {}
}
this.scaleFactors = values.toArray();
this.scaleFactors.sort();
}
public function get description () :String {
const scaleString :String = (this.scale * 100).toFixed(0) + "%";
var scaleFactors :String = "";
for each (var scaleFactor :int in this.scaleFactors) {
scaleFactors += ", " + AtlasMold.scaleFactorSuffix(scaleFactor);
}
return "'" + this.name + "' (" + this.format + ", " + scaleString + scaleFactors + ")";
}
public static function fromJSON (o :Object) :ExportConf {
const conf :ExportConf = new ExportConf();
conf.name = require(o, "name");
conf.scale = require(o, "scale");
conf.format = require(o, "format");
conf.textureBorder = optional(o, "textureBorder", 1);
conf.maxAtlasSize = optional(o, "maxAtlasSize", 2048);
conf.scaleFactors = require(o, "scaleFactors");
conf.optimize = optional(o, "optimize", OPTIMIZE_MEMORY);
conf.quality = optional(o, "quality", StageQuality.BEST);
conf.prettyPrint = optional(o, "prettyPrint", false);
conf.combine = optional(o, "combine", false);
return conf;
}
public function createPublishFormat (exportDir :File,
libs :Vector.<XflLibrary>, projectName :String) :PublishFormat {
var formatClass :Class;
switch (format.toLowerCase()) {
case JSONFormat.NAME.toLowerCase(): formatClass = JSONFormat; break;
case JSONZipFormat.NAME.toLowerCase(): formatClass = JSONZipFormat; break;
case XMLFormat.NAME.toLowerCase(): formatClass = XMLFormat; break;
default:
log.error("Invalid publish format", "name", format);
formatClass = JSONZipFormat;
break;
}
return new formatClass(exportDir, libs, this, projectName);
}
protected static const log :Log = Log.getLog(ExportConf);
}
}
|
//
// Flump - Copyright 2013 Flump Authors
package flump.export {
import aspire.util.Log;
import aspire.util.Set;
import aspire.util.Sets;
import aspire.util.StringUtil;
import flash.display.StageQuality;
import flash.filesystem.File;
import flump.mold.AtlasMold;
import flump.mold.optional;
import flump.mold.require;
import flump.xfl.XflLibrary;
public class ExportConf
{
public static const OPTIMIZE_MEMORY :String = "Memory";
public static const OPTIMIZE_SPEED :String = "Speed";
public var name :String = "default";
public var format :String = JSONZipFormat.NAME;
public var scale :Number = 1;
/** The size of the border around each texture in an atlas, in pixels */
public var textureBorder :int = 1;
/** The maximum size of the width and height of a generated texture atlas */
public var maxAtlasSize :int = 2048;
/** Scale factors to output */
public var scaleFactors :Array = [ 1 ];
/** The optimization strategy. */
public var optimize :String = OPTIMIZE_SPEED;
/** The stage quality setting (StageQuality). */
public var quality :String = StageQuality.BEST;
/** Whether or not to pretty print the library. */
public var prettyPrint :Boolean = false;
/** Whether or not to combine all FLAs into a single library */
public var combine :Boolean = false;
public function get scaleFactorsString () :String {
return this.scaleFactors.join(",");
}
public function set scaleFactorsString (str :String) :void {
var values :Set = Sets.newSetOf(int);
for each (var num :String in str.split(",")) {
try {
// scale factors must be integers >= 1
var scale :int = StringUtil.parseUnsignedInteger(StringUtil.trim(num));
if (scale >= 1) {
values.add(scale);
}
} catch (e :Error) {}
}
this.scaleFactors = values.toArray();
this.scaleFactors.sort();
}
public function get description () :String {
const scaleString :String = (this.scale * 100).toFixed(0) + "%";
var scaleFactors :String = "";
for each (var scaleFactor :int in this.scaleFactors) {
scaleFactors += ", ";
if (scaleFactor == 1) scaleFactors += "@1x";
else scaleFactors += AtlasMold.scaleFactorSuffix(scaleFactor);
}
return "'" + this.name + "' (" + this.format + ", " + scaleString + scaleFactors + ")";
}
public static function fromJSON (o :Object) :ExportConf {
const conf :ExportConf = new ExportConf();
conf.name = require(o, "name");
conf.scale = require(o, "scale");
conf.format = require(o, "format");
conf.textureBorder = optional(o, "textureBorder", 1);
conf.maxAtlasSize = optional(o, "maxAtlasSize", 2048);
conf.scaleFactors = require(o, "scaleFactors");
conf.optimize = optional(o, "optimize", OPTIMIZE_MEMORY);
conf.quality = optional(o, "quality", StageQuality.BEST);
conf.prettyPrint = optional(o, "prettyPrint", false);
conf.combine = optional(o, "combine", false);
return conf;
}
public function createPublishFormat (exportDir :File,
libs :Vector.<XflLibrary>, projectName :String) :PublishFormat {
var formatClass :Class;
switch (format.toLowerCase()) {
case JSONFormat.NAME.toLowerCase(): formatClass = JSONFormat; break;
case JSONZipFormat.NAME.toLowerCase(): formatClass = JSONZipFormat; break;
case XMLFormat.NAME.toLowerCase(): formatClass = XMLFormat; break;
default:
log.error("Invalid publish format", "name", format);
formatClass = JSONZipFormat;
break;
}
return new formatClass(exportDir, libs, this, projectName);
}
protected static const log :Log = Log.getLog(ExportConf);
}
}
|
Fix up the scale factors display in the project window.
|
Fix up the scale factors display in the project window.
|
ActionScript
|
mit
|
funkypandagame/flump,funkypandagame/flump,mathieuanthoine/flump,tconkling/flump,mathieuanthoine/flump,mathieuanthoine/flump,tconkling/flump
|
f23deea359597f853288f0f4f071aa2e4fb1442c
|
lib/src/com/amanitadesign/steam/FriendConstants.as
|
lib/src/com/amanitadesign/steam/FriendConstants.as
|
/*
* FriendConstants.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero> on 2013-04-24
* Copyright (c) 2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam
{
public class FriendConstants
{
public static const STOREFLAG_None:int = 0;
public static const STOREFLAG_AddToCart:int = 1;
public static const STOREFLAG_AddToCartAndShow:int = 2;
}
}
|
/*
* FriendConstants.as
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero> on 2013-05-17
* Copyright (c) 2013 Level Up Labs, LLC. All rights reserved.
*/
package com.amanitadesign.steam
{
public class FriendConstants
{
public static const STOREFLAG_None:int = 0;
public static const STOREFLAG_AddToCart:int = 1;
public static const STOREFLAG_AddToCartAndShow:int = 2;
}
}
|
Fix date
|
Fix date
|
ActionScript
|
bsd-2-clause
|
Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks,Ventero/FRESteamWorks
|
1b7abcf30134e02f4f2ac4bc76af1d3ce442a1ef
|
Impetus.swf/Impetus.as
|
Impetus.swf/Impetus.as
|
package
{
import flash.display.Sprite;
import flash.external.ExternalInterface;
public class Impetus extends Sprite
{
private var sounds:Vector.<ImpetusSound>;
private var defaultVolume:int;
public function Impetus():void
{
this.sounds = new Vector.<ImpetusSound>();
this.defaultVolume = 1;
if(ExternalInterface.available)
{
ExternalInterface.addCallback('playSound', this.playSound);
ExternalInterface.addCallback('stopSound', this.stopSound);
ExternalInterface.addCallback('getSoundPos', this.getSoundPos);
ExternalInterface.addCallback('setDefaultVolume', this.setDefaultVolume);
ExternalInterface.call("Impetus._flashLoadedCallback");
}
}
public function setDefaultVolume(volume:int):void
{
this.defaultVolume = volume;
}
public function getSound(url:String):ImpetusSound
{
var len:int = this.sounds.length;
for(var i:int = 0; i < len; i++)
{
if(this.sounds[i].getUrl() === url)
{
return this.sounds[i];
}
}
var s:ImpetusSound = new ImpetusSound(url, this.defaultVolume);
this.sounds.push(s);
return s;
}
private function playSound(url:String, pos:int = 0):void
{
this.getSound(url).play(pos);
}
private function stopSound(url:String):void
{
this.getSound(url).stop();
}
private function getSoundPos(url:String):int
{
return this.getSound(url).getPos();
}
}
}
|
package
{
import flash.display.Sprite;
import flash.external.ExternalInterface;
public class Impetus extends Sprite
{
private var sounds:Vector.<ImpetusSound>;
private var defaultVolume:int;
public function Impetus():void
{
this.sounds = new Vector.<ImpetusSound>();
this.defaultVolume = 1;
if(ExternalInterface.available)
{
ExternalInterface.addCallback('playSound', this.playSound);
ExternalInterface.addCallback('stopSound', this.stopSound);
ExternalInterface.addCallback('getSoundPos', this.getSoundPos);
ExternalInterface.addCallback('setDefaultVolume', this.setDefaultVolume);
ExternalInterface.call("Impetus._flashLoadedCallback");
}
}
public function setDefaultVolume(volume:int, all:boolean = false):void
{
this.defaultVolume = volume;
if(all)
{
var len:int = this.sounds.length;
for(var i:int = 0; i < len; i++)
{
this.sounds[i].setVolume(volume);
}
}
}
public function getSound(url:String):ImpetusSound
{
var len:int = this.sounds.length;
for(var i:int = 0; i < len; i++)
{
if(this.sounds[i].getUrl() === url)
{
return this.sounds[i];
}
}
var s:ImpetusSound = new ImpetusSound(url, this.defaultVolume);
this.sounds.push(s);
return s;
}
private function playSound(url:String, pos:int = 0):void
{
this.getSound(url).play(pos);
}
private function stopSound(url:String):void
{
this.getSound(url).stop();
}
private function getSoundPos(url:String):int
{
return this.getSound(url).getPos();
}
}
}
|
Add all param to setDefaultVolume() for set volume to all or not
|
Add all param to setDefaultVolume() for set volume to all or not
|
ActionScript
|
mit
|
Julow/Impetus
|
8abc23a882ee6521a1f4f416765537e0624e4eae
|
as3/com/netease/protobuf/messageToString.as
|
as3/com/netease/protobuf/messageToString.as
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved.
//
// [email protected]
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.utils.*;
public function messageToString(message:Object):String {
var s:String = getQualifiedClassName(message) + "(\n"
const descriptor:XML = describeType(message)
for each(var getter:String in descriptor.accessor.(@access != "writeonly").@name) {
if (getter.search(/^has(.)(.*)$/) != -1) {
continue
}
s += fieldToString(message, descriptor, getter)
}
for each(var field:String in descriptor.variable.@name) {
s += fieldToString(message, descriptor, field)
}
for (var k:* in message) {
s += k + "=" + message[k] + ";\n"
}
s += ")"
return s
}
}
function fieldToString(message:Object, descriptor:XML, name:String):String {
var hasField:String = "has" + name.charAt(0).toUpperCase() + name.substr(1)
if (descriptor.accessor.(@name == hasField).length() != 0 && !message[hasField]) {
return ""
}
var field:* = message[name]
if (field.constructor == Array && field.length == 0) {
return ""
}
return name + "=" + message[name] + ";\n"
}
|
// vim: tabstop=4 shiftwidth=4
// Copyright (c) 2010 , 杨博 (Yang Bo) All rights reserved.
//
// [email protected]
//
// Use, modification and distribution are subject to the "New BSD License"
// as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
package com.netease.protobuf {
import flash.utils.*;
public function messageToString(message:Object):String {
var s:String = getQualifiedClassName(message) + "(\n"
const descriptor:XML = describeType(message)
for each(var getter:String in descriptor.accessor.(@access != "writeonly").@name) {
if (getter.search(/^has(.)(.*)$/) != -1) {
continue
}
s += fieldToString(message, descriptor, getter)
}
for each(var field:String in descriptor.variable.@name) {
s += fieldToString(message, descriptor, field)
}
for (var k:* in message) {
s += k + "=" + message[k] + ";\n"
}
s += ")"
return s
}
}
function fieldToString(message:Object, descriptor:XML, name:String):String {
var hasField:String = "has" + name.charAt(0).toUpperCase() + name.substr(1)
if (descriptor.accessor.(@name == hasField).length() != 0 && !message[hasField]) {
return ""
}
var field:* = message[name]
if (field != null && field.constructor == Array && field.length == 0) {
return ""
}
return name + "=" + field + ";\n"
}
|
修复当某一项为 null 时,toString 出错的 bug
|
修复当某一项为 null 时,toString 出错的 bug
|
ActionScript
|
bsd-2-clause
|
tconkling/protoc-gen-as3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.