Authoring a Model Entity: Difference between revisions

From Valve Developer Community
Jump to navigation Jump to search
m (→‎Spawn(): thinking about this, it actually makes a lot of sense)
m (tweaks)
Line 59: Line 59:
  <span style="color:blue;">#define</span> ENTITY_MODEL <span style="color:brown;">"models/gibs/airboat_broken_engine.mdl"</span>
  <span style="color:blue;">#define</span> ENTITY_MODEL <span style="color:brown;">"models/gibs/airboat_broken_engine.mdl"</span>


This hard-codes the [[model]] that our entity will present to the world. This is a static piece of information, not a variable: it cannot change once the code has been compiled. The path to the .mdl file is relative to the game directory (e.g. <code>/hl2/</code>).
This hard-codes the [[model]] that our entity will present to the world. This is a static piece of information, not a variable: it cannot change once the code has been compiled. The path to the .mdl file is relative to the game directory (e.g. <code>hl2/</code>).


{{note|We are only creating this define to make finding and changing its value later on easier. It has no effect on how our code works.}}
{{note|We are only creating this define to make finding and changing its value later on easier. It has no effect on how our code works.}}
Line 122: Line 122:
== MoveThink() ==
== MoveThink() ==


A [[Think]] function allows an entity to make decisions without being prompted by an external source. If you think back to our logical entity, it only ever did anything when it received an input; this is clearly no good for something that is meant to move around of its own accord. A think function, if present, is usually the core of the entity's programming.
A [[Think()|think function]] allows an entity to make decisions without being prompted by an external source. If you think back to our logical entity, it only ever did anything when it received an input; this is clearly no good for something that is meant to move around of its own accord. A think function, if present, is usually the core of the entity's programming.


Here we create a think function that will be called up to 20 times a second. This may sound like a lot, but modern processors are very fast and this entity is very simple. You'll be able to have an awful lot of <code>CMyModelEntity</code>s in a map without running into any CPU issues!
Here we create a think function that will be called up to 20 times a second. This may sound like a lot, but modern processors are very fast and this entity is very simple. You'll be able to have an awful lot of <code>CMyModelEntity</code>s in a map without running into any CPU issues!
Line 157: Line 157:


*<code>[[gpGlobals]]->curtime</code> returns the time at which the code is being executed as a floating point value.
*<code>[[gpGlobals]]->curtime</code> returns the time at which the code is being executed as a floating point value.
*<code>[[Wikipedia:Vector (spatial)|Vector]]</code>s are used for movement, since they contain information about both facing and speed. <code>[[SetAbsVelocity]]</code> 'Sets' the 'Absolute' 'Velocity' with one.
*<code>[[Wikipedia:Vector (spatial)|Vector]]</code>s are used for movement, since they contain information about both facing and speed. <code>[[SetAbsVelocity()]]</code> 'Sets' the 'Absolute' 'Velocity' with one.
*<code>[[QAngle]]</code> is simply an angle - a vector minus data about velocity. It's used to set facing.
*<code>[[QAngle]]</code> is simply an angle - a vector minus data about velocity. It's used to set facing.
*<code>[[VectorAngles]]</code> converts a vector (<code>velFacing</code>) to an angle (<code>angFacing</code>). Remember that C++ is very strict about data types: you need utility functions to convert between any two.
*<code>[[VectorAngles()]]</code> converts a vector (<code>velFacing</code>) to an angle (<code>angFacing</code>). Remember that C++ is very strict about data types: you need utility functions to convert between any two.


