/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/sgx/core/threading/staticthreadfarm.cpp

*/

#include "sgx/core/core.hpp"

CStaticFarm::CStaticFarm(CSGXProcessThread **pThreadList, int numThreads)
{
	for(int i=0;i<numThreads;++i) {
		m_ThreadList.push_back(pThreadList[i]);
	}
}

CStaticFarm::CStaticFarm(sgxVector<CSGXProcessThread *>ThreadList)
{
	for(sgxVector<CSGXProcessThread *>::iterator it=ThreadList.begin();
	it != ThreadList.end(); ++it) {
		m_ThreadList.push_back((*it));
	}
}

void CStaticFarm::addThread(CSGXProcessThread *pThread)
{
	m_ThreadList.push_back(pThread);
}


CSGXThread *CStaticFarm::assignObject(sgxObject *pObject, tUINT32 iWeight)
{
SGX_UNUSED(iWeight);
	tUINT32 smallest = 0;
	CSGXProcessThread *pBestThread = NULL;

	// Find least busy thread
	for(sgxVector<CSGXProcessThread *>::iterator it=m_ThreadList.begin();
	it != m_ThreadList.end(); ++it) {
		tUINT32 numprocesses = (*it)->getNumprocessesWeighted();

		if (numprocesses <= smallest) {
			numprocesses = smallest;
			pBestThread = (*it);
		}
	}

	if (pBestThread) {
		pBestThread->addObject(pObject);
	}
	return pBestThread;
}

/**
This method doesn't support non-unity weights at present.
*/
void CStaticFarm::assignObject(sgxObject **pObjectList, int numObjects)
{
	// TODO Optimize this loop to sort once
	for(int i=0;i<numObjects;++i) {
		assignObject(pObjectList[i]);
	}
}
