Advertisement

Member function chaining?

Started by December 25, 2012 09:10 PM
5 comments, last by Paril101 11 years, 11 months ago

Hey there.

I'm just beginning to use AngelScript for my own project, and I must say it is brilliant. This is the first thing I've needed to get help on, as the documentation is extremely helpful.

Okay, so basically, here's my question: is it possible via AngelScript API to register a type that utilizes the well-known member function chaining method? An example of such a class is below:


class ChainMe
{
public:
	int X;

	ChainMe() :
		X(0)
	{
	}

	ChainMe &Increase(const int &v)
	{
		X += v;
		return *this;
	}
};


How would one register such a type in AngelScript so that you may use it from AngelScript as you would from C++, like:

ChainMe().Increase(5).Increase(15).Increase(25)

My first (failed) attempt at doing this involved this very basic implementation:


engine->RegisterObjectType("ChainMe", sizeof(ChainMe), asOBJ_VALUE | asOBJ_POD | asOBJ_APP_CLASS_C);
engine->RegisterObjectMethod("ChainMe", "ChainMe &Increase(const int &in)", asMETHOD(ChainMe, Increase), asCALL_THISCALL);

(This also included a constructor but they aren't important for this sample)

The engine runs the constructor, as expected, then runs Increase, as expected.. however, following that, it calls the constructor again, then errors with "GC cannot free an object of type '_builtin_objecttype_', it is kept alive by the application".

EDIT: I managed to get the error to go away by adding asOBJ_NOHANDLE to the type flags. I think that this was the problem. I'm still getting a two-constructor call when I try passing the return value of the functions to another function via a reference (ie, "const ChainMe &in")

EDIT2: Via adding one extra function (which I love about AngelScript), I have figured out that the "extra constructor" being called is the copy constructor. Fair enough, but, why is it copying when it only needs to pass a reference? Is it because it is an r-value reference?

Thanks in advance,

-P

Chaining method calls works and shouldn't cause any extra copies to be made.

Copies are however made at times when passing objects to functions as arguments. This is because AngelScript must guarantee the lifetime of the objects so there is no chance of them being destroyed while the function is still being executed. This is different from C++ where the lifetime of the objects is not guaranteed by the language, and it is up to the programmer to write the appropriate code that doesn't invalidate a reference before it is used.

Exactly when copies are made or not made depends on a lot of factors, e.g. the type of reference the function takes, whether the object is a local variable or not, etc.

An in-reference, i.e. &in, is meant as an input value for the function. This means that AngelScript must guarantee that the original object is not modified. Because of this AngelScript will almost always create a copy of the value, when passing it to a function like this. By making the reference const, AngelScript can avoid making copies in many situations, but there are still situations where copies are made.

Note that declaring a script function that takes a parameter as &in doesn't make much sense, as it is essentially the same as taking the parameter by value. This reference type is mostly there for compatibility with C++ implemented functions, where taking input arguments by reference is common to maintain good performance.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

Advertisement

I always use const &in for most of my types as that seems to work. If I try without in I get yelled at because apparently this type doesn't support inout, and out definitely isn't what I want (nor works), and I want to avoid needlessly creating copies by always passing by value.


namespace Default
{
	class DefaultRenderer : ::IBlockRenderer
	{
		void Render(const ::Block &in block, const ::Point3i &in position)
		{
			::renderer.Draw(::Box().SetAll(::Point2i(0, 0), ::Colorb(255, 0, 255, 255)));
		}
	}
}



	r = engine->RegisterObjectType("Box", sizeof(Box), asOBJ_VALUE | asOBJ_POD | asOBJ_APP_CLASS_CK | asOBJ_NOHANDLE); assert(r >= 0);
	r = engine->RegisterObjectBehaviour("Box", asBEHAVE_CONSTRUCT, "void f(int, Point3i, Point3i)", asFUNCTION(ConstructBox3), asCALL_CDECL_OBJLAST); assert(r >= 0);
	r = engine->RegisterObjectBehaviour("Box", asBEHAVE_CONSTRUCT, "void f(int, Point3i)", asFUNCTION(ConstructBox2), asCALL_CDECL_OBJLAST); assert(r >= 0);
	r = engine->RegisterObjectBehaviour("Box", asBEHAVE_CONSTRUCT, "void f(int)", asFUNCTION(ConstructBox1), asCALL_CDECL_OBJLAST); assert(r >= 0);
	r = engine->RegisterObjectBehaviour("Box", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ConstructBox0), asCALL_CDECL_OBJLAST); assert(r >= 0);
	r = engine->RegisterObjectBehaviour("Box", asBEHAVE_CONSTRUCT, "void f(const Box &in)", asFUNCTION(ConstructBoxC), asCALL_CDECL_OBJLAST); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &Unwrap(const Point2i &in)", asMETHOD(Box, Unwrap), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetIndex(const int &in, const Point2i &in, const Colorb &in)", asMETHOD(Box, SetIndex), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetRange(const int &in, const int &in, const Point2i &in, const Colorb &in)", asMETHOD(Box, SetRange), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetNorth(const Point2i &in, const Colorb &in)", asMETHOD(Box, SetNorth), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetEast(const Point2i &in, const Colorb &in)", asMETHOD(Box, SetEast), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetSouth(const Point2i &in, const Colorb &in)", asMETHOD(Box, SetSouth), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetWest(const Point2i &in, const Colorb &in)", asMETHOD(Box, SetWest), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetBottom(const Point2i &in, const Colorb &in)", asMETHOD(Box, SetBottom), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetTop(const Point2i &in, const Colorb &in)", asMETHOD(Box, SetTop), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetSides(const Point2i &in, const Colorb &in)", asMETHOD(Box, SetSides), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetAll(const Point2i &in, const Colorb &in)", asMETHOD(Box, SetAll), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetInset(const int &in, const int &in)", asMETHOD(Box, SetInset), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetTopInset(const int &in)", asMETHOD(Box, SetTopInset), asCALL_THISCALL); assert(r >= 0);
	r = engine->RegisterObjectMethod("Box", "Box &SetSidesInset(const int &in)", asMETHOD(Box, SetSidesInset), asCALL_THISCALL); assert(r >= 0);

