View difference between Paste ID: nU8Y59Ym and eV4zeyCR
SHOW: | | - or go back to the newest paste.
1
package com.mkv25.util;
2
3
import nme.display.DisplayObject;
4
import nme.display.Sprite;
5
6
/**
7
 * Recycles stage assets by creating and managing display assets, and cleanly removing from them from the stage ready for reuse.
8
 * @author John Beech
9
 */
10
class Recycler<T>
11
{
12
	public var classType:Class<T>;
13
	public var artworkProperty:String;
14
	public var params:Array<Dynamic>;
15
	
16
	private var itemsInUse:Array<T>;
17
	private var recycledItems:Array<T>;
18
	private var artBin:Sprite;
19
	
20
	/**
21
	 * Define a recycler for type T, specifying artwork and additional params for construction.
22
	 * @param	artworkProperty
23
	 * @param	params
24
	 */
25
	public function new(classType:Class<T>, artworkProperty:String = "", params:Array<Dynamic> = null) {
26
		this.classType = classType;
27
		this.artworkProperty = artworkProperty;
28
		this.params = params;
29
		
30
		itemsInUse = new Array();
31
		recycledItems = new Array();
32
		artBin = new Sprite();
33
	}
34
	
35
	/**
36
	 * Constructs an item of type T, or recycles an existing item of type T.
37
	 * @return an item of type T
38
	 */
39
	public function getItem():T {
40
		var item:T;
41
		if(recycledItems.length > 0) {
42
			item = recycledItems.pop();
43
		}
44
		else {
45
			if(params == null) {
46
				item = Type.createInstance(classType, params);
47
			}
48
			else {
49
				item = Type.createInstance(classType, null);
50
			}
51
		}
52
		itemsInUse.push(item);
53
		
54
		return item;
55
	}
56
	
57
	/**
58
	 * Recycle all items of type T tracked by this recycler and remove them or their art assets from the stage.
59
	 */
60
	public function recycleAll():Void {
61
		var item:T;
62
		var artwork:DisplayObject;
63
		while(itemsInUse.length > 0) {
64
			// Remove item from usage
65
			item = itemsInUse.pop();
66
			
67
			// Attempt to remove artwork from stage
68
			if (artworkProperty != "") {
69
				if (Reflect.hasField(item, artworkProperty)) {
70
					artwork = Reflect.field(item, artworkProperty);
71
					artBin.addChild(artwork);
72
				}
73
				else {
74
					var fields:Array<String> = Type.getInstanceFields(classType);
75-
						trace("Fields: " + fields);
75+
76
						artwork = Reflect.field(item, artworkProperty);
77
						artBin.addChild(artwork);
78
					}
79
					else {
80
						throw ("Recycled item (" + item + ") does not have an valid art reference (" + artworkProperty +")"); 
81
					}
82
				}
83
			}
84
			else if (Std.is(item, DisplayObject)) {
85
				artBin.addChild(cast item);
86
			}
87
			
88
			// Recycle item
89
			recycledItems.push(item);
90
		}
91
	}
92
	
93
	private function arrayContains(array:Array<String>, needle:String):Bool {
94
		for (item in array) {
95
			if (item == needle) {
96
				return true;
97
			}
98
		}
99
		return false;
100
	}
101
}