Polski:Zasoby

Przegląd
Innym typem noda w site.xml są załączniki (assets). Załączniki należą do stron, i są zewnętrznymi plikami które są powiązane ze stronami do których należą. Dzięki gaia zarządzanie załącznikami jest proste.

Załączniki AS2 i AS3

 * NetStreamAsset - plik flv lub m4a
 * XMLAsset       - plik XML
 * SoundAsset     - plik mp3 lub wav
 * StyleSheetAsset - pliki css

AS3 Assets
These mirror the AS3 DisplayObject inheritance tree.
 * DisplayObjectAsset - załącznik DisplayObject
 * BitmapAsset       - obrazki będą załadowane domyąlnie jako  BitmapAssets (png, jpg, gif, itp.)
 * BitmapSpriteAsset -bitmapa która została osadzona w obiekcie Sprite
 * SpriteAsset       -sprite
 * MovieClipAsset    - domyślnie każdy swf załaduje się jako MovieClipAssets.
 * TextAsset         - dla plików .txt i jako bazowa klasa dla XMLAsset, StyleSheetAsset i JSONAsset
 * JSONAsset         - dla pliku tekstowego w formacie JSON ( rozszerzenie  .json )

AS2 Assets

 * MovieClipAsset - wszystko co zostanie załadowane do MovieClip (swf, png, jpg, gif, etc.)
 * SoundClipAsset - Zewnętrzne pliki z dźwiękami (dla uzyskania idealnych pętli )



Jak używać załączników
Domyślnie załączniki są załadowane razem ze stroną jako część procesu wczytywania (preload). To zachowanie można nadpisać.

'''***UWAGA ! DOSTĘP DO ZASOBÓW***'''

Obiekt assets jest dostępny dopiero po wywołaniu zdarzenia transitionIn. Dlatego należy zapamiętać że w pierwszej klatce występuje proces wczytywania załączników i w tym miejscu nie są one dostępne do momentu wywołania transitionIn.

Poniżej szybki przegląd jak używać załączników.

       

W tym przykładzie strona ma cztery załączniki ( assets) o id: myMusic, myCopy myImage i mySWF. Załączniki są dostępne w stronie w obiekcie "assets" w klasie dokumentu albo w root timeline pliku swf.

Do konkretnego załącznika można dostać się używając jako klucza jego id np: assets['mySWF']. Metody konkretnego załącznika są dostępne bezpośrednio dzięki wzorcowi Proxy.

'''Notatka: Obrazki i pliki swf mają domyślnie ustawioną wartość visible na false i znajdują się w pozycji 0,0. Dlatego aby obrazek pokazał się na scenie należy ustawić mu własność visible na true.'''



MovieClipAsset
Do obiektu MovieClipAsset można się odwołać bezpośrednio po takich samych właściwościach i metodach jak do MovieClip.

Poniżej przykład.

AS2 assets.myImage._x = 50; assets.myImage._y = 100; assets.myImage._visible = true; trace(assets.myImage._parent);  // zwraca _parent MovieClip // assets.mySWF.gotoAndPlay(10); assets.mySWF.onRelease = function {};

AS3 nie wymaga typowania, ale jeżeli chcesz używać typowania dla autopodpowiedzi oraz zwiększenia wydajności, typuj assety do ich interfasju. MovieClipAssets używa IMovieClip, images IBitmap, sprites ISprite, wszystkie dziedziczą po IDisplayObject. Ważną informacją jest żę własność parent zwróci rodzica (parent) loadera a nie kontent.

AS3 IDisplayObject(assets.myImage).x = 50; IDisplayObject(assets.myImage).y = 100; IDisplayObject(assets.myImage).visible = true; // IMovieClip(assets.mySWF).gotoAndPlay(10); trace(IMovieClip(assets.mySWF).parent); // zwraca rodzica loadera, a nie loader.content // // AS3 działa także bez typowania // assets.mySWF.gotoAndStop(5); assets.myImage.scaleX = 0.5; trace(assets.myImage.parent); // BitmapSpriteAsset.parent zwraca rodzica Sprita

W AS3, gdy rozmiar pliku ma znaczenie można użyć interfajsu najbliższego do IAsset. Dla przykładu, gdy potrzeba tylko właściwości x i y, należy użyć IDisplayObject.

