/*
 * Created on Sep 27, 2005
 * Copyright 2005 Program of Computer Grpahics, Cornell University
 */
package pipeline;

import java.util.IdentityHashMap;

import pipeline.misc.Fragment;


/**
 * Pool for pre-allocated fragment objects to be used during rasterization.
 * @author arbree
 * Sep 27, 2005
 * FragementPool.java
 * Copyright 2005 Program of Computer Graphics, Cornell University
 */
public class FragmentPool {

  /** The fragments currently in use */
  private static IdentityHashMap used = new IdentityHashMap();
  
  /** The fragments currently free */
  private static IdentityHashMap freed = new IdentityHashMap();
  
  /**
   * Get a fragment from the pool
   * @return
   */
  public static final Fragment get() {
    
    Fragment output;
    if(freed.isEmpty())
      output = new Fragment();
    else {
      output = (Fragment) freed.keySet().iterator().next();
      freed.remove(output);
    }
    
    if(used.containsKey(output))
      throw new Error("FragmentPool.get(): Fragment gotten already in use.");
    
    used.put(output, null);
    
    return output;
    
  }
  
  /**
   * Put a fragment in the pool
   * @param inFrag
   */
  public static final void put(Fragment inFrag) {
    
    if(!used.containsKey(inFrag))
      throw new Error("FragmentPool.put(): Returned fragment not in use.");
    
    used.remove(inFrag);
    
    if(freed.containsKey(inFrag))
      throw new Error("FragmentPool.put(): Returned fragment already freed.");
    
    freed.put(inFrag, null);
    
  }
}
