In this forum post morez posted the following helpful bit on the Squirrel Scripting Language...
Table of contents
Intro
Hi guys,
In this topic I would like to explain how to set up a very simple application and use Squirrel for scripting (instead of Lua for example ๐ )
Squirrel is very nice high level imperative/OO programming language with syntax similar to C/C++ developed by Alberto Demichelis. I'm going to use SQPlus, developed by John Schultz, to bind Squirrel to C++.
This code example has been inspired by the LuaBind example in wiki page.
What do you need?
Note that I'm using Microsoft Visual Studio .NET 2003 (7.1).
You need Ogre (SDK or source) Squirrel and SQPlus of course ๐. SQPlus contains the last stable version of Squirrel. So, download it and compile.
Create the Project
I used the wizard to create a simple Standard Ogre Application. I called it SquirrelOgre.
Let's Include some stuff
Note that this simple example is made in debug mode. So in C++ general (Project properties) add:
- path/to/Squirrel/sqplus
- path/to/Squirrel/include
In Linker general add:
- path/to/Squirrel/lib
In Linker dependencies add:
- squirrelD.lib
- sqstdlibD.lib
- sqplusD.lib
If you are running *nix
gcc will need the following options:
- -Ipath/to/Squirrel/sqplus
- -Ipath/to/Squirrel/include
- -Lpath/to/Squirrel/lib
- -lsquirrel
- -lsqstdlib
- -lsqplus
Let's code
This is main.cpp. We do not change this file, I'll do everything in the header file. This is not a clear style code programming lesson ๐
#include "SquirrelOgre.h" #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include "windows.h" #endif #ifdef __cplusplus extern "C" { #endif #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT ) #else int main(int argc, char *argv[]) #endif { // Create application object SquirrelOgre app; SET_TERM_HANDLER; try { app.go(); } catch( Ogre::Exception& e ) { #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 MessageBox( NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL); #else std::cerr << "An exception has occured: " << e.getFullDescription().c_str() << std::endl; #endif } return 0; } #ifdef __cplusplus } #endif
Ok so let's see how to make our header file SquirrelOgre.h
#ifndef __SquirrelOgre_h_ #define __SquirrelOgre_h_ #include "sqplus.h" // Include the SQPlus header #include "ExampleApplication.h" #include <stdarg.h> // needed for redirecting squirrel output using namespace SqPlus; // SqPlus namespace
Simple and clear.
// ==================================================================== // Define a custom constructor for Vector 3 // ==================================================================== int constructVector3(int x, int y, int z, HSQUIRRELVM v) { return PostConstruct<Vector3>(v, new Vector3(x, y, z), ReleaseClassPtr<Vector3>::release); } SQ_DECLARE_RELEASE(Vector3) // This is required when using a custom constructor
Here we have declared a custom constructor for the Ogre::Vector3 class.
// ==================================================================== // Actor class this is a cut & paste from LuaBind wiki tutorial ;) // ==================================================================== class Actor { public: Actor() {} Actor( std::string sName, SceneManager *pSceneMgr, Vector3 v3Position, Vector3 v3Scale ) { mName = sName; mSceneMgr = pSceneMgr; std::stringstream ss; ss << mName << "_ControlNode"; mControlNode = pSceneMgr->getRootSceneNode()->createChildSceneNode( ss.str(), v3Position ); ss.flush(); ss << mName << "_Entity"; mEntity = pSceneMgr->createEntity( ss.str(), "ogrehead.mesh" ); mControlNode->attachObject( mEntity ); mControlNode->setScale( v3Scale ); } ~Actor(){} void setMaterialName( const SQChar* sMaterialName ) { mEntity->setMaterialName( sMaterialName ); } void setScale( Vector3* v3Scale ) { mControlNode->setScale( *v3Scale ); } void setPosition( Vector3* v3Position ) { mControlNode->setPosition( *v3Position ); } void setMesh( const SQChar* sMeshResourceName ) { if( mEntity ) { mControlNode->detachObject( mEntity->getName() ); mSceneMgr->removeEntity( mEntity ); mEntity = 0; } mEntity = mSceneMgr->createEntity( mName, sMeshResourceName ); mControlNode->attachObject( mEntity ); } protected: std::string mName; SceneNode *mControlNode; Entity *mEntity; SceneManager *mSceneMgr; }; // Declare both Actor and Vector3 class DECLARE_INSTANCE_TYPE(Actor) DECLARE_INSTANCE_TYPE(Vector3)
Here we have declared the Actor class and called the macro DECLARE_INSTANCE_TYPE for both Actor and Ogre::Vector3 classes. Note that the Actor class methods parameters are passed by reference in setScale and setPosition methods and I've used const SQChar* instead of std::string in setMaterialName and setMesh.
class SquirrelOgre : public ExampleApplication { virtual void createScene(void) { SquirrelVM::Init(); // Start the virtual machine Ogre::LogManager::getSingletonPtr()->createLog("squirrel.log"); sq_setprintfunc(SquirrelVM::GetVMPtr(), SquirrelOgre::printFunc); // Redirect the VM output, print func is declared below // The following reads the test.nut script using Ogres Resource manager: DataStreamPtr pStream = ResourceGroupManager::getSingleton().openResource( "Test.nut", "General"); // open the script file String filestream = pStream->getAsString(); SquirrelObject testSquirrel = SquirrelVM::CompileBuffer(filestream.c_str()); // Compile the script // This is if you instead want to open the test.nut file in the current directory and avoid the Ogre resource manager: // SquirrelObject testSquirrel = SquirrelVM::CompileScript("Test.nut"); try { SquirrelVM::RunScript(testSquirrel); // run the script } catch(SquirrelError & e) { // catch exceptions and print them out through the custom print function sq_getprintfunc(SquirrelVM::GetVMPtr()) (SquirrelVM::GetVMPtr(),_T("Error: %s, %s\n"),e.desc); } // Bind the Vector3 class SQClassDef<Vector3>(_T("Vector3")). staticFunc(constructVector3,_T("constructor")). // here's our custom cunstructor var(&Vector3::x,_T("x")). var(&Vector3::y,_T("y")). var(&Vector3::z,_T("z")); // Bind the Actor class SQClassDef<Actor>(_T("Actor")). func(&Actor::setMaterialName,_T("setMaterialName")). func(&Actor::setScale,_T("setScale")). func(&Actor::setPosition,_T("setPosition")). func(&Actor::setMesh,_T("setMesh")); // Create an Actor object Actor *pActor = new Actor( "TestActor", mSceneMgr, Vector3( 0, 0, 0 ), Vector3( 1, 1, 1 ) ); // Call initActor function and pass object by reference SquirrelFunction<void>(_T("initActor"))(pActor); // Shutdown the VM when finish SquirrelVM::Shutdown(); // Delete Actor object delete pActor; // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // Create a light Light* l = mSceneMgr->createLight("MainLight"); l->setPosition(20,80,50); }
I've put everything in the createScene method. First of all we create the Virtual Machine. Then we compile and run the script "Test.nut". The Test.nut file is in a directory where the ResourceGroupManager can read it, or the same directory of the exe file. It depends on which method you use to read it. After that we bind the classes Actor and Vector3. Note how the constructor is bind.
Finally we create an Actor object and the initActor (define in Test.nut) function is called. Note that pActor is passed by reference.
(NOTE: You probably should have a constructor and destructor in the SquirrelOgre class.)
static void printFunc(HSQUIRRELVM v,const SQChar * s,...) { std::string tempStr = ""; static SQChar temp[2048]; va_list vl; va_start(vl,s); scvsprintf( temp,s,vl); va_end(vl); Ogre::LogManager::getSingletonPtr()->getLog("squirrel.log")->logMessage(temp); } }; //ends the class #endif //ends #ifndef
This function must be a member of the same class as create scene above (SquirrelOgre)
This function requires the stdarg.h header, which allows you to do the magic required to make a function behave like printf, that is taking many arguements relating to the prototype you also send ( something like "Days %d: Name: %s" with additional integer and string arguements).
Now all the output from the VM, including exceptions and the ::print() function, is written to squirrel.log through the Ogre log manager.
Finally let's see Test.nut
// ========================================================== // Test.nut // ========================================================== function initActor( pActor ) { pActor.setMesh("robot.mesh"); pActor.setScale( Vector3(3, 3, 3) ); pActor.setPosition( Vector3( 0, 0, 0 ) ); pActor.setMaterialName( "Examples/BumpyMetal" ); }
Ok that's all. I hope it could be useful for someone. ๐