Targeting the timeline of MovieClipAssets
Gdy asset zawiera dodatkowe włąściwości lub metody należy odnieść się do tego assetu bezpośrednio. Można tego dokonać używając właściwości "content" która zwróci MovieClip.

AS2 assets.mySWF.content.someMethod assets.mySWF.content.someMovieClip._x = 10;

W AS3, można typować MovieClipAsset jako IMovieClip albo i nie.

AS3 assets.mySWF.content.someMethod; IMovieClip(assets.mySWF).content.someMovieClip.x = 10;

To samo dotyczy Stron (Page) (PageAsset extends MovieClipAsset).

AS2 Gaia.api.getPage("index/nav").content.someMovieClip._visible = true;

albo

_global.Gaia.getPage("index/nav").content.someMovieClip._visible = true;

AS3 Gaia.api.getPage("index/nav").content.someMovieClip.visible = true;



BitmapAsset (AS3 only)
BitmapAsset dziedziczy po DisplayObjectAsset. W AS3, każdy obrazek ustawiony w site.xml, np: jpg, gif, lub png, będzie załadowany jako BitmapAssets.

import com.gaiaframework.api.IBitmap; import flash.display.BitmapData; // IBitmap(assets.myBitmap).x = 50; var myBitmapData:BitmapData = IBitmap(assets.myImage).bitmapData;



BitmapSpriteAsset ( tylkoAS3 )
Ten asset bazuje na BitmapAsset z tą różnicą że wczytana bitmapa jest umieszczona w obiekcie Sprite. BitmapSpriteAsset dostarcza proxy do wszystkich metod i właściwości Sprite. Należy ustawić type="sprite" w nodzie asset aby zamienić BitmapAsset w BitmapSpriteAsset.

import com.gaiaframework.api.IBitmapSprite; // IBitmapSprite(assets.myBitmap).buttonMode = true; IBitmapSprite(assets.myBitmap).addEventListener(MouseEvent.CLICK, onClickBitmap);



SpriteAsset (AS3 only)
SpriteAsset dziedziczy po DisplayObjectAsset. Interfejs ISprite zajmuje mniej miejsca niż IMovieClip.

container
SpriteAsset posiada właściwość container która zawiera loader MovieClipAssets. W takich przypadkach najczęściej należy wykorzystać IBitmapSprite (który rozszeża ISprite).

import com.gaiaframework.api.IBitmapSprite // TweenLite.to(IBitmapSprite(assets.myBitmap).container, 2, {alpha:0});



SoundAsset
SoundAsset ma te same metody co obiekt Sound we Flashu.

Dla przykładu gdy załącznikiem (assetem) jest plik mp3, należy go uruchomić tak jak w poniższym przykładzie.

AS2 assets.myMusic.start; assets.myMusic.start(4, 5); // w przypadku uruchomienia od 4 sekundy w pętli 5 razy

AS3 używa interfajsu ISound.

AS3 ISound(assets.myMusic).play; ISound(assets.myMusic).play(4, 5); // w przypadku uruchomienia od 4 sekundy w pętli 5 razy

W przypadku muzyki wysłanej w postaci strumienia należy w atrybucie asseta ( w pliku site.xml) dodać "streaming=true". Powinno się też ustawić atrybut "preload" na wartość "false"

W AS3 atrybut streaming jest nie wykorzystywany i wszystkie dźwięki są traktowane jak strumień. Jeżeli ustawiono flagę preload na true, Gaia załaduje cały dźwięk jako fragment strony. Natomiast uruchomienie dźwięku nastąpi ręcznie po wywołaniu metody play.

Finalnie Gaia naprawiła błąd w AS2 w ograniczeniu zapętlania dźwięków wysyłanych jako strumień ( uruchomienie tej opcji następuje po ustawieniu flagi loops) więcej na ten temat można przeczytać w dzialeLoad On Demand.

SoundAsset posiada trzy metody pomocnicze:

pause
pause(flag:Boolean) flag:True pauzuje utwór, flag: False

