MNcdLoadNodeOperation* CNcdSearchNodeBundleProxy::LoadChildrenL( TInt aIndex, 
                                                           TInt aSize,
                                                           TNcdChildLoadMode aMode,
                                                           MNcdLoadNodeOperationObserver& aObserver )
    {
    DLTRACEIN((("this: %X"), this));
    DASSERT( iSearchFilter );
        
    if( aSize < 1 || aIndex < 0 || ( aMode == ELoadMetadata && aIndex + aSize > ChildCount() ))
        {
        // Nothing to be done 
        DLERROR(( "Argument error. ChildCount: %d Given index: %d, size: %d",
                  ChildCount(), aIndex, aSize ));
        DASSERT( EFalse );
        User::Leave( KErrArgument );
        }

    DLTRACE(( _L("Node: %S, %S"), &Namespace(), &Id() ));

    // Search bundle may contain transparent stuff, so use server child count for loading
    // to get correct indexing on server side.
    return CNcdSearchNodeFolderProxy::LoadChildrenL( 
        0,
        ServerChildCount(),
        aMode,
        aObserver );
    }
nsresult
nsAttrAndChildArray::InsertChildAt(nsIContent* aChild, PRUint32 aPos)
{
  NS_ASSERTION(aChild, "nullchild");
  NS_ASSERTION(aPos <= ChildCount(), "out-of-bounds");

  PRUint32 offset = AttrSlotsSize();
  PRUint32 childCount = ChildCount();

  NS_ENSURE_TRUE(childCount < ATTRCHILD_ARRAY_MAX_CHILD_COUNT,
                 NS_ERROR_FAILURE);

  // First try to fit new child in existing childlist
  if (mImpl && offset + childCount < mImpl->mBufferSize) {
    void** pos = mImpl->mBuffer + offset + aPos;
    if (childCount != aPos) {
      memmove(pos + 1, pos, (childCount - aPos) * sizeof(nsIContent*));
    }
    SetChildAtPos(pos, aChild, aPos, childCount);

    SetChildCount(childCount + 1);

    return NS_OK;
  }

  // Try to fit new child in existing buffer by compressing attrslots
  if (offset && !mImpl->mBuffer[offset - ATTRSIZE]) {
    // Compress away all empty slots while we're at it. This might not be the
    // optimal thing to do.
    PRUint32 attrCount = NonMappedAttrCount();
    void** newStart = mImpl->mBuffer + attrCount * ATTRSIZE;
    void** oldStart = mImpl->mBuffer + offset;
    memmove(newStart, oldStart, aPos * sizeof(nsIContent*));
    memmove(&newStart[aPos + 1], &oldStart[aPos],
            (childCount - aPos) * sizeof(nsIContent*));
    SetChildAtPos(newStart + aPos, aChild, aPos, childCount);

    SetAttrSlotAndChildCount(attrCount, childCount + 1);

    return NS_OK;
  }

  // We can't fit in current buffer, Realloc time!
  if (!GrowBy(1)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  void** pos = mImpl->mBuffer + offset + aPos;
  if (childCount != aPos) {
    memmove(pos + 1, pos, (childCount - aPos) * sizeof(nsIContent*));
  }
  SetChildAtPos(pos, aChild, aPos, childCount);

  SetChildCount(childCount + 1);
  
  return NS_OK;
}
MNcdLoadNodeOperation* CNcdSearchNodeFolderProxy::LoadChildrenL( TInt aIndex, 
                                                           TInt aSize,
                                                           TNcdChildLoadMode aMode,
                                                           MNcdLoadNodeOperationObserver& aObserver )
    {
    DLTRACEIN((("this: %X"), this));
    DASSERT( iSearchFilter );
    
    if( aSize < 1 || aIndex < 0 || ( aMode == ELoadMetadata && aIndex + aSize > ChildCount() ))
        {
        // Nothing to be done 
        DLERROR(( "Argument error. ChildCount: %d Given index: %d, size: %d",
                  ChildCount(), aIndex, aSize ));
        DASSERT( EFalse );
        User::Leave( KErrArgument );
        }

    DLTRACE(( _L("Node: %S, %S"), &Namespace(), &Id() ));

    #ifdef CATALOGS_BUILD_CONFIG_DEBUG    
    const MDesCArray& keywords = iSearchFilter->Keywords();
    DLINFO(("Search filter: "));
    for ( TInt i = 0; i < keywords.MdcaCount(); i++ ) 
        {
        DLINFO((_L("%S"), &keywords.MdcaPoint( i ) ));
        }
    #endif
        
    CNcdLoadNodeOperationProxy* operation = 
        OperationManager().CreateLoadNodeOperationL( *this,
            ETrue, // load children
            aSize, 
            aIndex,
            1,
            aMode,
            iSearchFilter );

    if( operation == NULL )
        {
        DLTRACEOUT(("NULL"));     
        return NULL;
        }

    CleanupReleasePushL( *operation );
    operation->AddObserverL( this );
    operation->AddObserverL( &aObserver );
    CleanupStack::Pop( operation );
    
    DLTRACEOUT((""));

    return operation;
    }
MNcdLoadNodeOperation* CNcdNodeFolderProxy::LoadChildrenL( TInt aIndex, 
                                                           TInt aSize,
                                                           TNcdChildLoadMode aMode,
                                                           MNcdLoadNodeOperationObserver& aObserver )
    {
    DLTRACEIN(("aIndex: %d, aSize: %d, expected child count: %d, load mode: %d",
        aIndex, aSize, iExpectedChildCount, aMode ));

    if ( aSize < 1 
         || aIndex < 0 
         || ( aMode == ELoadMetadata 
              && aSize != KMaxTInt 
              && aIndex + aSize > ChildCount() ) )
        {
        // Nothing to be done 
        DLERROR(( "Argument error. ChildCount: %d Given index: %d, size: %d",
                  ChildCount(), aIndex, aSize ));
        User::Leave( KErrArgument );
        }

    if ( aSize == KMaxTInt )
        {
        // Because aSize is KMaxTInt, reduce it by the aIndex value.
        // This way we will not have possible overload if aIndex is later added
        // to the aSize value. It does not really matter what the aSize value is
        // after this. KMaxTInt is so great value, that in all the cases the server
        // request should give all the required items.
        aSize -= aIndex;
        DLINFO(("aSize was KMaxTInt. Reduced by index: %d", aSize));
        }

    DLTRACE(( _L("Node: %S, %S"), &Namespace(), &Id() ));
    
    CNcdLoadNodeOperationProxy* operation = 
        OperationManager().CreateLoadNodeOperationL( 
            *this, ETrue, aSize, aIndex, 1, aMode );

    if ( !operation )
        {
        DLTRACEOUT(("NULL"));     
        return NULL;
        }

    operation->AddObserverL( this );
    operation->AddObserverL( &aObserver );

    DLTRACEOUT((""));        

    return operation;
    }
void
nsAttrAndChildArray::Compact()
{
  if (!mImpl) {
    return;
  }

  // First compress away empty attrslots
  PRUint32 slotCount = AttrSlotCount();
  PRUint32 attrCount = NonMappedAttrCount();
  PRUint32 childCount = ChildCount();

  if (attrCount < slotCount) {
    memmove(mImpl->mBuffer + attrCount * ATTRSIZE,
            mImpl->mBuffer + slotCount * ATTRSIZE,
            childCount * sizeof(nsIContent*));
    SetAttrSlotCount(attrCount);
  }

  // Then resize or free buffer
  PRUint32 newSize = attrCount * ATTRSIZE + childCount;
  if (!newSize && !mImpl->mMappedAttrs) {
    PR_Free(mImpl);
    mImpl = nsnull;
  }
  else if (newSize < mImpl->mBufferSize) {
    mImpl = static_cast<Impl*>(PR_Realloc(mImpl, (newSize + NS_IMPL_EXTRA_SIZE) * sizeof(nsIContent*)));
    NS_ASSERTION(mImpl, "failed to reallocate to smaller buffer");

    mImpl->mBufferSize = newSize;
  }
}
void ZombieGenetics::Populate(std::mt19937& a_random)
{
	unsigned int populationSize = PopulationSize();
	unsigned int childCount = ChildCount();

	for (int i = 0; i < populationSize + childCount; i++)
	{
		population[i].genes[0] = zombies[i];

		std::uniform_real_distribution<float> distrubution(1.0f, 10.0f);

		population[i].genes[0]->maxHealthRange = glm::vec2(1, 10);
		population[i].genes[0]->maxHealth = distrubution(a_random);

		population[i].genes[0]->speedRange = glm::vec2(5, 15);
		population[i].genes[0]->speed = distrubution(a_random);

		population[i].genes[0]->strengthRange = glm::vec2(1, 10);
		population[i].genes[0]->strength = distrubution(a_random);

		population[i].genes[0]->scaleRange = glm::vec2(0.75f, 1.25f);
		population[i].genes[0]->scale = std::uniform_real_distribution<float>(0.75f, 1.25f)(a_random);

		population[i].genes[0]->specialTraits = 0;

		population[i].genes[0]->active = i < populationSize;
	}
}
void ZombieGenetics::Select(std::mt19937& a_random)
{
	unsigned int populationSize = PopulationSize();
	unsigned int childCount = ChildCount();

	int totalChances = 0;

	for (int i = 0; i < populationSize; i++)
	{
		totalChances += (int)(population[i].fitness + 1.0f);
	}

	int parentCount = childCount * 2;

	for (int i = 0; i < parentCount; i++)
	{
		int result = rand() % totalChances;
		for (int j = 0; j < populationSize; j++)
		{
			result -= (int)(population[j].fitness + 1.0f);
			if (result < 0)
			{
				result = j;
				break;
			}
		}

		parents[i] = &population[result];
	}
}
Beispiel #8
0
nat32 Node::Write(io::OutVirt<io::Binary> & out) const
{
 nat32 ret = 0;
  // Header...
   nat32 bs = WriteSize();
   nat32 os = TotalWriteSize();
   nat8 zb = 0;

   ret += out.Write("HON",3);
   ret += out.Write(MagicString(),3);
   ret += out.Write(&bs,4);
   ret += out.Write(&zb,1);
   ret += out.Write(&os,4);
   ret += out.Write(&zb,1);
;
  // Child count...
   nat32 childCount = ChildCount();
   ret += out.Write(&childCount,4);

  // Children...
   if (child)
   {
    Node * targ = child;
    do
    {
     ret += targ->Write(out);
     targ = targ->Next();
    } while (!targ->First());
   }   

 if (ret!=bs) out.SetError(true);
 return ret;
}
Beispiel #9
0
/* Writes node information out to a file */
static void pf(FILE *f, void *t, int tab)
{
   TREENODE *tnode = t;

   fprintf(f,"%s(%d) @ L%d/C%d\n",
	   tnode->string,ChildCount(tnode),tnode->line,tnode->column);
}
nsIContent*
nsAttrAndChildArray::GetSafeChildAt(uint32_t aPos) const
{
  if (aPos < ChildCount()) {
    return ChildAt(aPos);
  }
  
  return nullptr;
}
nsIContent*
nsAttrAndChildArray::GetSafeChildAt(PRUint32 aPos) const
{
  if (aPos < ChildCount()) {
    return ChildAt(aPos);
  }
  
  return nsnull;
}
Beispiel #12
0
void TreeServer::FinishBurstInternal()
{
	this->bursting = false;
	SetNextPingTime(ServerInstance->Time() + Utils->PingFreq);
	SetPingFlag();
	for(unsigned int q=0; q < ChildCount(); q++)
	{
		TreeServer* child = GetChild(q);
		child->FinishBurstInternal();
	}
}
void
nsAttrAndChildArray::RemoveChildAt(PRUint32 aPos)
{
  NS_ASSERTION(aPos < ChildCount(), "out-of-bounds");

  PRUint32 childCount = ChildCount();
  void** pos = mImpl->mBuffer + AttrSlotsSize() + aPos;
  nsIContent* child = static_cast<nsIContent*>(*pos);
  if (child->mPreviousSibling) {
    child->mPreviousSibling->mNextSibling = child->mNextSibling;
  }
  if (child->mNextSibling) {
    child->mNextSibling->mPreviousSibling = child->mPreviousSibling;
  }
  child->mPreviousSibling = child->mNextSibling = nsnull;

  NS_RELEASE(child);
  memmove(pos, pos + 1, (childCount - aPos - 1) * sizeof(nsIContent*));
  SetChildCount(childCount - 1);
}
Beispiel #14
0
	bool iInputDevice::IsActive()
	{
		size_t count = ChildCount();
		for(size_t i = 0; i < count; i++)
		{
			if(GetChild(i)->IsTriggered())
				return true;
		}

		return false;
	}
already_AddRefed<nsIContent>
nsAttrAndChildArray::TakeChildAt(uint32_t aPos)
{
  NS_ASSERTION(aPos < ChildCount(), "out-of-bounds");

  uint32_t childCount = ChildCount();
  void** pos = mImpl->mBuffer + AttrSlotsSize() + aPos;
  nsIContent* child = static_cast<nsIContent*>(*pos);
  if (child->mPreviousSibling) {
    child->mPreviousSibling->mNextSibling = child->mNextSibling;
  }
  if (child->mNextSibling) {
    child->mNextSibling->mPreviousSibling = child->mPreviousSibling;
  }
  child->mPreviousSibling = child->mNextSibling = nullptr;

  memmove(pos, pos + 1, (childCount - aPos - 1) * sizeof(nsIContent*));
  SetChildCount(childCount - 1);

  return dont_AddRef(child);
}
Beispiel #16
0
	iInputControl *iInputDevice::FindControl(tString _name)
	{
		size_t count = ChildCount();
		for(size_t i = 0; i < count; i++)
		{
			iInputControl *chld = GetChild(i);
			if(chld && chld->GetName().compare(_name) == 0)
				return chld;
		}
		
		return NULL;
	}
bool QtPropertyDataDavaKeyedArcive::UpdateValueInternal()
{
	// update children
	{
		QSet<QtPropertyData *> dataToRemove;

		// at first step of sync we mark (placing to vector) items to remove
		for(int i = 0; i < ChildCount(); ++i)
		{
			QPair<QString, QtPropertyData *> pair = ChildGet(i);
			if(NULL != pair.second)
			{
				dataToRemove.insert(pair.second);
			}
		}

		// as second step we go throught keyed archive and add new data items,
		// and remove deleting mark from items that are still in archive
		if(NULL != curArchive)
		{
			DAVA::Map<DAVA::String, DAVA::VariantType*> data = curArchive->GetArchieveData();
			DAVA::Map<DAVA::String, DAVA::VariantType*>::iterator i = data.begin();

			for(; i != data.end(); ++i)
			{
				QtPropertyData *childData = ChildGet(i->first.c_str());

				// this key already in items list
				if(NULL != childData)
				{
					// remove deleting mark
					dataToRemove.remove(childData);
				}
				// create new child data
				else
				{
					ChildCreate(i->first.c_str(), i->second);
				}
			}
		}

		// delete all marked items
		QSetIterator<QtPropertyData *> it(dataToRemove);
		while(it.hasNext())
		{
			ChildRemove(it.next());
		}
	}

	return false;
}
MNcdNode::TState CNcdRootNodeProxy::State() const
    {
    DLTRACEIN((""));

    // Check if the link handle has been set, which means that also
    // link data has been internalized. Root node does not contain
    // metadata so it does not need to be checked.
    // The child count is also checked because in some situations when root loading
    // is cancelled the link handle may be set, but the children are not inserted to 
    // the root child list. So, the root should have children to be in initialized mode.
    if ( LinkHandleSet() && ChildCount() > 0 )
        {
        DLTRACE(("State was initialized"));
        // If state was initialized we have to check if the state
        // has acutally expired already 
        TTime now;
        now.HomeTime();

        DLTRACE(("now time: %d", now.Int64() ));
        DLTRACE(("expired time: %d", ExpiredTime().Int64() ));

        // We can just compare the times here. Server side
        // inserts the maximum value for the expired time if the
        // protocol has set never expire value for the validity delta.
        TBool isExpired = ( now > ExpiredTime() );
        TInt err = KErrNone;
        
        if ( !isExpired ) 
            {            
            TRAP( err, isExpired = IsTransparentChildExpiredL() );
            }
            
        if ( isExpired || err != KErrNone )
            {
            DLTRACEOUT(("Expired"));
            return MNcdNode::EStateExpired;
            }
            
        DLTRACEOUT(("Initialized"));
        return MNcdNode::EStateInitialized;
        }
     else
        {
        // Node has not been initialized.
        DLTRACEOUT(("Not intialized"));
        return MNcdNode::EStateNotInitialized;
        }

    }
Beispiel #19
0
/* Here is where the tree is dumped out in the Manuelian style. */
extern void DumpManuelTree(FILE *f, TREENODE *node)
{
   TREENODE *kid;

   kid = GetChild(node,1);
   while (kid) 
   {
      DumpManuelTree(f,kid);
      kid = NextSibling(kid);
   }
    
   fprintf(f,"%s\n",node->string);
   fprintf(f,"L%d/C%d\n",node->line,node->column);
   fprintf(f,"%d\n",ChildCount(node));
}
Beispiel #20
0
Datei: File.cpp Projekt: ThQ/memc
void
File::isValid (NodeValidator* v)
{
   Node::isValid(v);

   Node* child = NULL;
   for (size_t i = 0 ; i < ChildCount(); ++i)
   {
      child = getChild(i);

      v->ensure(node::isa<Use>(child)
         || node::isa<Class>(child)
         || node::isa<EnumType>(child)
         || node::isa<Func>(child),
         "Children of a File node must be either Use, Class or Func");
   }
}
void ZombieGenetics::Fitness(std::mt19937& a_random)
{
	unsigned int populationSize = PopulationSize();
	unsigned int childCount = ChildCount();

	const float damageWeight = 1.0f, timeAliveWeight = 0.25f;

	startWave = true;
	zombiesDead = false;
	while (startWave && !terminate) {}
	while (!zombiesDead && !terminate) {}

	for (int i = 0; i < populationSize; i++)
	{
		population[i].fitness = population[i].genes[0]->damageToPlayer * damageWeight + population[i].genes[0]->timeAlive * timeAliveWeight;
	}
}
void
nsAttrAndChildArray::Clear()
{
  if (!mImpl) {
    return;
  }

  if (mImpl->mMappedAttrs) {
    NS_RELEASE(mImpl->mMappedAttrs);
  }

  PRUint32 i, slotCount = AttrSlotCount();
  for (i = 0; i < slotCount && AttrSlotIsTaken(i); ++i) {
    ATTRS(mImpl)[i].~InternalAttr();
  }

  nsAutoScriptBlocker scriptBlocker;
  PRUint32 end = slotCount * ATTRSIZE + ChildCount();
  for (i = slotCount * ATTRSIZE; i < end; ++i) {
    nsIContent* child = static_cast<nsIContent*>(mImpl->mBuffer[i]);
    // making this false so tree teardown doesn't end up being
    // O(N*D) (number of nodes times average depth of tree).
    child->UnbindFromTree(false); // XXX is it better to let the owner do this?
    // Make sure to unlink our kids from each other, since someone
    // else could stil be holding references to some of them.

    // XXXbz We probably can't push this assignment down into the |aNullParent|
    // case of UnbindFromTree because we still need the assignment in
    // RemoveChildAt.  In particular, ContentRemoved fires between
    // RemoveChildAt and UnbindFromTree, and in ContentRemoved the sibling
    // chain needs to be correct.  Though maybe we could set the prev and next
    // to point to each other but keep the kid being removed pointing to them
    // through ContentRemoved so consumers can find where it used to be in the
    // list?
    child->mPreviousSibling = child->mNextSibling = nsnull;
    NS_RELEASE(child);
  }

  SetAttrSlotAndChildCount(0, 0);
}
void CNcdNodeFolderProxy::InternalizeL()
    {
    DLTRACEIN((""));

    // First call the parent internalizator. So, all the parent stuff will
    // be initialized before folder specific data.
    CNcdNodeProxy::InternalizeL();

    // Add the search interface because it is availabe for all the folders
    // that have at least one child.
    
    // check that is search supported for this node
    TBool isSearchSupported = IsSearchSupportedL();
        
    DLINFO(( "isSearchSupported: %d, child count: %d", isSearchSupported, 
        ChildCount() ));
    if ( isSearchSupported )
        {
        DLTRACE(("add search interface"));
        if ( iSearch == NULL )
            {
            // Create new search because old one did not exist.
            // Notice that the creation adds the interface to the node interface list
            // automatically.
            iSearch = CNcdNodeSearch::NewL( *this, OperationManager() );    
            }
        }
    else
        {
        DLTRACE(("remove search interface"));        
        delete iSearch;
        iSearch = NULL;
        }
        
    InternalizeNodeSeenFolderL();        
                   
    DLTRACEOUT((""));
    }
void ZombieGenetics::Discard(std::mt19937& a_random)
{
	unsigned int populationSize = PopulationSize();
	unsigned int childCount = ChildCount();

	for (int i = 0; i < childCount; i++)
	{
		children[i].fitness = 0.0f;
	}

	std::sort(populationPool.begin(), populationPool.end() - childCount, DiscardSortFunction());
	std::swap_ranges(populationPool.begin() + populationSize, populationPool.begin() + populationSize + childCount, populationPool.begin());

	for (int i = 0; i < populationSize; i++)
	{
		population[i].genes[0]->active = true;
	}

	for (int i = 0; i < childCount; i++)
	{
		children[i].genes[0]->active = false;
	}
}
Beispiel #25
0
void
VarAssign::isValid (NodeValidator* v)
{
   // Check self
   Node::isValid(v);
   v->ensure(ChildCount() == 2, "VarAssign must have exactly 2 children");
   v->ensure(hasExprType(), "VarAssign must have an expression type");

   // Check NAME node
   v->ensure(NameNode() != NULL, "VarAssign must have a name node");
   if (NameNode() != NULL)
   {
      v->ensure(NameNode()->hasExprType(), "VarAssign : Name node must have an expression type");
   }

   if (ValueNode() != NULL)
   {
      // Check VALUE node
      v->ensure(ValueNode()->hasExprType(), "VarAssign : Value node must have an expression type");

      // TODO Should check that the var type and the value type have the expr type.
      // Take care of pointers.
   }
}
Beispiel #26
0
void XMLElement :: DumpOn( std::ostream & os, bool recurse  ) const {
	os << "<" << Name();
	for ( unsigned int i = 0; i < AttrCount(); i++ ) {
		os << " " << AttrName(i) << "=\"";
		os << AttrValue( AttrName(i) ) << "\"";
	}
	if ( ! recurse ) {
		os << "/>\n";
	}
	else {
		os << ">\n";
		for ( unsigned int i = 0; i < ChildCount(); i++ ) {
			const XMLElement * ce = ChildElement( i ) ;
			if ( ce ) {
				ce->DumpOn( os, recurse );
			}
			const XMLText * ct = ChildText( i );
			if ( ct ) {
				os << LTrim( ct->Text() ) << "\n";
			}
		}
		os << "</" << Name() << ">\n";
	}
}
bool
nsAttrAndChildArray::AddAttrSlot()
{
  PRUint32 slotCount = AttrSlotCount();
  PRUint32 childCount = ChildCount();

  // Grow buffer if needed
  if (!(mImpl && mImpl->mBufferSize >= (slotCount + 1) * ATTRSIZE + childCount) &&
      !GrowBy(ATTRSIZE)) {
    return false;
  }
  void** offset = mImpl->mBuffer + slotCount * ATTRSIZE;

  if (childCount > 0) {
    memmove(&ATTRS(mImpl)[slotCount + 1], &ATTRS(mImpl)[slotCount],
            childCount * sizeof(nsIContent*));
  }

  SetAttrSlotCount(slotCount + 1);
  offset[0] = nsnull;
  offset[1] = nsnull;

  return true;
}
PRInt32
nsAttrAndChildArray::IndexOfChild(nsINode* aPossibleChild) const
{
  if (!mImpl) {
    return -1;
  }
  void** children = mImpl->mBuffer + AttrSlotsSize();
  // Use signed here since we compare count to cursor which has to be signed
  PRInt32 i, count = ChildCount();

  if (count >= CACHE_CHILD_LIMIT) {
    PRInt32 cursor = GetIndexFromCache(this);
    // Need to compare to count here since we may have removed children since
    // the index was added to the cache.
    // We're also relying on that GetIndexFromCache returns -1 if no cached
    // index was found.
    if (cursor >= count) {
      cursor = -1;
    }

    // Seek outward from the last found index. |inc| will change sign every
    // run through the loop. |sign| just exists to make sure the absolute
    // value of |inc| increases each time through.
    PRInt32 inc = 1, sign = 1;
    while (cursor >= 0 && cursor < count) {
      if (children[cursor] == aPossibleChild) {
        AddIndexToCache(this, cursor);

        return cursor;
      }

      cursor += inc;
      inc = -inc - sign;
      sign = -sign;
    }

    // We ran into one 'edge'. Add inc to cursor once more to get back to
    // the 'side' where we still need to search, then step in the |sign|
    // direction.
    cursor += inc;

    if (sign > 0) {
      for (; cursor < count; ++cursor) {
        if (children[cursor] == aPossibleChild) {
          AddIndexToCache(this, cursor);

          return static_cast<PRInt32>(cursor);
        }
      }
    }
    else {
      for (; cursor >= 0; --cursor) {
        if (children[cursor] == aPossibleChild) {
          AddIndexToCache(this, cursor);

          return static_cast<PRInt32>(cursor);
        }
      }
    }

    // The child wasn't even in the remaining children
    return -1;
  }

  for (i = 0; i < count; ++i) {
    if (children[i] == aPossibleChild) {
      return static_cast<PRInt32>(i);
    }
  }

  return -1;
}
void ZombieGenetics::Crossover(std::mt19937& a_random)
{
	unsigned int childCount = ChildCount();

	const float crossoverChance = 70.0f;

	for (int i = 0; i < childCount; i++)
	{
		Zombie	*childGenes = children[i].genes[0],
				*parent1Genes = parents[i * 2]->genes[0],
				*parent2Genes = parents[i * 2 + 1]->genes[0];

		childGenes->parentTraits.clear();
		childGenes->parentTraits.push_back(ParentTraits(parents[i * 2]->fitness, parent1Genes->speed, parent1Genes->strength, parent1Genes->maxHealth, parent1Genes->scale, parent1Genes->specialTraits));
		childGenes->parentTraits.push_back(ParentTraits(parents[i * 2 + 1]->fitness, parent2Genes->speed, parent2Genes->strength, parent2Genes->maxHealth, parent2Genes->scale, parent2Genes->specialTraits));

		std::uniform_real_distribution<float> distribution(0.0f, 99.0f);

#pragma region MAX_HEALTH
		if (distribution(a_random) - crossoverChance < 0.0f)
			childGenes->maxHealthRange.x = parent1Genes->maxHealthRange.x + parent2Genes->maxHealthRange.x / 2.0f;
		else
			childGenes->maxHealthRange.x = parent1Genes->maxHealthRange.x;

		if (distribution(a_random) - crossoverChance < 0.0f)
			childGenes->maxHealthRange.y = parent1Genes->maxHealthRange.y + parent2Genes->maxHealthRange.y / 2.0f;
		else
			childGenes->maxHealthRange.y = parent1Genes->maxHealthRange.y;
#pragma endregion MAX_HEALTH

#pragma region SIZE
		if (distribution(a_random) - crossoverChance < 0.0f)
			childGenes->scaleRange.x = parent1Genes->scaleRange.x + parent2Genes->scaleRange.x / 2.0f;
		else
			childGenes->scaleRange.x = parent1Genes->scaleRange.x;

		if (distribution(a_random) - crossoverChance < 0.0f)
			childGenes->scaleRange.y = parent1Genes->scaleRange.y + parent2Genes->scaleRange.y / 2.0f;
		else
			childGenes->scaleRange.y = parent1Genes->scaleRange.y;
#pragma endregion SIZE

#pragma region SPEED
		if (distribution(a_random) - crossoverChance < 0.0f)
			childGenes->speedRange.x = parent1Genes->speedRange.x + parent2Genes->speedRange.x / 2.0f;
		else
			childGenes->speedRange.x = parent1Genes->speedRange.x;

		if (distribution(a_random) - crossoverChance < 0.0f)
			childGenes->speedRange.y = parent1Genes->speedRange.y + parent2Genes->speedRange.y / 2.0f;
		else
			childGenes->speedRange.y = parent1Genes->speedRange.y;
#pragma endregion SPEED

#pragma region STRENGTH
		if (distribution(a_random) - crossoverChance < 0.0f)
			childGenes->strengthRange.x = parent1Genes->strengthRange.x + parent2Genes->strengthRange.x / 2.0f;
		else
			childGenes->strengthRange.x = parent1Genes->strengthRange.x;

		if (distribution(a_random) - crossoverChance < 0.0f)
			childGenes->strengthRange.y = parent1Genes->strengthRange.y + parent2Genes->strengthRange.y / 2.0f;
		else
			childGenes->strengthRange.y = parent1Genes->strengthRange.y;
#pragma endregion STRENGTH

#pragma region SPECIAL_TRAITS
		std::uniform_int_distribution<int> distribution2(0, 1);

		for (int j = 1; j != 256; j *= 2)
		{
			if (distribution2(a_random))
				childGenes->specialTraits |= parent1Genes->specialTraits & j;
			else
				childGenes->specialTraits |= parent2Genes->specialTraits & j;
		}
#pragma endregion SPECIAL_TRAITS
	}
}
Beispiel #30
0
void RenderRow(WINDOW* win, ND* node, int* row, int basecolumn, int rowindex,  int _y, int mode)
{

	int column = basecolumn + (2 * node->_ft_depth);

	if (node == NULL) {
		zlog_info(c, "Null Render (mode=%d, rowindex=%d)", mode, rowindex);
		return;
	}
	zlog_info(c, "[%d/%d]    Real_rende_call() %s at row %d/%d = col %d/%d",
		  rowindex, mode,  node->text,
		  *row, isExpanded(node), column, basecolumn);
	if (node->children != NULL && isExpanded(node)) {
		mvwhline(win, *row, column -  1, ACS_HLINE, 2 );
		mvwhline(win, *row, column - 1, ACS_URCORNER, 1 );

		//if (rowindex > 0) {
		//	mvwvline(win, (*row) - 1, column -  2, ACS_VLINE, 2 );
		//}
	}else{
		//if (node->children != NULL) {
		//	mvwhline(win, *row, column -  2, ACS_PLUS, 1 );
		//}else{
		//	//mvwhline(win, *row, column -  2, ACS_VLINE, 1 );
		//}
	}
	int _fkd = column + 1;
	/*
	 * Draw out all the lines back for the parent nodes
	 */
	if (rowindex == _selected) {
		wattron(win, COLOR_PAIR(4));
	}
	if (node->_ft_depth > 0) {
		while (true ) {
			_fkd--;
			_fkd--;
			if (_fkd <= basecolumn) {
				break;
			}
			mvwvline(win, (*row),  _fkd, ACS_VLINE, 1 );
			zlog_info(c, "         Working back, col now %d, %d, %d", node->_ft_depth,  _fkd, column);
		}
	}
	if (rowindex == _selected) {
		wattron(win, COLOR_PAIR(3));
	}

	/* Actually render the node details.
	 */

	// Clear the row...
	wmove(win, *row, column + 3);  wprintw(win, "                                                       ");
	// Draw the spine line to the text
	int SPLINE_COL = 4;
	mvwhline(win, *row, column - 1, ACS_HLINE, SPLINE_COL );
	if (node->next != NULL) {
		wmove(win, *row, column - 1 );  waddch(win, ACS_LTEE);
	}else{
		wmove(win, *row, column - 1 );  waddch(win, ACS_LLCORNER);
	}

	wmove(win, *row, basecolumn - 3);  wprintw(win, "%d", *row);
	if (node->children != NULL && !isExpanded(node)) {
		wmove(win, *row, column + SPLINE_COL);  wprintw(win, "(%d) %s",  TotalSize(node->children), substring(node->text, 60));
	}else{
		wmove(win, *row, column + SPLINE_COL);  wprintw(win, substring(node->text, 60));
	}
	wattron(win, COLOR_PAIR(3));
	wmove(win, *row, 85); wprintw(win, "cc=%4d  d=%4d ",
				      ChildCount(node, false),
				      node->_ft_depth
				      );
	wattroff(win, COLOR_PAIR(3));
	// deactivate colors
	if (rowindex == _selected) {
		wattroff(win, COLOR_PAIR(2));
	}

	zlog_info(c, "Done Rendering Leaving..");
	(*row)++;

	wattron(win, COLOR_PAIR(3));
	wmove(win, 2, 55); wprintw(win, "cc=%4d  d=%4d TTS=%4d SEL=%3d SR=%d R=%3d, NB=%3d B=%d, WS=%d",
				      ChildCount(node, false),
				      node->_ft_depth,
				      _total_tree_size,
				      _selected,
				      start_row,
				      *row,
				      _selected - start_row,
				      _selected - start_row > WINDOW_SIZE,
				      WINDOW_SIZE

				      );
	wattroff(win, COLOR_PAIR(3));
}