Source Pawn 2!

wanted241

Real-Gamer.Ru
Сообщения
428
Реакции
161
Доброго времени суток всем!

Не знаю, знаете ли вы о том, что сейчас идет активная разработка Source Pawn 2, но все-таки расскажу.

Хорошие новости для всех! Я победил buildbot, чтобы принести вам Source Pawn 2 экспериментальной сборки. Что такое Source Pawn 2 ?

Пока это не так много. Он содержит прототип нового двигателя сценариев Source Pawn 2. Вы можете переместить файлы .sp формата в папку plugins и это будет работать от исходного кода.

2 новых файла были добавлены в сборку:

  • plugins/sample.sp - Пример плагина, работающего на Source Pawn 2.
  • scripting/spshell.exe - Командная строка Source Pawn 2.

Сейчас есть много отладочных сообщений, например, при загрузке "sample.sp", вы увидите что то на подобие:
PHP:
     sm plugins load sample.sp [ FunctionStatement (PrintToServer) [ FunctionStatement (OnPluginStart) [ FunctionStatement (OnPluginStart)   [ BlockStatement     [ ExpressionStatement       [ CallExpression         [ NameProxy (PrintToServer)         [ StringLiteral 0    object 0 5    callnative 0 1 14   pop 15   stop  Safepoints:    5: 0 0    stop  Safepoints: SourcePawn 2.0! [SM] Loaded plugin sample.sp successfully.




Right now, a lot of the core language semantics such as operators and statements are supported. However, #include does not yet work, nor do callbacks. That means this prototype is extremely limited. Note that .sp plugins do not automatically refresh yet either. I will be implementing more language features and posting a new thread after each major milestone.

The shell is also quite limited. It supports one public function called "main" which takes no arguments (and any number of non-publics). For example:
Spoiler
Code:
dvander@linux32:$ cat test.sp public main() { new sum; for (new i = 0; i < 200; i++) sum += i; return sum; } dvander@linux32:$ ./spshell test.sp ... 19900

P.S. Я не переводил ничего, просто скопировал. Если надо - позже переведу.

Добавлено через 47 секунд
Часть 2:

Hi All,

You may remember me announcing a project called "Knight", with the intent of bringing a new language to SourceMod. After a long time not making any progress, two weeks ago I decided to ask a new question: "What if we just rewrote SourcePawn from scratch?"

It turns out, that's pretty easy to do. I have a working prototype of "SourcePawn 2", a brand new language engine for SourceMod. In a few days I will post a link where you can try new SourceMod Experimental snapshot builds.

Why?

The original SourcePawn compiler is extremely old. It was written by ITB CompuPhase in the 1990s and was originally based off a 1984 journal submission. It is nearly impossible to maintain. The binary format (".smx") is also archaic and inflexible, inhibiting almost any modern language feature or performance improvement.

When Borja and I decided to use Pawn, we rewrote the runtime, which is the thing that executes .smx files. That helped a lot, but even that is too restrictive. It provides a very rigid API and is ultimately limited by the .smx protocol.

My hope with SourcePawn 2 is a complete do-over. The compiler and runtime are tightly integrated as one unit, and the design will easily allow adding all sorts of new, modern language features.

Tell me more!

SourcePawn 2 runs plugins directly from source. That means you can drop ".sp" files in your plugins folder and they just work. Offline syntax and type checking is also supported. There are no plans to remove .smx support, however, .smx files will not be able to take advantage of SourcePawn 2.

My goal is to support enough SourcePawn language features that 70% of plugins on the forums will work. From there I'll evaluate what features are remaining and whether they're worth adding. In this initial prototype, enough features are working to write very simple plugins, though #include does not work so you must declare natives manually.

Here are the known language features I have not implemented, but will implement:
  • Const with non-refs
  • Array literals
  • Float comparison
  • Non-branching comparison
  • Global variables
  • Dynamic arrays
  • #include <>
  • Array slicing
  • Float comparisons
  • Booleans
  • The any: tag
  • Optional semicolons
  • Chained relational operators
  • Ternary expressions
  • Passing functions as variables/parameters
  • SortCustom2D, SortStrings
  • Very limited, specific uses of #if and #define

Eventually, if/as the language reaches maturity, I will start adding new language features that people have been requesting:
  • Resizable arrays
  • Global dynamic arrays
  • Structs
  • Classes
  • Closures/nested functions
  • Discriminated unions
  • Dynamic types
  • First-class FFI

SourcePawn 2 includes garbage collection. I've implemented a very basic garbage collector that only runs on map changes. For most use cases I've managed to maintain SourcePawn's performance and memory guarantees surrounding arrays, which is great.

Aside from that, the entire architecture is much more amenable to high-powered performance optimizations than SourcePawn 1. Although the implementation right now is simple (GC is not realtime, and the execution mode is an interpreter), the entire architecture is geared toward making an advanced GC and an optimizing JIT very easy.

There are many language features I will not implement. They are either too difficult to support in a modern design, or they are inherently bad features that may impede progress. Next to each I've listed what the eventual replacement will be:
  • Enum structs (replacement: actual structs)
  • #pragma semicolon (replacement: none, semicolons cannot be required)
  • #define X Y (replacement: use "const" or "static const")
  • #define X() ... (replacement: none, use functions)
  • #pragma (none, #pragmas are unneeded and will be ignored)
  • funcenum (replacement undecided)
  • Anything in <functions.inc> (replacement: module system like Java/C#)
  • Variadic arguments (replacement: alternate syntax I can talk about later)
  • Using String: as a non-array tag (replacement: none)
  • Tag mismatches as warnings (replacement: none, these are bugs)
  • #include "" ("use" keyword)
  • Enums with non-uniformly typed values (replacement: none, these are bugs)
  • Naming enums "Float", "String", "bool", etc. (replacement: none, these are bugs)

I'm happy to talk about why individual features will not be supported. Hopefully, SourcePawn 2 will eventually be compelling enough and people using these features will port to newer replacements.

Where do I get it?

Right now I have a bare-bones prototype where you can declare natives, forwards, and publics in a .sp file, and drop it into your plugins folder. It works but it's largely untested.

Later this week I will create a page where you can download snapshots, and I'll post a new thread about it here. For now, I'd just like to field any concerns/questions or discussions people might want to have.
 
Последнее редактирование:

semjef

semjef.ru
Сообщения
993
Реакции
444
Ну придётся некоторые вещи изучать заново, надеюсь документация будет полная, лучше писать плагины как это задумано valve:) т.е. Чистый С++
 

wanted241

Real-Gamer.Ru
Сообщения
428
Реакции
161
Про Call back's с переводом:

Я реализовал базовую поддержку обратного вызова в SourcePawn 2. Это означает, что теперь вы можете передать функцию в другие функции, и хранить их в переменных. В отличие от оригинальной Pawn - теперь вы можете вызывать функции, которые хранятся в переменных.

Вот краткая демонстрация того, что я имею в виду:

PHP:
typedef void:FrameCallback(); 

void:IdleFrame() 
{ 
} 

void:WorkFrame() 
{ 
    PrintToServer(".... stuff... "); 
} 

new FrameCallback:g_FrameFunction = IdleFrame; 

public OnGameFrame() 
{ 
    g_FrameFunction(); 
} 

public OnClientPutInServer(client) 
{ 
    g_FrameFunction = WorkFrame; 
} 

public OnClientDisconnected(client) 
{ 
    if (GetClientCount() == 0) 
        g_FrameFunction = IdleFrame; 
}
В этом примере, OnGameFrame будет выполнять пустую функцию, если ни один из игроков не подключен. В противном случае, он будет выполнять функцию, которая делает вещи.
Интересно, что это предоставляет большую гибкость для мульти-файлов или библиотек в стиле плагинов, которые ранее сражались с functions.inc (Инклюды которых не будут портированы в SP2).
Это также путь, путь быстрее, чем functions.inc. Например, посмотрите на SortCustom1D против SortIntegers. SortCustom1D составляет 12,8 раза медленнее, чем SortIntegers, в то время как написание исключительно в SourcePawn 2, разница составляет всего около 1,7.
The next, small step to complete this round of work is to support passing callbacks into natives, and that will bring a large set of .inc files into compatibility.
Далее, маленький шаг для успешной работы раунда с поддержкой обратных вызовов в native's и, которые принесут большой набор .inc файлов на совместимость.

Добавлено через 19 минут
Теперь про массивы (Arrays):

Всем привет!

Я только что закончил реализацию круглых огромных улучшений массива в Source Pawn 2.

1. Новая система типа массива.

Типы массивов теперь в двух вариантах: с фиксированной длиной и динамичной. Фиксированный массив имеет постоянную длину, в то время, как динамичный может быть любого размера. Кроме того, массивы с фиксированной длиной выступают в качестве значений, а с динамической - как ссылка.

Пример 1:

PHP:
new g_PlayerList[];  BuildPlayerList() {     new players[MaxClients];     // ...     g_PlayerList = players; }
В этом примере, g_PlayerList является ссылкой на массив целых чисел. По умолчанию, это пустой массив. ( размер 0 ) Позже создается новый массив и g_PlayerList становится ссылкой на него.

Вы можете назначить динамический массив любое число раз. Пример 2:

PHP:
Test() {     new array[];      // Note: this is a fixed-length array because of the initializer!     new temp1[] = {1, 2, 3, 4};     array = temp1;      new temp2[] = {5, 6, 7, 8};      // Note that these assignment do not affect temp1!     array = temp2;     array[0] = 12; }
Для демонстрации разницы между динамическим и фиксированным массивами - пример 3:
PHP:
Test() {     new Float:a[3], Float:b[3];      b[0] = 5.0;     a = b;     a[0] = 4.0;      // This will print 5.0, because |b| has not been changed.     PrintToServer("%f", b[0]);      new Float:c[];      c = b;     c[0] = 3.0;      // Now this prints 3.0, because |c| is a reference pointing to |b|, so changing |c| changes |b|.     PrintToServer("%f", b[0]); }
Правило: Если массив не имеет размера, или размер не является постоянным, тогда массив динамический и выступает в качестве ссылки. В противном случае, если массив с фиксированной длиной и это старая копия - семантика сохраняется в случае необходимости. Обратите внимание, что есть вещи, которые не работают:

Пример 4:
PHP:
BadTests() {     new Float:a[3];     new Float:b[];      // This is a type mismatch: only fixed arrays can assign to fixed arrays.     a = b;      new x[][];     new y[][5];          // This coercion is no longer valid, because x[n] could subvert the type requirements of |y|.     x = y; }
Добавлено через 23 минуты
2. Функции теперь могут вернуть любые массивы.

Это приходит с новым синтаксом. Пример 5:

PHP:
String[][] GetPlayerNames() {     new String:names[MaxClients + 1][];      for (new i = 1; i <= MaxClients; i++) {         // Note that buffer must be inside the loop, so a new one is created each time.         new String:buffer[MAX_NAME_LENGTH];         GetClientName(i, buffer, sizeof(buffer));         names[i] = buffer;     }      return names; }
Вы заметили, что Source Mod native's не могут вернуть массивы ( пока ). Это будет позже.


Добавлено через 27 минут
3. Структуры могут содержать массивы.
Это только опираясь на верхнюю часть существующей структуры поддержки в SourcePawn 2. Пример 6:
PHP:
struct Player
{
    String:name[];
    String:steamid[];
    Float:origin[3];
};

Float[3] GetPlayerOrigin();

public main()
{
    new Player:bail;

    bail.name = "BAILOPAN";
    bail.steamid = "STEAM_0:1:16";
    bail.origin = GetPlayerOrigin();
}
Обратите внимание, что строковый литерал назначается в новую модель массива. Строковый литерал создает динамический массив, а не фиксированной длины массив.

Добавлено через 52 минуты
Это еще не все! Ближе к вечеру еще переводы скину. ( Изменю этот пост )
 
Последнее редактирование:

neatek

Участник
Сообщения
424
Реакции
225
Enum'ы заменят на структуры... -_-
главное чтобы серв после этого не тупил, если дойдет до сервов
 

wanted241

Real-Gamer.Ru
Сообщения
428
Реакции
161
SM 2.0:
http://www.sourcemod.net/smdrop/2.0/sourcemod-2.0.0-linux-r3689-20120917071128.tar.gz

Добавлено через 3 минуты
Кстати, в нем появилось еще:

Changed files


  • gamedata/core.games/blacklist.plugins.txt

Добавлено через 24 минуты
Жду плюсов)

Добавлено через 30 минут
еще 1 вещь узнал, будет возможным делать так:

PHP:
new String:derp[] = "derp";
derp += "cake";
 
Последнее редактирование:

GeParD

SourcePawn
Сообщения
8
Реакции
9
Лучше бы занялись бы реализацией классов в SourcePawn
Я до сих пор уважаю ES (python) только за классы.

Вот это будет офигенный прорыв вперед.
 

wanted241

Real-Gamer.Ru
Сообщения
428
Реакции
161
PHP:
from sourcemod import PrintToServer
import regex

PrintToServer("....", regex.match(...))

Новый вид..

Добавлено через 1 минуту
И еще:

(1) Two SP1 types are changing. It'll be a simple search and replace to get from SP1 to SP2:
Float becomes float
String becomes char.


Т.е. Float сменилась на float, а String на char.
 
Последнее редактирование:

neatek

Участник
Сообщения
424
Реакции
225
wanted241, данная шняга(sm2.0) уже работает на каких-то игрушках?
ставил? юзал?
 
Сверху Снизу