fadeTo
fadeTo(value:Number, duration:Number, [onComplete:Function]) // AS2 fadeTo(value:Number, duration:Number, onComplete:Function = null) // AS3 Value to docelowa głośność dźwięku, duration to czas w sekundach całej operacji, na koniec opcjonalnie można przekazać nazwę funkcji która ma być wykonana po zakończeniu fada.

panTo
panTo(value:Number, duration:Number, [onComplete:Function]) // AS2 panTo(value:Number, duration:Number, onComplete:Function = null) // AS3

Value wartość pozycji pan (-100 do 100 w AS2, -1 do 1 in AS3), duration czas w sekundach całej operacji, na koniec opcjonalnie można przekazać nazwę funkcji która ma być wykonana po zakończeniu fada.



SoundClipAsset (AS2 only)
A SoundClipAsset is nearly identical to a SoundAsset, and has most of the same native methods as the Sound Asset. SoundClipAssets are primarily used for mp3 files which you need to be perfectly looped.

To create a SoundClipAsset for Gaia, first, you create a new Flash file and import your audio file. Give your audio file any linkage ID you like and put the following code in the timeline.

sound = new Sound(this); sound.attachSound("YOUR_LINKAGE_ID");

In your site.xml, you will need to set the asset type attribute to "soundclip". Example:



That's all you need to do and Gaia does the rest.

SoundClipAssets behave just like SoundAssets with the exception that they cannot be set to streaming. Other than that, you access them exactly the same as normal Sound Assets. You can add them to SoundGroups, as well.

<br style="clear:both" />

NetStreamAsset
NetStreamAssets have all of the methods available to the NetStream class available to them. A NetStreamAsset also has a property "ns" which is the reference to the NetStream instance itself.

In AS3, NetStreamAssets use the INetStream interface.

INetStream(assets.myFLV).play; INetStream(assets.myFLV).attach(video);

In both AS2 and AS3, NetStreamAssets have two convenience properties and one method.

duration
get duration:Number Returns the duration of a loaded NetStreamAsset, extracted from the metaData.

metaData
get metaData:Object Returns the metaData object of a loaded NetStreamAsset.

attach
attach(video:Video) This helper method lets you pass a video instance to attach and Gaia handles attaching the NetStream to the Video.

In AS3 only, NetStreamAssets have four additional convenience properties/methods.

volume (AS3 only)
get volume:Number set volume(value:Number):void This setter property accesses the volume on the NetStreamAsset, a floating point value from 0 to 1.

pan (AS3 only)
get pan:Number set pan(value:Number):void This getter/setter property accesses the pan on the NetStreamAsset, a floating point value from -1 to 1.

fadeTo (AS3 only)
fadeTo(value:Number, duration:Number, onComplete:Function = null) Value is the volume you want to fade to, duration is the number of seconds for the fade, and you can optionally pass a function to be called when the fade is complete.

panTo (AS3 only)
panTo(value:Number, duration:Number, onComplete:Function = null) Value is the pan value you want to pan to (-100 to 100 in AS2, -1 to 1 in AS3), duration is the number of seconds for the pan, and you can optionally pass a function to be called when the pan is complete.

<br style="clear:both" />

NetStreamAssetEvent
NetStreamAsset also dispatches events for the client "events" including onMetaData and onCuePoint. You can add a listener for these events to the NetStreamAsset, and the Event passes the "info" property for your use.

// AS3 INetStream(assets.myFLV).addEventListener(NetStreamAssetEvent.METADATA, onMetaData); // AS2 assets.myFLV.addEventListener(NetStreamAssetEvent.METADATA, Delegate.create(this, onMetaData));

To listen to the onMetaData event, the NetStreamAsset must be set to preload="false", otherwise, the metadata will already be available by the time you can access the asset.

These are all the NetStreamAsset events you can listen for. Consult the Actionscript NetStream documentation for more information about these events.

AS3 and AS2 * NetStreamAssetEvent.METADATA * NetStreamAssetEvent.CUEPOINT

AS3 only * NetStreamAssetEvent.IMAGE_DATA * NetStreamAssetEvent.TEXT_DATA * NetStreamAssetEvent.XMP_DATA

AS2 only * NetStreamAssetEvent.STATUS

<br style="clear:both" />

XMLAsset
In AS2, XML assets have two ways of accessing them. You can either get the xml raw in the property xml or as an XML2AS Actionscript object in the property obj.