Is there anything I'm doing particularly wrong? It all seems to work properly, so I'm just not sure if I'm breaking standards or what.

-P

Hmm, asOBJ_NOHANDLE is not meant to be used with asOBJ_VALUE. In fact, the library should have returned an error with this combination (I'll have that fixed).

asOBJ_NOHANDLE is meant to be used in combination with asOBJ_REF, where it tells AngelScript that the script must not store any handles to the type besides the one that the application registers. This is normallly used for singletons.

http://www.angelcode.com/angelscript/sdk/docs/manual/doc_adv_single_ref_type.html



const &in is the most performatic for value types, as it will allow the compiler to avoid the extra copy in most cases. &inout or just & is not allowed for value types, because AngelScript cannot guarantee the lifetime of the object in all cases. You can bypass this with SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, true), but then you're shifting the responsibility of guaranteeing the lifetime of the objects to the script writer.


In your script above the compiler has to make a copy because it doesn't know that the reference returned by the SetAll() method really is the same object that was constructed earlier. In order to guarantee that the object pointed to by the reference really isn't modified it will make the copy.

If you declare and initialize the Box as a local variable, and then pass that variable to the Draw() function the compiler will not make the extra copy. Of course, the script code won't be as compact this way, so I can understand why you don't want to do that.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

Hey.

Thanks for the response. I imagine this is exactly like C++ then, with certain optimizations turned off, what will happen is the object will be constructed, then copied to a local variable on the stack, -then- passed by reference to the function. In a way, it's akin to doing this (in C++):

void CallFunc(const Box &);

Box box = Box(...);

CallFunc(box);

I can understand if AngelScript just doesn't have this optimization to pass r-value references that are constructed right during the call. No problem smile.png

If I remove asOBJ_NOHANDLE will it just function normally? It may have been when I was experimenting with different flags to get it working.


EDIT: It's the only type I used that on, as it was the first I created during my AngelScript times. All of my other types only have "asOBJ_VALUE | asOBJ_POD | asOBJ_APP_CLASS_CAK".


EDIT2: I'm really excited because I -just- finished the first build which now supports AngelScript for defining block renderers. I figure I would show this off since I assume you like seeing things that can be done with your offspring ;)

http://i.imgur.com/wSssV.png

(Module.as)


