Code archives/3D Graphics - Misc/NextChild(entity) function

This code has been declared by its author to be Public Domain code.

Download source code

NextChild(entity) function by Beaker2003
Deceptively simple and very useful non-recursive function that allows you to access all sub-entities of a model as though they were all on the same level of the hierarchy. Very useful for applying an effect to a model in its entirety.

[EDIT: This was a hard one to name, I did consider calling it NextEntity(). It basically returns the next entity - either the next sibling, first child or whatever until you have "seen" all entities in the model tree structure. ]

Example of use - show names of all entities
alien = LoadAnimMesh("alien.b3d")

ent = alien
While ent
	DebugLog EntityName(ent)
	ent = NextChild(ent)
Wend


Example 2 - change alpha of all entites
alien = LoadAnimMesh("alien.b3d")

ent = alien
While ent
	EntityAlpha ent,0.3
	ent = NextChild(ent)
Wend


Example 3 - count all tris in entity
alien = LoadAnimMesh("alien.b3d")

tris=0
ent = alien
While ent
	For i = 1 To CountSurfaces(ent)
		tris = tris + CountTriangles(GetSurface(ent, i))
	Next
	ent = NextChild(ent)
Wend
Debuglog tris


Function:
Function NextChild(ent)
	Local siblingcnt
	If CountChildren(ent)>0
		Return GetChild(ent,1)
	EndIf

	Local foundunused=False
	Local foundent = 0, parent,sibling
	While foundunused=False And ent<>0
		parent = GetParent(ent)
		If parent<>0
			If CountChildren(parent)>1
				If GetChild(parent,CountChildren(parent))<>ent
					For siblingcnt = 1 To CountChildren(parent)
						sibling = GetChild(parent,siblingcnt)
						If sibling=ent
							foundunused = True
							foundent = GetChild(parent,siblingcnt+1)
						EndIf
					Next
				EndIf
			EndIf
		EndIf
		ent = parent
	Wend
	Return foundent
End Function

Comments

Beaker2007
I've fixed an undeclared variable in NextChild().

Also, some more related functions:
Function NextSibling(ent)
	Local childcnt,child
	Local par = GetParent(ent)
	If CountChildren(par)=1 Then Return False
	For childcnt = 1 To CountChildren(par)-1
		child = GetChild(par,childcnt)
		If child = ent Then Return GetChild(par,childcnt+1)
	Next
	Return False
End Function

Function PrevSibling(ent)
	Local childcnt,child
	Local par = GetParent(ent)
	If CountChildren(par)=1 Then Return False
	For childcnt = CountChildren(par) To 2 Step -1
		child = GetChild(par,childcnt)
		If child = ent Then Return GetChild(par,childcnt-1)
	Next
	Return False
End Function

;examples
alien = LoadAnimMesh("alien.b3d")
ent = GetChild(alien,CountChildren(alien))
While ent
	DebugLog EntityName(ent)
	ent = PrevSibling(ent)
Wend

ent = GetChild(alien,1)
While ent
	DebugLog EntityName(ent)
	ent = NextSibling(ent)
Wend



_PJ_2007
Very helpful!


_332007
NextChild doesn't seem to work on 1.99! Can anyone confirm this?


Code Archives Forum