The situation is as follows. Currently i'm developing an AIR game that will contain plenty of bitmap assets. I'd like to target several tablets (iPad, Xoom, others) and, thus, am considering having the assets done in different ppi, so as to have more visual consistency across the devices. I'm not concerned much about the resolution, because i'll be using scrolling for assets that don't fit on the screen; but units, buildings, enemies should look pretty much the same regardless of the device.
The question is:
can this be done and how (packager-based?)
what would be the best way of doing this
should i even bother?
The only thought that comes to my mind so far is to have an application file for each device being targeted (or ppi, actually), that pulls a big bitmap-registry that corresponds to the ppi of the device. The static registry class is essentially the same for all of these applications differing only in the filename that [Embed] points to (and the classname obviously).
I think you are on the right track, if you wanted to have specific sets of assets for each device type. The way that I've done this in the past is to use a rake script, but any make-like/ant-like utility that you are conformable with will do. Essentially, one of the tasks that runs before the project compilation is to dig through the file structure and programmatically build up these helper classes; it helps avoid the monotony of constructing these mappings by hand. Which can be mind-numbing once you get a non-trivial set of assets.
In my project I would have a structure like this:
/ProjectRoot
/src
/imgs
/132dpi
/unit1.jpg
/unit2.jpg
.
/160dpi
/unit1.jpg
/unit2.jpg
.
/264dpi
/unit1.jpg
/unit2.jpg
.
/326dpi
/unit1.jpg
/unit2.jpg
.
I would usually have some interface which all my assets would abide by, something like
public interface IAssetSet {
function get DPI():uint;
function get Unit1():BitmapData;
function get Unit2():BitmapData;
}
The script would run scrape the folders/files and generate actionscript classes in folder like /src/assets. Stuff like
public class AssetSet132dpi implements IAssetSet {
public function get DPI():uint { return 132; }
[Embed("img/132dpi/unit1.jpg")]
private var _unit1Class:Class;
private var _unit1:BitmapData;
public function get Unit1():BitmapData { return _unit1; }
[Embed("img/132dpi/unit2.jpg")]
private var _unit2Class:Class;
private var _unit2:BitmapData;
public function get Unit2():BitmapData { return _unit2; }
...
public function AssetSet132dpi() {
_unit1 = BitmapData(new _unit1Class()).bitmapData;
_unit2 = BitmapData(new _unit2Class()).bitmapData;
....
}
}
In your initialization code, you determine what device you are running on or you precompile only for specific devices, and instantiate the dpi you want. Everywhere else in your code you just pass around references to IAssetSet, and figure out what to do based on IAssetSet.DPI.
That is one approach, but there are others.
Another approach, would be store embed your source images at the highest DPI and then on application load, downscale them in memory to the desired DPI and dispose() the originals.
Another approach, which is more viable these days with Stage3D and frameworks like Starling and nd2d, you can get away with letting the GPU -- which is really good at doing this scaling -- do most of the heavy lifting that really feasible with traditional compositing.
I think, if you are using traditional compositing, then you will probably seem some performance boosts using assets specifically sized to what you need, rather than trying to dynamically size them all the time. Flash can be a little weird sometimes about regenerating internal representations of those assets at strange times and tanking performance. Probably the best approach would be to leverage Stage3D/Starling/nd3d, but if you have a non-trivial codebase built up, it will probably be a non-trivial task to switch rendering engines at this point in the game...
At least, those are my two cents. Maybe somebody else has had a different experience.
Related
I'm writing a flash game in actionscript 3. In one of my MovieClip classes, I began coding by writing a few functions and variables. So we all know that private functions and variables cannot be accessed outside of the MovieClip, while public functions and variables can.
So here comes my question: Why do we not just always use public functions? Does it cause latency problems? Does it return a specific value that makes it public which makes the player do more work?
Also, if you're not writing in a class and putting frame code, the functions are always public. Why is this? Why not let private functions and variables in frame actions, too, for whatever reason in my first question's answer?
You can use all public if you want.
Suppose your code was a McDonalds and you were the manager. You make things that the customers need public, such as the tables, chairs, and the free refill soda machines. However, there are things that a customer doesn't need access to, and you have those things in a private area locked off by an Employees Only door. You don't want people with no knowledge or need to be in your kitchen, potentially screwing something up.
It's good practice to only expose things that need to be exposed, and that reduces the chances of it's inner workings being compromised. It's more important when you are working with a large code base and a team of people working together. If it's all your code and you are the only one who'll ever see it, it's not likely going to matter as much. However using public/private to expose/restrict properties/methods can make your life easier as it's less clutter when working with an instance of that class.
The reason behind not always using public access is because even though it is A LOT more convienient when wanting to use one class with another, it also can make things confusing. There are going to be items you need, as well as ones you dont. Why have ones that aren't needed? They should be put away and left to themselves. This is simply what private variables are. They are not allowed to interact, so it allows the more important stuff to communicate. I hope that helps with the confusion.
When doing Object Oriented design you will be finding you are writing you code in a class file.
When you make a method Public, you are explicitly saying, use this method from outside my class to help achieve your goal.
Use private methods to help prevent any confusing for anyone (eg yourself) for saying, don't use this method oustide my class. This method is for this call and dont try and use it.
eg.
public function deleteAllUsers():void{
// 1. check user is logged in
// 2. check users are not active
// 3. clean up another object.
// 4. call _deteleAllusers
}
private function _deleteAllUsers(){
// delete from users (do no error checking.
}
From the above example, calling deleteAllUsers does a lot of checking.
But making the method _deteleAllUsers private you cannot skip the error checking and this method is only used internally by the class once we are ready to delete the users.
Cheers, John.
what is the meaning of this interfaces? even if we implement an interface on a class, we have to declare it's functionality again and again each time we implement it on a different class, so what is the reason of interfaces exist on as3 or any other languages which has interface.
Thank you
I basically agree with the answers posted so far, just had a bit to add.
First to answer the easy part, yes other languages have interfaces. Java comes to mind immediately but I'm pretty sure all OOP languages (C++, C#, etc.) include some mechanism for creating interfaces.
As stated by Jake, you can write interfaces as "contracts" for what will be fulfilled in order to separate work. To take a hypothetical say I'm working on A and you're working on C, and bob is working on B. If we define B' as an interface for B, we can quickly and relatively easily define B' (relative to defining B, the implementation), and all go on our way. I can assume that from A I can code to B', you can assume from C you can code to B', and when bob gets done with B we can just plug it in.
This comes to Jugg1es point. The ability to swap out a whole functional piece is made easier by "dependency injection" (if you don't know this phrase, please google it). This is the exact thing described, you create an interface that defines generally what something will do, say a database connector. For all database connectors, you want it to be able to connect to database, and run queries, so you might define an interface that says the classes must have a "connect()" method and a "doQuery(stringQuery)." Now lets say Bob writes the implementation for MySQL databases, now your client says well we just paid 200,000 for new servers and they'll run Microsoft SQL so to take advantage of that with your software all you'd need to do is swap out the database connector.
In real life, I have a friend who runs a meat packing/distribution company in Chicago. The company that makes their software/hardware setup for scanning packages and weighing things as they come in and out (inventory) is telling them they have to upgrade to a newer OS/Server and newer hardware to keep with the software. The software is not written in a modular way that allows them to maintain backwards compatibility. I've been in this boat before plenty of times, telling someone xyz needs to be upgraded to get abc functionality that will make doing my job 90% easier. Anyhow guess point being in the real world people don't always make use of these things and it can bite you in the ass.
Interfaces are vital to OOP, particularly when developing large applications. One example is if you needed a data layer that returns data on, say, Users. What if you eventually change how the data is obtained, say you started with XML web services data, but then switched to a flat file or something. If you created an interface for your data layer, you could create another class that implements it and make all the changes to the data layer without ever having to change the code in your application layer. I don't know if you're using Flex or Flash, but when using Flex, interfaces are very useful.
Interfaces are a way of defining functionality of a class. it might not make a whole lot of sense when you are working alone (especially starting out), but when you start working in a team it helps people understand how your code works and how to use the classes you wrote (while keeping your code encapsulated). That's the best way to think of them at an intermediate level in my opinion.
While the existing answers are pretty good, I think they miss the chief advantage of using Interfaces in ActionScript, which is that you can avoid compiling the implementation of that Interface into the Main Document Class.
For example, if you have an ISpaceShip Interface, you now have a choice to do several things to populate a variable typed to that Interface. You could load an external swf whose main Document Class implements ISpaceShip. Once the Loader's contentLoaderInfo's COMPLETE event fires, you cast the contentto ISpaceShip, and the implementation of that (whatever it is) is never compiled into your loading swf. This allows you to put real content in front of your users while the load process happens.
By the same token, you could have a timeline instance declared in the parent AS Class of type ISpaceShip with "Export for Actionscript in Frame N *un*checked. This will compile on the frame where it is first used, so you no longer need to account for this in your preloading time. Do this with enough things and suddenly you don't even need a preloader.
Another advantage of coding to Interfaces is if you're doing unit tests on your code, which you should unless your code is completely trivial. This enables you to make sure that the code is succeeding or failing on its own merits, not based on the merits of the collaborator, or where the collaborator isn't appropriate for a test. For example, if you have a controller that is designed to control a specific type of View, you're not going to want to instantiate the full view for the test, but only the functionality that makes a difference for the test.
If you don't have support in your work situation for writing tests, coding to interfaces helps make sure that your code will be testable once you get to the point where you can write tests.
The above answers are all very good, the only thing I'd add - and it might not be immediately clear in a language like AS3, where there are several untyped collection classes (Array, Object and Dictionary) and Object/dynamic classes - is that it's a means of grouping otherwise disparate objects by type.
A quick example:
Image you had a space shooter, where the player has missiles which lock-on to various targets. Suppose, for this purpose, you wanted any type of object which could be locked onto to have internal functions for registering this (aka an interface):
function lockOn():void;//Tells the object something's locked onto it
function getLockData():Object;//Returns information, position, heat, whatever etc
These targets could be anything, a series of totally unrelated classes - enemy, friend, powerup, health.
One solution would be to have them all to inherit from a base class which contained these methods - but Enemies and Health Pickups wouldn't logically share a common ancestor (and if you find yourself making bizarre inheritance chains to accomodate your needs then you should rethink your design!), and your missile will also need a reference to the object its locked onto:
var myTarget:Enemy;//This isn't going to work for the Powerup class!
or
var myTarget:Powerup;//This isn't going to work for the Enemy class!
...but if all lockable classes implement the ILockable interface, you can set this as the type reference:
var myTarget:ILockable;//This can be set as Enemy, Powerup, any class which implements ILockable!
..and have the functions above as the interface itself.
They're also handy when using the Vector class (the name may mislead you, it's just a typed array) - they run much faster than arrays, but only allow a single type of element - and again, an interface can be specified as type:
var lockTargets:Vector.<Enemy> = new Vector.<Enemy>();//New array of lockable objects
lockTargets[0] = new HealthPickup();//Compiler won't like this!
but this...
var lockTargets:Vector.<ILockable> = new Vector.<ILockable>();
lockTargets[0] = new HealthPickup();
lockTargets[1] = new Enemy();
Will, provided Enemy and HealthPickup implement ILockable, work just fine!
What's the most resources efficient way to take a screenshot of display object in as3?
This is the code I am currently using:
public static function img(o:DisplayObject,width:int,height:int):ByteArray
{
var b:BitmapData = new BitmapData(width,height,true,0x000000);
b.draw(o,new Matrix(o.width/width,0,0,o.height/height),null,null,null,true);
return new JPGEncoder(35).encode(b);
}
But it takes too much CPU power. I am okay if it will be processed more slowly, but without CPU utilization up to 60%.
Thanks.
It's JPEG encoding that takes most of the time, and not capturing of a displayobject to a BitmapData.
To achieve better performance (sacrificing its running time) you have to use some optimized version of standard JPEGEncoder class or/and its asynchronous version.
Optimized version of JPEGEncoder
Asynchronous version of JPEGEncoder
If you are not satisfied with the above, try googling for similar solutions: some guys out there have already solved the problem.
Note: you can also implement a couple of optimizations.
You don't need to create new Matrix instance every time. You can use one instance, calling Matrix.identity() before drawing. This will be of use if you perform this operation many times during one application session.
You don't need to create new JPEGEncoder instance every time. You can create one and hold it in some private static field (for example, create it on first call to img()).
I'm developing a game with AS3 and AIR. I will have a large-ish quantity of images that I need to load for display elements. It would be nice not to embed all of the images that the game needs, thereby avoiding having them all in memory at once. That's okay in smaller projects, but doesn't make sense here.
I'm curious about strategies for loading images during run time. Since all of the files are quite small and local ( in my current project ) loading them on request might be the best solution, but I'd like to hear what ideas people have for managing this.
For bonus points, I'm also curious about solutions for loading images on-demand server-side as well.
a good idea would be, to create external SWFs, that embed images, that are likely to be used together, if that is possible at all ... something like projectiles.swf, obstacles.swf, enemies.swf, misc.swf .... i don't know ... something that makes sense ... maybe divide assets by levels, or something ... take a simple interface, that allows you to extract assets from an swf ... for example, let there always be a class Assets, with a static method getAll, which returns an Object, mapping string identifiers to corresponding classes, so you will get something like:
function onComplete(e:Event) {//this is the handler for the loading operation
var map:Object = (e.target as LoaderInfo).applicationDomain.getDefinition("Assets").getAll();//should return something like {"bullet1":Bullet1,"bullet2":Bullet2,...}
//do whatever you need to do with it
}
advantages:
images get compressed one against another, so overall filesize will be decreased ...
you drastically reduce request count on your server ...
you don't wind up with n-hundred files, following some name/path convention, or even not (also, you need to have a file index somewhere, to know, which files exist and which don't) ...
you can easily reskin your app by loading a different swf, instead of loading n-hundred images seperately ...
the ultimate advantage of this approach is, that you will have classes, that you can simply instantiate, instead of loading images over and over again ... the first operation is synchronous, the latter is not ... if you really need to do that, consider loading the image in binary form into a ByteArray using URLLoader, and then getting it on stage with Loader::loadBytes ...
you may want to generate the swfs on serverside using swfmill, to automate the process ...
greetz
back2dos
for you project
u can make solution using amfphp and mysql blob-storage.
in this link u can take understand how mysql blob-storage.
http://www.anyexample.com/programming/php/php_mysql_example__image_gallery_%28blob_storage%29.xml
and for amfphp please visit
http://www.amfphp.org/
and also please check this AMFPHP Live JPEG Encoder too,
http://www.bytearray.org/?p=90
The solution that I ended up settling on was to create a reusable singleton loading class which manages the loading and storage of data on-demand. It manages "jobs" which can be LOCAL or REMOTE which store references and the loaded data itself which is mapped in the manager class once it has fully loaded.
While I really like back2dos's suggestion, managing the (re-)creation of SWF's everytime an asset changes isn't optimal for my purposes.
I was confused when I first started to see anti-singleton commentary. I have used the singleton pattern in some recent projects, and it was working out beautifully. So much so, in fact, that I have used it many, many times.
Now, after running into some problems, reading this SO question, and especially this blog post, I understand the evil that I have brought into the world.
So: How do I go about removing singletons from existing code?
For example:
In a retail store management program, I used the MVC pattern. My Model objects describe the store, the user interface is the View, and I have a set of Controllers that act as liason between the two. Great. Except that I made the Store into a singleton (since the application only ever manages one store at a time), and I also made most of my Controller classes into singletons (one mainWindow, one menuBar, one productEditor...). Now, most of my Controller classes get access the other singletons like this:
Store managedStore = Store::getInstance();
managedStore.doSomething();
managedStore.doSomethingElse();
//etc.
Should I instead:
Create one instance of each object and pass references to every object that needs access to them?
Use globals?
Something else?
Globals would still be bad, but at least they wouldn't be pretending.
I see #1 quickly leading to horribly inflated constructor calls:
someVar = SomeControllerClass(managedStore, menuBar, editor, sasquatch, ...)
Has anyone else been through this yet? What is the OO way to give many individual classes acces to a common variable without it being a global or a singleton?
Dependency Injection is your friend.
Take a look at these posts on the excellent Google Testing Blog:
Singletons are pathologic liars (but you probably already understand this if you are asking this question)
A talk on Dependency Injection
Guide to Writing Testable Code
Hopefully someone has made a DI framework/container for the C++ world? Looks like Google has released a C++ Testing Framework and a C++ Mocking Framework, which might help you out.
It's not the Singleton-ness that is the problem. It's fine to have an object that there will only ever be one instance of. The problem is the global access. Your classes that use Store should receive a Store instance in the constructor (or have a Store property / data member that can be set) and they can all receive the same instance. Store can even keep logic within it to ensure that only one instance is ever created.
My way to avoid singletons derives from the idea that "application global" doesn't mean "VM global" (i.e. static). Therefore I introduce a ApplicationContext class which holds much former static singleton information that should be application global, like the configuration store. This context is passed into all structures. If you use any IOC container or service manager, you can use this to get access to the context.
There's nothing wrong with using a global or a singleton in your program. Don't let anyone get dogmatic on you about that kind of crap. Rules and patterns are nice rules of thumb. But in the end it's your project and you should make your own judgments about how to handle situations involving global data.
Unrestrained use of globals is bad news. But as long as you are diligent, they aren't going to kill your project. Some objects in a system deserve to be singleton. The standard input and outputs. Your log system. In a game, your graphics, sound, and input subsystems, as well as the database of game entities. In a GUI, your window and major panel components. Your configuration data, your plugin manager, your web server data. All these things are more or less inherently global to your application. I think your Store class would pass for it as well.
It's clear what the cost of using globals is. Any part of your application could be modifying it. Tracking down bugs is hard when every line of code is a suspect in the investigation.
But what about the cost of NOT using globals? Like everything else in programming, it's a trade off. If you avoid using globals, you end up having to pass those stateful objects as function parameters. Alternatively, you can pass them to a constructor and save them as a member variable. When you have multiple such objects, the situation worsens. You are now threading your state. In some cases, this isn't a problem. If you know only two or three functions need to handle that stateful Store object, it's the better solution.
But in practice, that's not always the case. If every part of your app touches your Store, you will be threading it to a dozen functions. On top of that, some of those functions may have complicated business logic. When you break that business logic up with helper functions, you have to -- thread your state some more! Say for instance you realize that a deeply nested function needs some configuration data from the Store object. Suddenly, you have to edit 3 or 4 function declarations to include that store parameter. Then you have to go back and add the store as an actual parameter to everywhere one of those functions is called. It may be that the only use a function has for a Store is to pass it to some subfunction that needs it.
Patterns are just rules of thumb. Do you always use your turn signals before making a lane change in your car? If you're the average person, you'll usually follow the rule, but if you are driving at 4am on an empty high way, who gives a crap, right? Sometimes it'll bite you in the butt, but that's a managed risk.
Regarding your inflated constructor call problem, you could introduce parameter classes or factory methods to leverage this problem for you.
A parameter class moves some of the parameter data to it's own class, e.g. like this:
var parameterClass1 = new MenuParameter(menuBar, editor);
var parameterClass2 = new StuffParameters(sasquatch, ...);
var ctrl = new MyControllerClass(managedStore, parameterClass1, parameterClass2);
It sort of just moves the problem elsewhere though. You might want to housekeep your constructor instead. Only keep parameters that are important when constructing/initiating the class in question and do the rest with getter/setter methods (or properties if you're doing .NET).
A factory method is a method that creates all instances you need of a class and have the benefit of encapsulating creation of the said objects. They are also quite easy to refactor towards from Singleton, because they're similar to getInstance methods that you see in Singleton patterns. Say we have the following non-threadsafe simple singleton example:
// The Rather Unfortunate Singleton Class
public class SingletonStore {
private static SingletonStore _singleton
= new MyUnfortunateSingleton();
private SingletonStore() {
// Do some privatised constructing in here...
}
public static SingletonStore getInstance() {
return _singleton;
}
// Some methods and stuff to be down here
}
// Usage:
// var singleInstanceOfStore = SingletonStore.getInstance();
It is easy to refactor this towards a factory method. The solution is to remove the static reference:
public class StoreWithFactory {
public StoreWithFactory() {
// If the constructor is private or public doesn't matter
// unless you do TDD, in which you need to have a public
// constructor to create the object so you can test it.
}
// The method returning an instance of Singleton is now a
// factory method.
public static StoreWithFactory getInstance() {
return new StoreWithFactory();
}
}
// Usage:
// var myStore = StoreWithFactory.getInstance();
Usage is still the same, but you're not bogged down with having a single instance. Naturally you would move this factory method to it's own class as the Store class shouldn't concern itself with creation of itself (and coincidentally follow the Single Responsibility Principle as an effect of moving the factory method out).
From here you have many choices, but I'll leave that as an exercise for yourself. It is easy to over-engineer (or overheat) on patterns here. My tip is to only apply a pattern when there is a need for it.
Okay, first of all, the "singletons are always evil" notion is wrong. You use a Singleton whenever you have a resource which won't or can't ever be duplicated. No problem.
That said, in your example, there's an obvious degree of freedom in the application: someone could come along and say "but I want two stores."
There are several solutions. The one that occurs first of all is to build a factory class; when you ask for a Store, it gives you one named with some universal name (eg, a URI.) Inside that store, you need to be sure that multiple copies don't step on one another, via critical regions or some method of ensuring atomicity of transactions.
Miško Hevery has a nice article series on testability, among other things the singleton, where he isn't only talking about the problems, but also how you might solve it (see 'Fixing the flaw').
I like to encourage the use of singletons where necessary while discouraging the use of the Singleton pattern. Note the difference in the case of the word. The singleton (lower case) is used wherever you only need one instance of something. It is created at the start of your program and is passed to the constructor of the classes that need it.
class Log
{
void logmessage(...)
{ // do some stuff
}
};
int main()
{
Log log;
// do some more stuff
}
class Database
{
Log &_log;
Database(Log &log) : _log(log) {}
void Open(...)
{
_log.logmessage(whatever);
}
};
Using a singleton gives all of the capabilities of the Singleton anti-pattern but it makes your code more easily extensible, and it makes it testable (in the sense of the word defined in the Google testing blog). For example, we may decide that we need the ability to log to a web-service at some times as well, using the singleton we can easily do that without significant changes to the code.
By comparison, the Singleton pattern is another name for a global variable. It is never used in production code.