namespace Default
{
	// Returns a ModuleInfo which defines this
	// module.
	::ModuleInfo GetInfo()
	{
		return ::ModuleInfo
				(
					"Minecraft Block Renderers",	// Module name (any characters)
					"mcdefaultblocks",				// Module friendly name (lowercase only, no symbols)
					"1.0",							// Module version
					"Paril"							// Module author
				);
	}
	
	// Initializes and creates renderers.
	void Init(::RendererBase &renderer)
	{
		::ITexture terrain = renderer.GetTexture("terrain.png");

		::AddRenderer(77, Default::ButtonRenderer(terrain, ::Point2i(1 * 16, 0 * 16)));
	}
}

(ButtonRenderer.as)


namespace Default
{
	class ButtonRenderer : ::IBlockRenderer
	{
		ButtonRenderer(::ITexture texture, const ::Point2i &in pos)
		{
			Texture = texture;
			Position = pos;
		}

		void Render(::RendererBase &renderer, const ::Block &in block, const ::Point3i &in position)
		{
			renderer.Translate(8, 8, 8);

			switch (block.Data & 0x07)
			{
			case 1:
				renderer.Rotate(90, 0, 1, 0);
				break;
			case 2:
				renderer.Rotate(-90, 0, 1, 0);
				break;
			case 3:
				break;
			case 4:
				renderer.Rotate(180, 0, 1, 0);
				break;
			}

			renderer.Translate(-8, -8, -8);

			renderer.Draw(::Box(Texture, ::Point3i(6, 4, (block.Data & 0x08) != 0 ? 1 : 2), ::Point3i(5, 6, 0)).SetAll(::Point2i(Position.X + 5, Position.Y + 6)));
		}

		::ITexture Texture;
		::Point2i Position;
	}
}

One tiny question though: why do I have to explicitly specify the namespace for "Default::ButtonRenderer" (in Default::Init) when the current namespace already IS Default? Without it, I get an error that ButtonRenderer is not a proper classname. Is it because they are in different files?

-P

The word 'Minecraft' strikes out at me smile.png

Are you writing some scriptable plugin for Minecraft? I haven't really gotten into Minecraft myself, but I understand its community is huge and it would definitely be exciting to see AngelScript exposed to that community.


It would appear you've found one of those bugs about namespaces that I mentioned in your other thread about removing ::. You're right, it shouldn't be necessary to specify the namespace in Default::Init. I'll look into this as soon as possible.

AngelCode.com - game development and more - Reference DB - game developer references
AngelScript - free scripting library - BMFont - free bitmap font generator - Tower - free puzzle game

Advertisement

I'm working on a program:

http://planetminecraft.com/project/mschemv

In short, it's a schematic viewer - schematics are collections of blocks that can be imported into maps. It may also support worlds in the future, but atm it only works on Schematics.

I am using AngelScript to supply block renderers (the logic which renders the block itself). Some of these renderers get pretty intense in their logic, so it's neat to see how this is going to work out.

I planned to allow users to create their own modules for block rendering, as modifications are HUGE in Minecraft. I looked at a -lot- of different scripting engines, and I just happened to come across AngelScript on a whim and decided to try it out. I have not been disappointed in the slightest. I was so close to being set on using Lua.. but it was giving me too much trouble.

Basically, my checklist for a scripting engine was something like this:

- Loading external files into groups of modules (in this case I'm using namespaces as pseudo-modules)

- Allow modules to communicate (ie, if somebody makes a new module which includes a very similar block to another module, they can grab the renderer from that module rather than re-writing code for it)

- Compiles into bytecode (I would like to support compiled versions to decrease file sizes)

While those are my basic requirements for implementation, I also had a standard in my mind set for how easy the API should be to access, as well as how easy the language is to learn. While the latter -might- be a problem with new programmers, if I have enough samples it shouldn't be a problem.. as for the API, I don't think you could have done a better job at making it clear.

If you'd like to follow the progress in-depth, you can follow the source code here:

http://code.google.com/p/mschemv

(Most of the AngelScript stuff is here: http://code.google.com/p/mschemv/source/browse/trunk/MSchemVLib/Scripting/RenderScriptEngine.cpp )

It seems to work without any flaws so far. I was able to destroy the engine and it did not throw any errors. I just noticed too while uploading that you generate debug stats on Debug mode.. my god it's amazing.

-P

This topic is closed to new replies.

Advertisement