All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.badlogic.gdx.ai.btree.utils.PooledBehaviorTreeLibrary Maven / Gradle / Ivy

The newest version!
package com.badlogic.gdx.ai.btree.utils;

import com.badlogic.gdx.ai.btree.BehaviorTree;
import org.mini2Dx.gdx.utils.ObjectMap;
import org.mini2Dx.gdx.utils.Pool;

/** A {@code BehaviorTreeLibrary} using reference pool.
 * 
 * {@link BehaviorTree} created by {@link PooledBehaviorTreeLibrary} should be disposed by
 * calling {@link BehaviorTreeLibrary#disposeBehaviorTree(String, BehaviorTree)}.
 * 
 * @author mgsx
 *
 */
@SuppressWarnings("rawtypes")
public class PooledBehaviorTreeLibrary extends BehaviorTreeLibrary
{
	protected ObjectMap> pools = new ObjectMap>();
	
	/**
	 * retrieve pool by tree reference, create it if not already exists.
	 * @param treeReference
	 * @return existing or newly created pool.
	 */
	protected Pool getPool(final String treeReference){
		Pool treePool = pools.get(treeReference);
		if(treePool == null){
			treePool = new Pool(){
				@Override
				protected BehaviorTree newObject() {
					return newBehaviorTree(treeReference);
				}
			};
			pools.put(treeReference, treePool);
		}
		return treePool;
	}
	
	/**
	 * creates concrete tree instance.
	 * @param treeReference
	 * @return a new tree instance.
	 */
	protected  BehaviorTree newBehaviorTree (String treeReference) {
		return super.createBehaviorTree(treeReference, null);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public  BehaviorTree createBehaviorTree(String treeReference, T blackboard) {
		Pool pool = getPool(treeReference);
		BehaviorTree tree = (BehaviorTree)pool.obtain();
		tree.setObject(blackboard);
		return tree;
	}
	
	@Override
	public void disposeBehaviorTree(final String treeReference, BehaviorTree behaviorTree) {
		Pool pool = getPool(treeReference);
		pool.free(behaviorTree);
	}
	
	/**
	 * Clear pool for a tree reference.
	 * @param treeReference
	 */
	public void clear(String treeReference){
		Pool treePool = pools.get(treeReference);
		if(treePool != null){
			treePool.clear();
		}
	}
	
	/**
	 * clear all pools.
	 */
	public void clear(){
		for(ObjectMap.Entry> entry : pools.entries()){
			entry.value.clear();
		}
		pools.clear();
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy