En ^ Ru

AVS tutorial by FSK
 (basic 2D SSC tutorial.avs)
 
http://avs.chat.ru/avsbyfsk.htm
http://avs.chat.ru/avsbyfsk.avs
 
Это руководство сделано для людей, кто пока не пробовал создать SuperScope (SSC). Все примеры в этом руководстве являются базовыми и все основаны на высшей математике, так что если вы имеете математическое образование или учитесь сейчас, то сможете разобраться во всём этом (возможно лучше меня). Мой английский не достаточно хорош, так же как и мой математический, так что, пожалуйста, прошу меня извинить, если я использовал неправильную терминологию (или даже лучше написать мне, и сообщить об этом). Каждый Список эффекта содержит один пример (в первую очередь SSC) и комментарий. Чтобы пройти консультацию, сначала  включите Список эффекта, и прочитайте комментарии, затем выключите его и включите следующий за ним. Прочитайте информацию в SSC и помощи выражения, чтобы видеть как использовать функции. Вы можете послать мне свой пример, чтобы добавить его, так что вместе мы можем сделать это руководством лучше.
 

1) The simple
 
Самым простым SSC является прямая линия (горизонтальная или вертикальная). Чтобы сделать прямую линию одной из координат (x или y), нужно одну координату оставить постоянной, пока другая измененяет (увеличивает или уменьшает) свою величину.
 
 Init:
n=300;
 Per Point:
y=0;
x=i;
 
("i" содержит величины от 0 до 1, переменная "n" определяет сколько величин (точек) вам требуется. Первой точкой является 0, а последней 1). Чтобы сделать линиию по всей длине экрана, нужно переместить её на начало экрана и протянуть ещё, увеличив размер в два раза. Замените предшествующий код этим:
 
 Per Point:
y=0;
x=i*2-1;
 
А чтобы сделать настоящий SSC, замените y=0 на y=v. Такая суперобласть уже не является "простой". Вместо "v" можно использовать "getosc(i,0,0)" для waveform или "getspec(i,0,0)" для spectrum. Вот два примера, показывающих как сформировать другую волновую линию:
 
 Per Point:
y=getosc(i,.4,0);                   // длина волны больше чем .4
y=getosc(i,0,0)-getosc(i,.01,0);    // длина волны между 0 и .01
 

2) Circle
 
Следующий SSC пример - круг. Не буду объяснять, почему это работает, поскольку не могу этого сделать. Моей математической подготовки просто не достаточно для этого. Эффект работает, поскольку функции sin и cos производят такой результат.
 
 Init:
PI=3.14159=acos(-1);
 PerPoint:
r=i*PI*2;
d=.5;
x=sin(r)*d;
y=cos(r)*d;
 
Чтобы сделать круг реагирующим на музыку, нужно добавить "d=.5+v/3". "r" - угол (в радианах) от 0 до 2PI (умноженное на "i", чтобы получать все величины полного круга). "d" - расстояние из центра - радиус. x и y часть является преобразованием из полярных координат (r,d) в прямоугольные декартовые координаты (x,y). Это очень полезный алгоритм. Таким образом можно сделать квадраты, звезды, треугольники, спирали и другие геометрические формы с ними. Для квадрата просто используется 5 точек (n=5), для треугольника 4 точки, для спирали расстояние изменяется с каждой следующей точкой (d=i), и можно умножать "r", чтобы изменять спиральную плотность.
 

3) Star SSC
 
Эффект снова использует те же уравнения, только теперь добавлена функция cos к расстоянию d (график функции сделан ниже этой звезды). Данный пример сделан без динамики.
 
 Init:
n=11; PI=acos(-1);
 Per Point:
r=i*PI*2;
d=.5+cos(i*PI*(n-1))*.25;
x=sin(r)*d;
y=cos(r)*d;
 
"x=sin(r)*d*(cos(i*PI*(n-1))+1)*.5" или "d=(cos(i*PI*(n-1))+1)*.25" делают сплошной заполненный круг, если "n" будет достаточно большим, и при использовании в Misc / Set render mode установки ширины линии для наилучшего результата. (n=444; linesize=4;)
 
d=.5+cos(i*PI*(n-1))*.25;
x=sin(r)*d*(cos(i*PI*(n-1))+1)*.5; x=x*h/w;
 
d=(cos(i*PI*(n-1))+1)*.25;
x=sin(r)*d; x=x*h/w;
 
Здесь важно взять cos с правильной частотой, чтобы точки составили половину от части длины волны косинуса.
(n-1) - количество работы (thoes the job). Другой путь сделать подобное - использовать функцию "if" (в сочетании с cos), чтобы разделить точки на две группы и дать им различную дистанцию:
 
d=if(above(cos(r*(n-1)/2),0),distance1,distance2);
x=sin(r)*d; x=x*h/w;
 
Последний вариант ещё лучше, поскольку эти две дистанции ни каким образом не связаны друг с другом, что даёт больше свободы при изменении формы звезды. И таким образом легче организовать вращение. Так вы можете сделать заполненный круг, установив одну дистанцию на 0 и вторую в радиус. Есть и другие пути сделать круг, но я сейчас знаю только эти два. Один из ещё возможных способов - выделить четные из разницы. Усиленно размышляю о том как это сделать. Добро пожаловать, если предложите дополнительно и такой способ.
 

4) Movement
 
Чтобы перемещать SSC по периметру, можно просто добавлять или вычитать из всех x или y координат. Самый благоприятный путь добиться этого, дописать в конце всех записей выражение (нет необходимости писать именно moveX, вы можете использовать любое имя, которое захотите):
 
x=x+moveX;
y=y+moveY;
 
Выличины moveX(Y) должны находиться между -1 и 1, в противном случае SSC выйдет за границы экрана. Ось y направлена вниз, так что если вы хотите переместить SSC вверх, moveY должно быть отрицательным.
 
 Init:
n=5; PI=acos(-1); moveX=.3; moveY=.5;
 PerPoint:
r=i*PI*2; d=.5;
x=sin(r)*d; y=cos(r)*d; 
x=x+moveX; y=y+moveY;
 

5) Rotation 1
 
Данный способ вращения работает только с SSC, сделанным по этому алгоритму. Чтобы вращать область, нужно добавлять или вычитаться из "r" (Причём, угол нужно преобразовывать в радианы, если хотите ввести градусы, соответственно, PI радиан равно 180 градусам. Сдвиг на 36 градусов, множитель "*PI/180" преобразует угол в радианы).
 
 Init:
n=5;PI=acos(-1);moveX=.3;moveY=.5;rot=36;rot1=rot*PI/180;
 PerPoint:
r=i*P*2+rot1; d=.5;
x=sin(r)*d; y=cos(r)*d;
x=x+moveX; y=y+moveY;
 

6) Rotation 2
 
Этот способ вращения применим к любым SSC.
 
 Per Point:
x=i-.5; y=v/2;                           // область
d=sqrt(x*x+y*y);                         // преобразование к полярным координатам
r1=atan(y/x);
r=if(above(x,0),r1,r1+pi);
r=r+rot;                                 // добавление параметра вращения
x=sin(r)*d; y=cos(r)*d;                  // преобразование к прямоугольным координатам
 
Отредактируйте "d" между преобразованиями, чтобы масштабировать SSC:
 
d=d*1.5;
 

7) Rectangular\Polar coordinates
 
Есть два пути указать определённую позицию в системе координат:
 - с использованием x и y (rectangular-Cartesian coordinates)
 - с использованием r и d (polar coordinates)
 
Преобразование прямоугольных к полярным (известное уравнение Пифагора):
 
 d*d=x*x+y*y
 tan(r)=y/x
 r=atan(y/x)
 
d=sqrt(sqr(x)+sqr(y);
r1=atan(y/x);
r=if(above(x,0),r1,r1+PI);
 
Это та часть, которую вы используете. Функция "if" обеспечивает вычисление противоположных углов для отрицательных координат x (Даже не знаю, почему уравнение не работает без этого?).
 
Преобразование полярных к прямоугольным:
 
y=sin(r)*d;
x=cos(r)*d;
 

8) Basic dinamix 1 (position)
 
Любой параметр SSC может быть сделан динамическим. Наиболее общие характеристики, которые могут быть динамическими: размер, позиция, вращение, форма. Можно использовать On Beat, Per Frame, Per point для программирования динамики вашего SSC. Материал, записанный в окне Init считывается только в первом фрейме. Материал в окне On Beat прочитывается всякий раз, когда AVS обнаруживает ритм. Per Frame материал читается каждый фрейм, а материал Per Point прочитывается для каждой точки отдельно (n раз для каждой точки, один раз за каждый фрейм). Делайте запись именно здесь, если хотите переместить специфические части вашего SSC.
 
 Init:
n=5; PI=acos(-1);
moveX=0; moveY=0; rot=0;        // установите здесь начальные значения
 Per Frame:
t=t+0.01; moveY=sin(t);         // читайте комментарий ниже
 Per Point:
r=i*PI*2+rot*PI/180; d=.5;
x=sin(r)*d; y=cos(r)*d;
x=x+moveX; y=y+moveY;
 
Величина t увеличивается на 0.01 с каждым фреймом. Самостоятельный параметр t необходим (usles), поскольку если мы непосредственно добавляем его к координатам X вместо moveX область пойдет за экран и не возвратится обратно. Поэтому, помещаем t в функции sin или cos (дипазон величин этих двух функций - от -1 до 1). Если хотите уменьшить перемещение, разделите sin(t), а если хотите, чтобы перемещение было более быстрым, то увеличьте величину, добавляемую к t. Знаю, о чём вы думаете прямо сейчас, - что такое - это скучно, хочу, чтобы мой SSC реагировал на музыку. Так происходит, поскольку величина, добавляемая к t, всегда одна и та же. Используйте окно On Beat, чтобы изменить это. Один из вариантов - воспользоваться функцией "rand":
 
 On Beat:
speed=rand(5)/100;             // дипазон величин: от 0 до 0.05
 Per frame:
t=t+speed; moveY=sin(t);
 
Это изменит величину t в каждом ритме. Вы можете сделать то же самое для координаты X, но вам придётся использовать другие параметры t (t1) и speed. Если хотите получить циклическое перемещение, то возьмите те же самые t и speed, и используйте sin для moveX, а cos для moveY (или же cos для moveX, sin для moveY).
 
Circular movement:
 Per Frame:
t=t+0.01; moveY=sin(t); moveX=cos(t)
 

9) Basic dinamix 2 (rotation)
 
 Init:
n=5; PI=acos(-1);
moveX=0; moveY=0; rot=0;
 On Beat:
speed=getosc(0,0,0)/5;
 Per Frame:
rot=rot+speed;
 Per Point:
r=i*PI*2+rot; d=.5;
x=sin(r)*d; y=cos(r)*d;
x=x+moveX; y=y+moveY;
 
Здесь я использовал функцию getosc (дипазон величин: от 0 до 1), чтобы изменять скорость. Это вполне оправданно, поскольку скорость выбрана не произвольно, а определяется музыкой, плюс вы получаете отрицательные скорости (вращение в обоих направлениях).
 

10) Color codeing
 
Цветовой код используется для получения ритмических цветовых изменений, и для создания SSC с многочисленными цветами, делающими части SSC невидимыми или проявляющимися. Каждый канал кодируется отдельно Красным, Зеленым и Синим.
 
 Per Point:
r=i*PI*45; d=i*.5;
x=sin(r)*d; y=cos(r)*d;
red=1-i;                      // red=(1-i)/255*value;
green=1-i;
blue=1-i;
 
Чтобы получать желаемый цвет, легче всего заранее зафиксировать любимые цвета, и записать их вводные величины для каждого цвета. Включите эффект "Render/Clear screen", который распложен ниже этого "Misc/Comment". Чтобы сделать черные части невидимые (на всех фонах), нужно в эффекте "Misc/Set render mode" устанавить "set the render mode" на "maximum blend". Также измените ширину линии на 10.
 
Example (Per Point):
 
red=sin(r*4);
green=sin(r*4);
blue=sin(r*4);
 
red=sin(r*4+t);
green=sin(r*4+t);
blue=sin(r*4+t);
 
red=sin(r*3+t);
green=sin(r*3+t1);
blue=b;
 
Две функции getosc используются для раздельного обнаружения левого-правого каналов.
 
speed=getosc(0,0,1); speed1=getosc(0,0,2);
 

11) Another example of colour codeing
 
n=800; PI=acos(-1); re=255; gr=100; bl=100; re1=1/255*re; gr1=1/255*gr; bl1=1/255*bl;
 
r=i*PI*2; d=if(above(cos(r*(n-1)/2),0),0,.6+v*.7);
x=sin(r)*d; y=cos(r)*d;
red=re1+v; green=gr1+v; blue=bl1+v;
 
В этом SSC величины яркости цвета и расстояние точек на крае обоих кругов изменены на "v". Иллюзия 3D следует из двух монокулярных (monocular) ключей восприятия 3D:
 
 ярче   - темнее
 +        +
 больше - меньше
 =        =
 ближе  - дальше
 
FSK

Перевод: А.Панов.
http://avs.chat.ru

counter
Panow©



En ^ Ru

AVS tutorial by FSK
 (basic 2D SSC tutorial.avs)
 
http://www.visbot.net/category/documents
http://www.visbot.net/doc/Basic_2D_SSC_tutorial.zip
 
I made this tutorial for people who haven't made a superscope (SSC) yet.The examples in this tutorial are all very basic and all based on highschool math, so if you finished that or are currently in one you should undestand this (better than me) :). My english sucks as much as my math so please excuse me (or even better- Email me and tell me about it) if I used the wrong terms.
Each Effect list contains one example (the first SSC) and a comment.To go through the tutorial enable the first Effect list and read the comment inside then dissable it and enable the next one...
Read the info in the SSC and the expression help to see how to use the functiones.
You can send me an example to add, so we can make this a better tutorial.
 
1) THE SIMPLE
 
The simplest SSC is a straight (horizontal or vertical) line. To make a straight line one of the coordinats (x or y) needs to stay the same while the changes (increases-decreases) its value.
 
Example 1:
Init:  n=300
Per Point:
y=0;
x=i           
 
(i contains values from 0 to 1, the "n" variable determines how many values (points) you take.The first one is 0 and the last is 1)
to make a line along the whole length of the screen, you need to move the line back to the start of the screen and stretch it to be twice the size it is now.
Replace the previous code with this
 
Per Point:
y=0;
x=i*2-1
now to make this a real SSC repleace the y=0 with y=v. Now isn't that SIMPLE.
 
Instead of "v"  you can use "getosc(i,0,0)" for waveform or "getspec(i,0,0)" for spectrum.
Here are two examples showing how to isolate difrent wave lenghts:
 
Per Point:
y=getosc(i,.4,0)                               -wave lenghts longer than .4
y=getosc(i,0,0)-getosc(i,.01,0)         -wave lenghts between 0 and .01
 
2)
 
The next SSC examle is a circle. I am not going to explain why this workes because i can't.My math just sucks too much for that.
It workes because the sin and cos functiones where
made the way they are.
 
Example1:
Init:                      PI=3.14159=acos(-1)
PerPoint:
r=i*PI*2;
d=.5;                              (to make it music responsive "d=.5+v/3")
x=sin(r)*d;
y=cos(r)*d;
 
"r"  is the angle (in radians) from 0 to 2PI (multiplyed with "i" to get all the values-whole circle)
"d" is the distance from centre - radius
the x and y part is the conversion from polar coordinates (r,d) to rectangular-Cartesian coordinates (x,y). 
 
This is a very usefull alogorithm. You can make squres, stars, triangles, spirals and other geometric shapes with it.
For a square simply use 5 points (n=5), for a triangel you use 4 points, for a spiral the distance is groing with each next point (d=i), multyply the "r" to alter the spiral's density.
 
3) star SSC
 
this one uses the same function again, only now we added a cos function to the distance (I made a graph of this function below the star)
 
this example is without the dinamix
Init:  n=11;PI=acos(-1)
Per Point:
r=i*PI*2;                              "x=sin(r)*d*(cos(i*PI*(n-1))+1)*.5" or
d=.5+cos(i*PI*(n-1))*.25;       "d=(cos(i*PI*(n-1))+1)*.25" 
x=sin(r)*d;                           makes a filled circle if "n" is high enough
y=cos(r)*d                           use Misc/Set render mode to set the                                                     line width for a beter reasout
 
The important thing here is to take a cos with the right frequecy, so that the points are 1/2 the cos wavelenght apart.
The (n-1) thoes the job.
 
another way of doing this is to use the "if" function (in combination with the cos) to separate the points in two groups and giving them difrent distances:
 
d=if(above(cos(r*(n-1)/2),0),distance1,distance2)
 
This is good because the two distances are not in any way linked to eachother, givig you more freedom with the shape of the star. And it is easier to rotate this way.You can make a filled circle this way, just set one distance to 0 and the other is the radius .
 
There are surly other ways of doing this but I only know how to make this two for now. One other way is to seperate evens from odds. I wonder how that is done. You are welcome to add it.
 
4) Movement:
 
To move the SSC around you simply add or subtract from ALL the x or y coordinates. The safest way of doing this is to write this on the end:
 
x=x+moveX;                      (no need for writeing moveX you can use    y=y+moveY                         any name you want)
 
moveX(Y)  must be between -1 and 1, otherwise the SSC will go offscreen. The y axis is turned around  :? , so if you want to move the SSC up the moveY must be negative.
 
example:
Init:    n=5;PI=acos(-1);moveX=.3;moveY=.5
 
PerPoint:
r=i*PI*2;
d=.5;
x=sin(r)*d;
y=cos(r)*d; 
x=x+moveX;
y=y+moveY;
 
5) Rotation 1:
 
THIS ONLY WORKS WITH SSC MADE WITH THIS ALGORITHM
 
To rotate you add or subtract from the "r". (You need to convert to radians if you want to enter degrees- PI rad=180 deg)
 
example:
Init:
n=5;PI=acos(-1);moveX=.3;moveY=.5;rot=36;rot1=rot*PI/180;                                                           (*PI/180  Conversion to radians)
rotates for 36 degrees                                           
PerPoint:
r=i*P*2+rot1;
d=.5;
x=sin(r)*d;
y=cos(r)*d;
x=x+moveX;
y=y+moveY
 
6) Rotation 2:
 
THIS APLLIES TO ALL SSC
 
example:
Per Point:
x=i-.5;                                              the scope
y=v/2;                                            
d=sqrt(x*x+y*y);                               conversion to polar
r1=atan(y/x);
r=if(above(x,0),r1,r1+pi);                 
r=r+rot;                                            adding the rotation amount
x=sin(r)*d;                                       conversion to rectangular
y=cos(r)*d;
 
edit the "d" between the conversions to scale the SSC
example:           d=d*1.5;
 
7) Rectangular - Polar coordinates
 
there are two ways of specifing point position in a sistem of coordinates:
-with x and y (rectangular-Cartesian coordinates)
-with r and d (polar coordinates)
 
CONVERSION:
rectangular to polar:
d*d=x*x+y*y                    does the name Pythagoras sound familiar :)
tan(r)=y/x          r=atan(y/x)
 
d=sqrt(sqr(x)+sqr(y);                   This is the part you use. The "if"  r1=atan(y/x);                              function is there to make the               r=if(above(x,0),r1,r1+PI);           
 oposite angles for negative x coordinates. (I dont know why it  doesnt work without it :?) 
 
polar to rectangular
y=sin(r)*d;
x=cos(r)*d;
 
8) BASIC DINAMIX                                  
 
Any SSC paramerter can be made dinamic. The most common things you to be made dinamic are: size, position, rotation, shape. You can use the On Beat, Per Frame or Per point windows to program the dinamix of your SSC. The stuff written in the Init window are only read on the first frame. The stuff in the On Beat win. is read whenever AVS detects a beat, Per Frame stuff is read every frame and the Per Point stuff is read for each point seperatly (n times - every point once per every frame).Write here if you want to move specific parts of your SSC.
 
example 1 (position):
Init:
n=5;PI=acos(-1);moveX=0;moveY=0;rot=0
                 (set the starting point here)
Per Frame:
t=t+0.01;moveY=sin(t);            read comment below
Per Point:
r=i*PI*2+rot*PI/180;
d=.5;
x=sin(r)*d;
y=cos(r)*d;
x=x+moveX;
y=y+moveY
 
The value of t incereases for 0.01 with every frame. The t by itself is usles because if we add that to the X coordinates instead of moveX the scope will go offscreen and not come back. So you put the t in a sin or cos function (the range of values of this two functions is from-1 to 1). If you want it to move less divide the sin(t), if you want it to move faster increase the value being added to t.
 
I know what you are thinking right now, what is this boring shit I want my SSC to react to music. That's because the value being added to t is always the same. You use the On Beat window to change this.
One way of doing this is with the "rand" finction:
 
On Beat:
speed=rand(5)/100      (the range of values: 0 to 0.05)
Per frame:
t=t+speed;moveY=sin(t)
 
This will change the value on every beat.
 
You can do the same thing for the X coordinates, but you need to make another t (t1) and another speed. If you want circular movement you use the same t and speed and use sin for moveX and cos for moveY (or cos for moveX ,sin for moveY).
 
circular movement:
Per Frame:         t=t+0.01;moveY=sin(t);moveX=cos(t)
 
9) BASIC DINAMIX
 
example 2 (rotation):
Init:                   n=5;PI=acos(-1);moveX=0;moveY=0;rot=0
On Beat:           speed=getosc(0,0,0)/5
Per Frame:        rot=rot+speed
Per Point:
r=i*PI*2+rot;
d=.5;
x=sin(r)*d;
y=cos(r)*d;
x=x+moveX;
y=y+moveY
 
I used the getosc function (range of values: 0 to 1) to change the speed here. This is good because the speed is not randomly chosen, instead it's determined by music + you get negative speeds (rotation in both directions).
 
10) Color codeing
 
Colour codeing is used to get on beat colour changes, SSC with multiple colours making parts of the SSC invisible or making....
Each chanel is coded separatly Red, Green, Blue.
 
Example:
Per Point:
red=1-i;                                 (red=(1-i)/255*value)
green=1-i;                   to get the desired colour easier write it like this
blue=1-i                       and enter values for each colour
 
Enable the "Render/Clear screen" below this "Misc/Comment".
To make the black parts invisible (on all backgrounds) you need to set the render mode to maximum blend in the "Misc/Set render mode". Also change the line width to 10.
 
Example 2:
Per Point:
red=sin(r*4);
green=sin(r*4);
blue=sin(r*4)
 
Example 3:
Per Point:
red=sin(r*4+t);
green=sin(r*4+t);
blue=sin(r*4+t)
 
Example 5:
red=sin(r*3+t);
green=sin(r*3+t1);
blue=b
 
The two getosc functiones are for seperate left-right channel detection.
 
11) another example of colour codeing
 
In this SSC the values of the colour brightnes and the distance of the points on the edge of the circle are both changed with "v".
The 3D comes from two monocular 3D perception keys:
 
brighter - darker
bigger - smaller
------------------------
closer - further
 
I hope anyone finds this usefull
 
FSK
Email: fskolog@volja.net
 
http://avs.chat.ru