Having done all this we call <code>[[SetNextThink()]]</code>. This tells the entity when next to run its think function. Here it is set to think again in 0.05 seconds (1/20th), but that number can vary between entities. It’s important to note that failure to use SetNextThink() will cause the entity to stop thinking (which is sometimes desired).
Having done all this we call <code>[[SetNextThink()]]</code>. This tells the entity when next to run its think function. Here it is set to think again in 0.05 seconds (1/20th), but that number can vary between entities. It’s important to note that failure to use SetNextThink() will cause the entity to stop thinking (which is sometimes desired).
Line 204: Line 204:
When activating the entity we start its think loop by telling Source what think function to use (the default is <code>[[Think()]]</code>, but we don't have that here) - note the addition of an & and the omission of any parentheses in the argument. We then tell Source that the entity will move by flying, although this would actually be better-described as "floating" since there is no true simulation of flight in Source (perhaps you could make one?). And, of course, we set <code>m_bActive</code> to true. It isn't going to change itself!
When activating the entity we start its think loop by telling Source what think function to use (the default is <code>[[Think()]]</code>, but we don't have that here) - note the addition of an & and the omission of any parentheses in the argument. We then tell Source that the entity will move by flying, although this would actually be better-described as "floating" since there is no true simulation of flight in Source (perhaps you could make one?). And, of course, we set <code>m_bActive</code> to true. It isn't going to change itself!


Under the <code>else</code> command we stop the entity from moving. The active think function is set to <code>NULL</code> to stop all thinking, <code>[[AbsVelocity]]</code> is set to the entity's  [[origin]], a vector with no movement, the movement type is set to <code>[[MOVETYPE_NONE]]</code> to prevent any kind of movement that might be imposed externally, and lastly <code>m_bActive</code> is made false.
Under the <code>else</code> command we stop the entity from moving. The active think function is set to <code>NULL</code> to stop all thinking, <code>[[AbsVelocity()]]</code> is set to the entity's  [[origin]], a vector with no movement, the movement type is set to <code>[[MOVETYPE_NONE]]</code> to prevent any kind of movement that might be imposed externally, and lastly <code>m_bActive</code> is made false.


== FGD entry ==
== FGD entry ==
Line 224: Line 224:
:The model is spawning halfway inside the wall...can you fix it?
:The model is spawning halfway inside the wall...can you fix it?
;It doesn't collide with physics objects
;It doesn't collide with physics objects
:The <code>SetAbs*</code> commands interfere with physics calculations. If you want to physically simulate collisions, you'll need to use a different method for movement.
:The <code>SetAbs*</code> functions interfere with physics calculations. If you want to physically simulate collisions, you'll need to use a different method of movement.
;It will dodge around me every time I get in its way
;It will dodge around me every time I get in its way
:It isn't clear why this happens. Perhaps <code>CBaseAnimating</code> thinks every time its path is blocked?
:It isn't clear why this happens. Perhaps <code>CBaseAnimating</code> thinks every time its path is blocked?
Line 231: Line 231:


*[[Model Entity|Tutorial code in full]]
*[[Model Entity|Tutorial code in full]]
*[[My First Entity]]


{{otherlang:en}}
{{otherlang:en}}

Revision as of 11:02, 27 February 2008

This tutorial assumes you have completed and understood Authoring a Logical Entity.

In this tutorial we'll create an entity that can move, collide with other objects, and that has a visual component (in this case, a model). We will make the entity randomly move around the world.

Create Server/Source Files/sdk_modelentity.cpp and we'll begin.

Include and Declare

You should understand this code now:

#include "cbase.h"

class CMyModelEntity : public CBaseAnimating
{
public:
	DECLARE_CLASS( CMyModelEntity, CBaseAnimating );
	DECLARE_DATADESC();

	void Spawn( void );
	void Precache( void );

	void MoveThink( void );

	// Input function
	void InputToggle( inputdata_t &inputData );

private:

	bool	m_bActive;
	float	m_flNextChangeTime;
};

Notice how we are now inheriting from CBaseAnimating, and how we have some new functions. The private variables are a boolean (true/false) and a floating point (decimalised number).

Entity name and Datadesc

LINK_ENTITY_TO_CLASS( my_model_entity, CMyModelEntity );

// Start of our data description for the class
BEGIN_DATADESC( CMyModelEntity )
	
	// Save/restore our active state
	DEFINE_FIELD( m_bActive, FIELD_BOOLEAN ),
	DEFINE_FIELD( m_flNextChangeTime, FIELD_TIME ),

	// Links our input name from Hammer to our input member function
	DEFINE_INPUTFUNC( FIELD_VOID, "Toggle", InputToggle ),

	// Declare our think function
	DEFINE_THINKFUNC( MoveThink ),

END_DATADESC()

The biggest change here from our logical entity is DEFINE_THINKFUNC. Think functions are special cases in Source, and we need to identify them.

Defining the model

// Name of our entity's model
#define	ENTITY_MODEL	"models/gibs/airboat_broken_engine.mdl"

This hard-codes the model that our entity will present to the world. This is a static piece of information, not a variable: it cannot change once the code has been compiled. The path to the .mdl file is relative to the game directory (e.g. hl2/).

Note.pngNote:We are only creating this define to make finding and changing its value later on easier. It has no effect on how our code works.

Precache()

Now we come to our first function. Precache() should be called when an entity spawns, and ensures that loading of whatever is listed in it occurs before the player spawns (i.e. sees the world and gains control). See Precaching Assets for more information.

Precaching gets a special name because there are other types of "asynchronous" loading that can occur after player spawn.

//-----------------------------------------------------------------------------
// Purpose: Precache assets used by the entity
//-----------------------------------------------------------------------------
void CMyModelEntity::Precache( void )
{
	PrecacheModel( ENTITY_MODEL );
}

For this entity there is only one resource that needs precaching. More complex entities might also precache sounds, particle effects, and so on. No matter how much loading needs to be done though, this is generally a very simple function.

Spawn()

You may have noticed the absence of a constructor from the class declaration. That is because we're now using Valve's Spawn() function instead. Like a constructor it gets called every time an instance is made, but it does some Source-specific things as well.

//-----------------------------------------------------------------------------
// Purpose: Sets up the entity's initial state
//-----------------------------------------------------------------------------
void CMyModelEntity::Spawn( void )
{
	Precache();

	SetModel( ENTITY_MODEL );
	SetSolid( SOLID_BBOX );
	UTIL_SetSize( this, -Vector(20,20,20), Vector(20,20,20) );

	m_bActive = false;
}

We call Precache() first of course, followed by several CBaseAnimating functions.

SetModel() should be obvious if you think back to our earlier define, but SetSolid() needs some explanation. It defines the shape of our entity in the world. Using the model itself would be far, far too expensive, so Source offers us a set of compromises:

SOLID_NONE
Not solid.
SOLID_BBOX
Uses an axis-aligned bounding box.
SOLID_BSP
Uses the BSP tree to determine solidity (used for brushes).
SOLID_CUSTOM
Entity defines its own functions for testing collisions.
SOLID_VPHYSICS
Uses a model's embedded collision model to test accurate physics collisions.

These are engine-level choices that mod authors cannot change or add to. We are using SOLID_BBOX, which generates a "bounding box" that is sized by the engine to completely enclose our model. The more expensive SOLID_VPHYSICS, which physically simulates collisions based on the model's embedded collision mesh, doesn't support the low-level movement functions we'll be using for this entity and should be avoided.

We call UTIL_SetSize() to make our bounding box a cube. This is done because, as bizarre as this might at first sound, bounding boxes cannot rotate. You will need vphysics collisions if you want rotation, and as noted above we aren't using them.

Lastly for Spawn(), we "initialise" m_bActive in order to default our entity to inactivity. Variables do not have default values, and failing to give them one before their use can have weird and wacky results!

Warning.pngWarning:Spawn() is called immediately after the creation of the entity. If this has occurred at the beginning of a map there is no guarantee that other entities have been spawned yet. Therefore, any code which requires the entity to search or otherwise link itself to other entities is unreliable. Use the Activate() function instead, which is always called after all spawning has completed.

MoveThink()

A think function allows an entity to make decisions without being prompted by an external source. If you think back to our logical entity, it only ever did anything when it received an input; this is clearly no good for something that is meant to move around of its own accord. A think function, if present, is usually the core of the entity's programming.

Here we create a think function that will be called up to 20 times a second. This may sound like a lot, but modern processors are very fast and this entity is very simple. You'll be able to have an awful lot of CMyModelEntitys in a map without running into any CPU issues!

//-----------------------------------------------------------------------------
// Purpose: Think function to randomly move the entity
//-----------------------------------------------------------------------------
void CMyModelEntity::MoveThink( void )
{
	// See if we should change direction again
	if ( m_flNextChangeTime < gpGlobals->curtime )
	{
		// Randomly take a new direction and speed
		Vector vecNewVelocity = RandomVector( -64.0f, 64.0f );
		SetAbsVelocity( vecNewVelocity );

		// Randomly change it again within one to three seconds
		m_flNextChangeTime = gpGlobals->curtime + random->RandomFloat( 1.0f, 3.0f );
	}

	// Snap our facing to where we're heading
	Vector velFacing = GetAbsVelocity();
	QAngle angFacing;
	VectorAngles( velFacing, angFacing );
 	SetAbsAngles( angFacing );

	// Think every 20Hz
	SetNextThink( gpGlobals->curtime + 0.05f );
}

While a lot of code is packed into this function, its outcome is fairly simple. Once a random time interval has elapsed, the entity will choose a new, random direction and speed to travel at. It will also update its angles so that the model visibly faces towards the new direction. This occurs in three dimensions.

Some help:

  • gpGlobals->curtime returns the time at which the code is being executed as a floating point value.
  • Vectors are used for movement, since they contain information about both facing and speed. SetAbsVelocity() 'Sets' the 'Absolute' 'Velocity' with one.
  • QAngle is simply an angle - a vector minus data about velocity. It's used to set facing.
  • VectorAngles() converts a vector (velFacing) to an angle (angFacing). Remember that C++ is very strict about data types: you need utility functions to convert between any two.

Having done all this we call SetNextThink(). This tells the entity when next to run its think function. Here it is set to think again in 0.05 seconds (1/20th), but that number can vary between entities. It’s important to note that failure to use SetNextThink() will cause the entity to stop thinking (which is sometimes desired).

InputToggle()

Now we come to our last function. This is an input that will toggle movement on and off.

//-----------------------------------------------------------------------------
// Purpose: Toggle the movement of the entity
//-----------------------------------------------------------------------------
void CMyModelEntity::InputToggle( inputdata_t &inputData )
{
	// Toggle our active state
	if ( !m_bActive )
	{
		// Start thinking
		SetThink( &CMyModelEntity::MoveThink );

		SetNextThink( gpGlobals->curtime + 0.05f );
		
		// Start flying
		SetMoveType( MOVETYPE_FLY );

		// Set our next time for changing our speed and direction
		m_flNextChangeTime = gpGlobals->curtime;
		m_bActive = true;
	}
	else
	{
		// Stop thinking
		SetThink( NULL );
		
		// Stop moving
		SetAbsVelocity( vec3_origin );
 		SetMoveType( MOVETYPE_NONE );
		
		m_bActive = false;
	}
}

This is all very straightforward. We use an if statement to check whether or not m_bActive is true. The exclamation mark means "not": "if m_bActive is not true, do this". Later on, we use the else command to specify what we want to do in any other case - which with a boolean value can only be if m_bActive is true.

When activating the entity we start its think loop by telling Source what think function to use (the default is Think(), but we don't have that here) - note the addition of an & and the omission of any parentheses in the argument. We then tell Source that the entity will move by flying, although this would actually be better-described as "floating" since there is no true simulation of flight in Source (perhaps you could make one?). And, of course, we set m_bActive to true. It isn't going to change itself!

Under the else command we stop the entity from moving. The active think function is set to NULL to stop all thinking, AbsVelocity() is set to the entity's origin, a vector with no movement, the movement type is set to MOVETYPE_NONE to prevent any kind of movement that might be imposed externally, and lastly m_bActive is made false.

FGD entry

The FGD entry for this entity displays the model in Hammer and allows you to name it and send the input "Toggle".

@PointClass base(Targetname) studio("models/gibs/airboat_broken_engine.mdl")= my_model_entity :  "Tutorial model entity."
[
	input Toggle(void) : "Toggle movement."
]

The working entity

my_model_entity in-game.

Play with your entity. You can use the console command ent_fire my_model_entity toggle to get it moving without map I/O. You'll notice a few things:

If I spawn it flush against the ground, it will rotate but not move
The model is spawning halfway inside the wall...can you fix it?
It doesn't collide with physics objects
The SetAbs* functions interfere with physics calculations. If you want to physically simulate collisions, you'll need to use a different method of movement.
It will dodge around me every time I get in its way
It isn't clear why this happens. Perhaps CBaseAnimating thinks every time its path is blocked?

See also

Template:Otherlang:en Template:Otherlang:en:ru