AS2 assets.myCopy.xml.firstChild.firstChild.attributes.id; assets.myCopy.obj.site[0].page[0].attributes.id;

In AS3, the XML is stored in the xml property, and you can use E4X syntax to parse through it. AS3 uses the IXml interface.

AS3 var myXML:XML = IXml(assets.myCopy).xml; trace(myXML.child[0].anotherChild[0].@someAttribute);

<br style="clear:both" />

StyleSheetAsset
StyleSheetAsset is for .css files. It contains proxy methods for the StyleSheet class, has a property "style" to get the StyleSheet instance, and one helper method, transformStyle, which combines two native StyleSheet methods into one that returns a TextFormat.

transformStyle
myFormat:TextFormat = assets.myStyle.transformStyle(styleName);

AS3 uses the IStyleSheet interface.

myFormat:TextFormat = IStyleSheet(assets.myStyle).transformStyle(styleName);

<br style="clear:both" />

TextAsset (AS3 only)
TextAsset is for .txt files, and is also the base class for StyleSheetAsset, JSONAsset and XMLAsset. It uses the IText interface and has a property "text" to get the raw text.

AS3 uses the IText interface.

var str:String = IText(assets.myFLV).text;

<br style="clear:both" />

JSONAsset (AS3 only)
JSONAsset extends TextAsset and uses the IJson interface. It has one property "json" which returns a deserialized JSON object using the com.serialization.json.JSON class.

IJson(assets.myJson).json;

<br style="clear:both" />

ByteArrayAsset (AS3 only)
ByteArrayAsset loads in raw byte data, which is avaiable in the public property "data" which returns the ByteArray. One use for this is if you want to load in the raw bytes of a file to create multiple instances of it, such as a Bitmap or swf file.

IByteArray(assets.myByteArray).data;

<br style="clear:both" />

DisplayObjectAsset (AS3 only)
DisplayObjectAsset extends AbstractAsset and is the base asset for SpriteAsset (and thus, MovieClipAsset), BitmapAsset and BitmapSpriteAsset.

<br style="clear:both" />

Load-On-Demand Assets
In the site.xml, by setting the preload attribute to "false", assets can be set to not preload with a page and instead be loaded on demand. To load assets on demand, you use the load method. You can load on demand any number of assets at once, and Gaia will automatically queue them to load two at a time (the maximum number of simultaneous HTTP requests).

assets.mySWF.load; assets.myMusic.load;

In AS3, use the appropriate interface class.

IMovieClip(assets.mySWF).load; ISound(assets.myMusic).load;

Sound And NetStream Assets
Sound and NetStream assets will immediately start streaming when load is called on them. If the Sound is an event sound or a SoundClipAsset, it will load first and immediately play.

load
Sound Assets accept two parameters on the load method, just like the Sound.start method.

SoundAsset.load(startTime:Number, loops:Number);

If the SoundAsset is not streaming, it will load the entire sound file and then play it. If it is streaming, it will play it immediately. Unlike the (AS2) native loadSound method, you can loop streaming audio files by passing the number of loops you want. For example, this code will start streaming a sound asset and loop it 999 times:

assets.myStreamingMusic.load(0, 999);

loadWithoutPlaying
Sound Assets also have a method to load without playing.

SoundAsset.loadWithoutPlaying;

<br style="clear:both" />

Other Asset Types
Image, swf, and xml assets will load like they normally do, with image and swf assets being invisible upon load.

<br style="clear:both" />

Progress Attribute
By setting the progress attribute to "true" in the site.xml, you can use the preloader to display the loading progress of the asset (this does not work for NetStream or streaming sound assets), set it to "false" to not show progress. The asset loader uses the site preloader by default, but this behavior can be changed at runtime. Read the Preloader and API documentation for more information.

<br style="clear:both" />

How To Know When An Asset Is Done Loading
If you want to know when an asset is done loading, assign an AssetEvent.ASSET_COMPLETE event listener to the asset. Make sure you remove the event listener when it's done!

AS3

