вторник, 29 октября 2013 г.

“getTrailingNumber” function in T2D

by yurembo



Hello all!

I used Torque 3D for a long time. I liked to use “getTrailingNumber” function. This function is very useful to get a tail number of an object. For example, you have many objects, all of these have a name ”Gun” and to differ these you add a number to the end of a name, like “Gun22”. Then you need to get this number, right, you should call “getTrailingNumber” function and pass a target word with a number as a parameter to this function. It returns a tailing number. But T2D miss this function. Ok, we can add “getTrailingNumber” to T2D. It is very simple.
So, open up your project in VS, open \engine\source\string\stringBuffer.h file and add a declaration of a function in the StringBuffer class:

static const UTF8* GetTrailingNumber(const char* str, S32& number);

You should notice that this is a static function. Next open engine\source\string\stringBuffer.cc file to write a definition of this function:

const UTF8* StringBuffer::GetTrailingNumber(const char* str, S32& number)
{
   // Check for trivial strings
   if (!str || !str[0])
      return StringTable->EmptyString;

   // Find the number at the end of the string
   StringBuffer base = str;
   const char* p = base.getPtr8() + base.length() - 1;

   // Ignore trailing whitespace
   while ((p != base.getPtr8()) && dIsspace(*p))
      p--;

   // Need at least one digit!
   if (!isdigit(*p))
      return base.getPtr8();

   // Back up to the first non-digit character
   while ((p != base.getPtr8()) && isdigit(*p))
      p--;

   // Convert number => allow negative numbers, treat '_' as '-' for Maya
   if ((*p == '-') || (*p == '_'))
      number = -dAtoi(p + 1);
   else
      number = ((p == base.getPtr8()) ? dAtoi(p) : dAtoi(++p));

   // Remove space between the name and the number
   while ((p > base.getPtr8()) && dIsspace(*(p-1)))
      p--;

   return base.substring(0, p - base.getPtr8()).getPtr8();
}

I took up this cod from T3D with little modifications. Nice!
Next thing we should to do is to write a console function. This way we will able to call “getTrailingNumber” from Torque Script. Right way, open up \engine\source\console\consoleFunctions.cc and to the end of this file add this cod:

ConsoleFunction(getTrailingNumber, S32, 2, 2, "")
{
    S32 suffix = -1;
    StringBuffer::GetTrailingNumber(argv[1], suffix);
    return suffix;
}

Don’t forget: you should include StringBuffer.h header to current file. Now, when we call getTrailingNumber from a T2D script cod we should get a result like from T3D.
Yep, this is very simple to play!
So have a rest!

Комментариев нет:

Отправить комментарий