// replace this IAsset import with whatever specific asset interface you're using import com.gaiaframework.events.AssetEvent; import com.gaiaframework.api.IAsset; // var myAsset:IAsset = Gaia.api.getPage("index").assets.mySWF; myAsset.addEventListener(AssetEvent.ASSET_COMPLETE, onAssetLoaded, false, 0, true); myAsset.load; // private function onAssetLoaded(event:AssetEvent):void {    myAsset.removeEventListener(AssetEvent.ASSET_COMPLETE, onAssetLoaded); // access your asset OR event.target, which is also your asset }

AS2

import com.gaiaframework.assets.AbstractAsset; import com.gaiaframework.events.AssetEvent; import mx.utils.Delegate; // var myAsset:AbstractAsset = Gaia.api.getPage("index").assets.mySWF; var completeDelegate:Function = Delegate.create(this, onAssetLoaded); myAsset.addEventListener(AssetEvent.ASSET_COMPLETE, completeDelegate); myAsset.load; // private function onAssetLoaded(event:AssetEvent):Void {    myAsset.removeEventListener(AssetEvent.ASSET_COMPLETE, completeDelegate); // access your asset OR event.target, which is also your asset }

<br style="clear:both" />

Re-Parenting DisplayObjectAssets (AS3 Only)
If you want to put a BitmapAsset or MovieClipAsset into a MovieClip or Sprite that you create, wait until transitionIn is called and use the loader property. myContainer.addChild(assets.myAsset.loader);

If you want to reparent a BitmapSpriteAsset or MovieClipAsset, use the container property. myContainer.addChild(assets.myAsset.container);

<br style="clear:both" />

Other Uses For Assets
Another use for assets is to preload and cache assets you want to load yourself manually. Just get the src property of the asset.

One example use case is for sound assets you want to persist after the page goes away.

AS2 var mc:MovieClip = _root.createEmptyMovieClip("MC_Music", _root.getNextHighestDepth); _root.music = new Sound(mc); _root.music.loadSound(assets.myMusic.src); _root.music.onLoad = function {    _root.music.start; };

<br style="clear:both" />

Accessing Assets On Other Pages
If you are inside one page and want to access assets on another loaded page in the branch, you have two options.

The recommended way is to use the API method, getPage.

Gaia.api.getPage(branch).assets

which you can read more about in the API section of the documentation.

The other way is to access the page's parent or children properties, such as:

page.getParent.assets OR page.children.somePageID.assets

<br style="clear:both" />

Preloader Asset
You can use a MovieClipAsset as a preloader for the site. Most of the time, you'll want to set its depth="preloader" to load it into the right depth. It's best to make this an asset of a page that will not unload (e.g. the index page). If your MovieClipAsset unloads, the PreloadController will revert to using the default site preloader. Make sure that the MovieClipAsset is loaded before you override the preloader with this asset. You can read more about this in the Preloader documentation.

<br style="clear:both" />

Dynamic Externalized Assets
This is an advanced technique and you should be completely familiar with how Gaia's assets work before using it.

You can create asset xml files and assign assets to a page dynamically at runtime using the Gaia API method addAssets. All you have to do is make sure the nodes you pass have the minimum required asset attributes of id and src. This makes creating image galleries with Gaia much simpler and allows you to use the AssetLoader or Gaia's preloading engine for dynamic lists of assets.

A recommended practice is to have your xml file with assets in it as an asset of the index page (using indexFirst="true", see example below), and call addAssets inside the index page's transitionIn method on the page you want to add the assets to. You can also addAssets to a page that is already loaded.

You can add the assets as on-demand (preload="false") or, if you want them to preload with the page, set preload="true".

To use addAssets, pass a list of valid asset nodes and a reference to the PageAsset you want to add them to. Gaia will warn you if you try to add an asset that already exists on a page so make sure you use unique IDs for your external assets and do not add the same assets multiple times. Adding assets to a page using addAssets is permanent, not temporary.

How To Use External Assets
Gaia.api.addAssets(nodes:XMLList, page:IPageAsset):void // AS3 Gaia.api.addAssets(nodes:Array, page:PageAsset):Void // AS2

Here's an example of how it works:

Example site.xml
<site title="Gaia Scaffold Site: %PAGE%" menu="true" indexFirst="true"> <page id="index" src="index.swf"> <asset id="homeAssets" src="homeAssets.xml"/> <page id="nav" src="nav.swf" depth="top"> <page id="home" title="Home" src="home.swf" menu="true" />

As you can see, the index page has an XMLAsset, homeAssets, and indexFirst is set to true. This is so the index page and the xml will be loaded before Gaia attempts to load the home page branch.

<br style="clear:both" />

Example homeAssets.xml
<asset id="asset1" src="image1.jpg"/> <asset id="asset2" src="image2.jpg"/> <asset id="asset3" src="image3.jpg"/> <asset id="asset4" src="image4.jpg"/>

<br style="clear:both" />

Example IndexPage.as
AS3 override public function transitionIn:void {   super.transitionIn; var assetNodes:XMLList = IXml(assets.homeAssets).xml.asset; var homePage:IPageAsset = Gaia.api.getPage("index/nav/home"); Gaia.api.addAssets(assetNodes, homePage); TweenLite.to(this, 0.3, {alpha:1, onComplete:transitionInComplete}); }

AS2 public function transitionIn:Void {   super.transitionIn; var assetNodes:Array = assets.homeAssets.obj.assets[0].asset; var homePage:PageAsset = Gaia.api.getPage("index/nav/home"); Gaia.api.addAssets(assetNodes, homePage); TweenLite.to(this, 0.3, {_alpha:100, onComplete:Delegate.create(this, transitionInComplete)}); }

<br style="clear:both" />

Explanation
The above code will add all the assets in the homeAssets.xml file to the "home" Page before it loads, and will preload them with the page since these assets are being added before the "index/nav/home" branch is loaded.

If you do not need to preload the assets with the page, set preload="false" in each of your external asset nodes and you can load them yourself in the HomePage class, if you like.

Note that the nodes themselves do not need to be named "asset". You could have many pages of asset nodes in a single external xml file. Just pass the list of nodes you want to the addAssets API method and the page they belong to and Gaia will iterate through that list.

<br style="clear:both" />

Adding Assets To Pages That Are Already Loaded
If you choose to add assets to a page that is in the currently loaded branch, you will need to manually call load on them if you want them to load at that time, even if they're set to preload with the branch. The reason is because Gaia loads all the files associated with a branch when it first loads the branch, and since you have added assets to the branch after this load has occurred, Gaia won't load them until the next time it loads the branch.

Again, it is recommended that you addAssets to a page BEFORE it is loaded in to avoid having to write conditional statements to check if the page already has the assets you're trying to add and whether or not you should load them manually. It's possible to do it, it just takes more work to do so. So, unless you have a really good reason for not adding them ahead of time, you really should do it that way, instead.

<br style="clear:both" />

Update File Bytes
If you want the Gaia Panel to update the "bytes" attribute for external assets, you will need to set assets="true" on the xml asset for the panel to update it.

<br style="clear:both" />

Duplicating Assets
If you want to duplicate an asset, you can simply duplicate its node, change the id, and dynamically add it.

AS3 var node:XML = assets.myAsset.node.copy; // duplicate the node node.@id = "newAssetID"; // give the asset a new id var xml:XML = ;  // create a root node for an XMLList xml.appendChild(node); // add the asset to the root node Gaia.api.addAssets(xml.asset, page); // add the duplicated asset to the page

<br style="clear:both" />

More Information On Assets
To see all of the methods available to assets, check out their individual class files in the com.gaiaframework.assets package. Most, if not all, native methods are available directly.

In AS3, make sure to look at the individual asset interface classes in the com.gaiaframework.api package.

You should use these interfaces when casting assets you access to keep your file sizes considerably smaller.

AS3 import com.gaiaframework.api.ISound; var myMusic:ISound = assets.myMusic as ISound; myMusic.play;

import com.gaiaframework.api.INetStream; var myVideo:INetStream = assets.myVideo as INetStream; myVideo.play;

node
Wszystkie załączniki (assets) włączając w to strony (pages) mają własność "node", zawiera ona xml węzła strony lub załącznika w site.xml. Ponieważ to zwykły XML, można załączać do niego dodatkowe dowolne atrybuty a nawet rozbudowywać strukturę o kolejne węzły ( pod warunkiem że mają inną nazwę niż page lub asset które są zarezerwowanymi nazwami). W AS3 można operować na atrybucie poprzez E4X natomiast w AS2 poprzez klasę XML2AS object.