Извините, ничего не найдено.

Не расстраивайся! Лучше выпей чайку!
Регистрация
Справка
Календарь

Вернуться   forum.boolean.name > Программирование игр для компьютеров > Unity > Общие вопросы

Общие вопросы вопросы не попадающие ни в один из доступных разделов

Ответ
 
Опции темы
Старый 24.02.2013, 22:07   #1
dsd
Мастер
 
Аватар для dsd
 
Регистрация: 13.06.2011
Сообщений: 1,103
Написано 481 полезных сообщений
(для 1,836 пользователей)
Simplex noise 2d 3d 4d

по мотивам: http://webstaff.itn.liu.se/~stegu/si...mplexnoise.pdf




using System;
using UnityEngine;
using System.Collections.Generic;

public class 
SimplexNoise MonoBehaviour {
    
    public 
float zScale 70.0f;
    public 
float overallScale 0.1f;
    public 
int seed 158;
    
    private static 
Vector3[] grad3 = {
        new 
Vector3(1,1,0),new Vector3(-1,1,0),new Vector3(1,-1,0),new Vector3(-1,-1,0),
         new 
Vector3(1,0,1),new Vector3(-1,0,1),new Vector3(1,0,-1),new Vector3(-1,0,-1),
         new 
Vector3(0,1,1),new Vector3(0,-1,1),new Vector3(0,1,-1),new Vector3(0,-1,-1)};

    private static 
Vector4[] grad4= {
        new 
Vector4(0,1,1,1),    new Vector4(0,1,1,-1),     new Vector4(0,1,-1,1),     new Vector4(0,1,-1,-1),
         new 
Vector4(0,-1,1,1),    new Vector4(0,-1,1,-1), new Vector4(0,-1,-1,1), new Vector4(0,-1,-1,-1),
         new 
Vector4(1,0,1,1),     new Vector4(1,0,1,-1),     new Vector4(1,0,-1,1),     new Vector4(1,0,-1,-1),
        new 
Vector4(-1,0,1,1),     new Vector4(-1,0,1,-1), new Vector4(-1,0,-1,1), new Vector4(-1,0,-1,-1),
        new 
Vector4(1,1,0,1),     new Vector4(1,1,0,-1),     new Vector4(1,-1,0,1),     new Vector4(1,-1,0,-1),
        new 
Vector4(-1,1,0,1),     new Vector4(-1,1,0,-1), new Vector4(-1,-1,0,1), new Vector4(-1,-1,0,-1),
        new 
Vector4(1,1,1,0),     new Vector4(1,1,-1,0),     new Vector4(1,-1,1,0),     new Vector4(1,-1,-1,0),
        new 
Vector4(-1,1,1,0),     new Vector4(-1,1,-1,0), new Vector4(-1,-1,1,0), new Vector4(-1,-1,-1,0)};
    
    
// A lookup table to traverse the simplex around a given point in 4D.
     // Details can be found where this table is used, in the 4D noise method.
    
private static Vector4[] simplex = {
        new 
Vector4(0,1,2,3),new Vector4(0,1,3,2),new Vector4(0,0,0,0),new Vector4(0,2,3,1),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(1,2,3,0),
        new 
Vector4(0,2,1,3),new Vector4(0,0,0,0),new Vector4(0,3,1,2),new Vector4(0,3,2,1),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(1,3,2,0),
        new 
Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),
        new 
Vector4(1,2,0,3),new Vector4(0,0,0,0),new Vector4(1,3,0,2),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(2,3,0,1),new Vector4(2,3,1,0),
        new 
Vector4(1,0,2,3),new Vector4(1,0,3,2),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(2,0,3,1),new Vector4(0,0,0,0),new Vector4(2,1,3,0),
        new 
Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),
        new 
Vector4(2,0,1,3),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(3,0,1,2),new Vector4(3,0,2,1),new Vector4(0,0,0,0),new Vector4(3,1,2,0),
        new 
Vector4(2,1,0,3),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(0,0,0,0),new Vector4(3,1,0,2),new Vector4(0,0,0,0),new Vector4(3,2,0,1),new Vector4(3,2,1,0)};
    
    
    private static 
int[] = new int[256];
    
// To remove the need for index wrapping, float the permutation table length
    
private static int[] perm = new int[512];

        
    
// Use this for initialization
    
void Start () {    
        
System.Random rand = new System.Random(seed);
        for(
int i=0i<256i++) p[i] = rand.Next(0,255); 
        for(
int i=0i<512i++) perm[i]=p[255];
    }
    
// Update is called once per frame
    
void Update () {
    
    }
    
// This method is a *lot* faster than using (int)Math.floor(x)
     
private static int fastfloor(float x) {
         return 
x>? (int): (int)x-1;
     }
    
    private static 
float dot(Vector3 gradient,Vector2 coords){
        return    
gradient.x*coords.gradient.y*coords.y;
    }
    
    private static 
float dot(Vector3 gradient,Vector3 coords){
        return    
gradient.x*coords.gradient.y*coords.gradient.z*coords.z;
    }
    
    private static 
float dot(Vector4 gradient,Vector4 coords){
        return    
gradient.x*coords.gradient.y*coords.gradient.z*coords.gradient.w*coords.w;
    }    
    
// 2D simplex noise
    
public float noise(float xinfloat yin) {
        
xin xin overallScale;
        
yin yin overallScale;
        
float n0n1n2;
        
float F2 0.5f*((float)Math.Sqrt(3.0f)-1.0f);
        
float s = (xin+yin)*F2
        
int i fastfloor(xin+s);
        
int j fastfloor(yin+s);
        
float G2 = (3.0f-(float)Math.Sqrt(3.0f))/6.0f;
        
float t = (i+j)*G2;
        
float X0 i-t
        
float Y0 j-t;
        
float x0 xin-X0
        
float y0 yin-Y0;
        
int i1j1
        if(
x0>y0) {i1=1j1=0;} 
        else {
i1=0j1=1;} 
        
float x1 x0 i1 G2;
        
float y1 y0 j1 G2;
        
float x2 x0 1.0f 2.0f G2;
        
float y2 y0 1.0f 2.0f G2;
        
int ii 255;
        
int jj 255;
        
int gi0 perm[ii+perm[jj]] % 12;
        
int gi1 perm[ii+i1+perm[jj+j1]] % 12;
        
int gi2 perm[ii+1+perm[jj+1]] % 12;
        
float t0 0.5f x0*x0-y0*y0;
        if(
t0<0n0 0.0f;
        else {
            
t0 *= t0;
            
n0 t0 t0 dot(grad3[gi0],new Vector2(x0y0));
        }
        
float t1 0.5f x1*x1-y1*y1;
        if(
t1<0n1 0.0f;
        else {
            
t1 *= t1;
            
n1 t1 t1 dot(grad3[gi1],new Vector2(x1y1));
        } 
float t2 0.5f x2*x2-y2*y2;
        if(
t2<0n2 0.0f;
        else {
            
t2 *= t2;
            
n2 t2 t2 dot(grad3[gi2],new Vector2(x2y2));
        }
        return 
zScale * (n0 n1 n2);
    }    

// 3D simplex noise
    
public float noise(float xinfloat yinfloat zin) {
        
xin xin overallScale;
        
yin yin overallScale;
        
zin zin overallScale;
        
float n0n1n2n3;
        
float F3 1.0f/3.0f;
        
float s = (xin+yin+zin)*F3;
        
int i fastfloor(xin+s);
        
int j fastfloor(yin+s);
        
int k fastfloor(zin+s);
        
float G3 1.0f/6.0f;
        
float t = (i+j+k)*G3
        
float X0 i-t;
        
float Y0 j-t;
        
float Z0 k-t;
        
float x0 xin-X0;
        
float y0 yin-Y0;
        
float z0 zin-Z0;
        
int i1j1k1;
        
int i2j2k2;
        if(
x0>=y0) {
        if(
y0>=z0)
        { 
i1=1j1=0k1=0i2=1j2=1k2=0; }
        else if(
x0>=z0) { i1=1j1=0k1=0i2=1j2=0k2=1; } 
        else { 
i1=0j1=0k1=1i2=1j2=0k2=1; }
        }
        else {
        if(
y0<z0) { i1=0j1=0k1=1i2=0j2=1k2=1; }
        else if(
x0<z0) { i1=0j1=1k1=0i2=0j2=1k2=1; }
        else { 
i1=0j1=1k1=0i2=1j2=1k2=0; }
        }
        
float x1 x0 i1 G3;
        
float y1 y0 j1 G3;
        
float z1 z0 k1 G3;
        
float x2 x0 i2 2.0f*G3;
        
float y2 y0 j2 2.0f*G3;
        
float z2 z0 k2 2.0f*G3;
        
float x3 x0 1.0f 3.0f*G3;
        
float y3 y0 1.0f 3.0f*G3;
        
float z3 z0 1.0f 3.0f*G3;
        
        
int ii 255;
        
int jj 255;
        
int kk 255;
        
        
int gi0 perm[ii+perm[jj+perm[kk]]] % 12;
        
int gi1 perm[ii+i1+perm[jj+j1+perm[kk+k1]]] % 12;
        
int gi2 perm[ii+i2+perm[jj+j2+perm[kk+k2]]] % 12;
        
int gi3 perm[ii+1+perm[jj+1+perm[kk+1]]] % 12;

        
float t0 0.5f x0*x0 y0*y0 z0*z0;
        if(
t0<0n0 0.0f;
        else {
        
t0 *= t0;
        
n0 t0 t0 dot(grad3[gi0], new Vector3(x0y0z0));
        }
        
float t1 0.5f x1*x1 y1*y1 z1*z1;
        if(
t1<0n1 0.0f;
        else {
        
t1 *= t1;
        
n1 t1 t1 dot(grad3[gi1], new Vector3(x1y1z1));
        }
        
float t2 0.5f x2*x2 y2*y2 z2*z2;
        if(
t2<0n2 0.0f;
        else {
        
t2 *= t2;
        
n2 t2 t2 dot(grad3[gi2], new Vector3(x2y2z2));
        }
        
float t3 0.5f x3*x3 y3*y3 z3*z3;
        if(
t3<0n3 0.0f;
        else {
        
t3 *= t3;
        
n3 t3 t3 dot(grad3[gi3], new Vector3(x3y3z3));
        }
    return 
zScale * (n0 n1 n2 n3);
    } 

// 4D simplex noise
    
public float noise(float xfloat yfloat zfloat w) {
        
overallScale;
        
overallScale;
        
overallScale;
        
overallScale;
        
float F4 = ((float)Math.Sqrt(5.0f)-1.0f)/4.0f;
        
float G4 = (5.0f-(float)Math.Sqrt(5.0f))/20.0f;
        
float n0n1n2n3n4

        
float s = (w) * F4
        
int i fastfloor(s);
        
int j fastfloor(s);
        
int k fastfloor(s);
        
int l fastfloor(s);
        
float t = (l) * G4
        
float X0 t
        
float Y0 t;
        
float Z0 t;
        
float W0 t;
        
float x0 X0
        
float y0 Y0;
        
float z0 Z0;
        
float w0 W0;
        
        
int c1 = (x0 y0) ? 32 0;
        
int c2 = (x0 z0) ? 16 0;
        
int c3 = (y0 z0) ? 0;
        
int c4 = (x0 w0) ? 0;
        
int c5 = (y0 w0) ? 0;
        
int c6 = (z0 w0) ? 0;
        
int c c1 c2 c3 c4 c5 c6;
        
int i1j1k1l1;
        
int i2j2k2l2;
        
int i3j3k3l3;
        
        
i1 simplex[c].x>=0;
        
j1 simplex[c].y>=0;
        
k1 simplex[c].z>=0;
        
l1 simplex[c].w>=0;
        
i2 simplex[c].x>=0;
        
j2 simplex[c].y>=0
        
k2 simplex[c][2]>=0;
        
l2 simplex[c].w>=0;
        
        
i3 simplex[c].x>=0;
        
j3 simplex[c].y>=0;
        
k3 simplex[c].z>=0;
        
l3 simplex[c].w>=0;
        
        
float x1 x0 i1 G4;
        
float y1 y0 j1 G4;
        
float z1 z0 k1 G4;
        
float w1 w0 l1 G4;
        
float x2 x0 i2 2.0f*G4;
        
float y2 y0 j2 2.0f*G4;
        
float z2 z0 k2 2.0f*G4;
        
float w2 w0 l2 2.0f*G4;
        
float x3 x0 i3 3.0f*G4;
        
float y3 y0 j3 3.0f*G4;
        
float z3 z0 k3 3.0f*G4;
        
float w3 w0 l3 3.0f*G4;
        
float x4 x0 1.0f 4.0f*G4;
        
float y4 y0 1.0f 4.0f*G4;
        
float z4 z0 1.0f 4.0f*G4;
        
float w4 w0 1.0f 4.0f*G4;
        
        
int ii 255;
        
int jj 255;
        
int kk 255;
        
int ll 255;
        
int gi0 perm[ii+perm[jj+perm[kk+perm[ll]]]] % 32;
        
int gi1 perm[ii+i1+perm[jj+j1+perm[kk+k1+perm[ll+l1]]]] % 32;
        
int gi2 perm[ii+i2+perm[jj+j2+perm[kk+k2+perm[ll+l2]]]] % 32;
        
int gi3 perm[ii+i3+perm[jj+j3+perm[kk+k3+perm[ll+l3]]]] % 32;
        
int gi4 perm[ii+1+perm[jj+1+perm[kk+1+perm[ll+1]]]] % 32;
        
        
float t0 0.5f x0*x0 y0*y0 z0*z0 w0*w0;
        if(
t0<0n0 0.0f;
        else {
        
t0 *= t0;
        
n0 t0 t0 dot(grad4[gi0], new Vector4(x0y0z0w0));
        }
        
float t1 0.5f x1*x1 y1*y1 z1*z1 w1*w1;
        if(
t1<0n1 0.0f;
        else {
        
t1 *= t1;
        
n1 t1 t1 dot(grad4[gi1], new Vector4(x1y1z1w1));
        }
        
float t2 0.5f x2*x2 y2*y2 z2*z2 w2*w2;
        if(
t2<0n2 0.0f;
        else {
        
t2 *= t2;
        
n2 t2 t2 dot(grad4[gi2], new Vector4(x2y2z2w2));
        }
        
float t3 0.5f x3*x3 y3*y3 z3*z3 w3*w3;
        if(
t3<0n3 0.0f;
        else {
        
t3 *= t3;
        
n3 t3 t3 dot(grad4[gi3], new Vector4(x3y3z3w3));
        }
        
float t4 0.5f x4*x4 y4*y4 z4*z4 w4*w4;
        if(
t4<0n4 0.0f;
        else {
        
t4 *= t4;
        
n4 t4 t4 dot(grad4[gi4], new Vector4(x4y4z4w4));
        }
        
        return 
zScale * (n0 n1 n2 n3 n4);
    }
    


Последний раз редактировалось dsd, 26.02.2013 в 03:27.
(Offline)
 
Ответить с цитированием
Эти 2 пользователя(ей) сказали Спасибо dsd за это полезное сообщение:
MadMedic (08.03.2013), pax (25.02.2013)
Старый 24.02.2013, 22:58   #2
seaman
Знающий
 
Регистрация: 08.01.2013
Адрес: Самара
Сообщений: 284
Написано 104 полезных сообщений
(для 180 пользователей)
Ответ: Simplex noise 2d 3d 4d

Если бы на шейдерах было бы куда интереснее.
(Offline)
 
Ответить с цитированием
Старый 26.02.2013, 03:19   #3
dsd
Мастер
 
Аватар для dsd
 
Регистрация: 13.06.2011
Сообщений: 1,103
Написано 481 полезных сообщений
(для 1,836 пользователей)
Ответ: Simplex noise 2d 3d 4d

гексагон с 25% лишних точек.



using UnityEngine;
using System;


public class 
CreateHexagone MonoBehaviour {
    public 
int width=10;
    
// Use this for initialization
    
void Start () {
            
//ставлю точки
            
Vector3[] vert = new Vector3[(width+1)*(width+1)];
            
Vector3[] normals = new Vector3[(width+1)*(width+1)];
            
Vector2[] uv = new Vector2[(width+1)*(width+1)];
            
//синусокосинус 45 градусов
            
float cosin =(float)Math.Sqrt (Math.PI*0.25f);
            for(
int i 0i<=widthi++){
                for( 
int j 0j<=widthj++){
                
//поворот на 45 градусов и сжатие по одной оси на корень из двух пока треугольник не станет правильным        
                    
float xCoor =(i-j)*cosin;
                    
float zCoor =(i+j-width)*0.5f;
                    
float yCoor 0;
                    
vert[i*(width+1)+j] = new Vector3(xCoor,yCoor,zCoor);
                    
normals[i*(width+1)+j] = new Vector3(0,1,0);
                    
uv[i*(width+1)+j] = new Vector2(xCoor,zCoor);
            }}    
            
//ставлю треугольники
            
int[] trians = new int[3*2*width*width];
            
int trianIndex =0;
            for(
int i 0i<widthi++){
                for( 
int j 0j<widthj++){
                    
int v0 i*(width+1)+j;
                    
int v1 v0+1;
                    
int v2 v0+width+1;
                    
int v3 v2+1;
                
//прямая -x+y-0.5*width=0 и прямая -x+y+0.5*width=0
                //точка (i,j)
                //расстояние от прямой d = (-1*i + 1*j+0.5*width)/sqrt(2)
                //так как нужен только знак то все проще
                
float d0 = -i+j+0.5f*width;
                
float d1 = -i+j-0.5f*width;
                if(
d0>=&& d1<0){
                    
trians[trianIndex+0]=v0;
                    
trians[trianIndex+1]=v1;
                    
trians[trianIndex+2]=v3;
                    
trianIndex+=3;
                }
                if(
d0>&& d1<=0){
                    
trians[trianIndex+0]=v0;
                    
trians[trianIndex+1]=v3;
                    
trians[trianIndex+2]=v2;
                    
trianIndex+=3;
                }
            }}
            
gameObject.AddComponent("MeshFilter");
            
Mesh mesh GetComponent<MeshFilter>().mesh;
            
mesh.Clear();
            
mesh.vertices vert;
            
mesh.uv uv;
            
mesh.triangles trians;
            
mesh.normals normals;
    }
    
    
// Update is called once per frame
    
void Update () {
    
    }

(Offline)
 
Ответить с цитированием
Старый 04.03.2013, 00:52   #4
dsd
Мастер
 
Аватар для dsd
 
Регистрация: 13.06.2011
Сообщений: 1,103
Написано 481 полезных сообщений
(для 1,836 пользователей)
Ответ: Simplex noise 2d 3d 4d


Слегка модифицированный шум перлина.

using UnityEngine;
using System.Collections;
using System;

public class 
PerlinNoise MonoBehaviour {
    
        private static 
System.Random randGen
        private static 
int[] rand = new int[512];
        private static 
float[] reliefFactor = {1.0f,0.5f,0.25f,0.125f,0.125f,0.125f,0.125f,0.125f};
        public static 
float zoom 1.0f;
    
// Use this for initialization
    
public static void Init int seed) {
        
randGen = new System.Random(seed);
        for(
int i=0i<511i++) rand[i] = randGen.Next(0,255); 
    }
    
    
     private static 
float fade(float t) {
         return 
t*t*t*(t*(t*6-15)+10);
        }
    
    private static 
int myRand(int xint y){
        
int x0 x%256;
        
int y0 y%512;
        
int result 0;
        if(
x0>=&& y0>=0)result rand[x0+rand[y0]];
        return 
result;
    }
    
    public static 
float perlin2d(float xfloat yint octave){
        
        
int length reliefFactor.Length;
        
float result 0.0f;
        
float height 0.0f;
        for( 
int i=1i<=lengthi++){
            
//принимаю шум от текущей октавы в (0;1) перевожу к (-1;1);
            
float octaveNoise =2*noise(x*zoom*i,y*zoom*i)-1;
            
result += octaveNoise*reliefFactor[i-1];
            
height += reliefFactor[i-1];
        }
        
            
//перевожу к (-1;1);
        
result result/height;
        
        
float degree = (Mathf.Abs(result) + 1)*2.5f;
        
float reliefHeight 1.15f;
        if(
result>=0){result Mathf.Pow(reliefHeight*result,degree);}
        else{
result = -Mathf.Pow(Mathf.Abs(reliefHeight*result),degree);}
        
        
        return 
result;
        
    }
    
    
    private static 
float noise(float xfloat y){
        
//получаю координаты ячейки
        
int x0 Mathf.FloorToInt(x);
        
int y0 Mathf.FloorToInt(y);
        
//смещение внутри ячейки
        
float dx x-x0;
        
float dy y-y0;
        
//получаю четыре значения в углах клетки
        
int x00 myRand(x0,y0);
        
int x01 myRand(x0,y0+1);
        
int x10 myRand(x0+1,y0);
        
int x11 myRand(x0+1,y0+1);

        
//получаю значение в клетке для текущей координаты
        
float dif0 Mathf.Lerp(x00,x01,fade (dy));
        
float dif1 Mathf.Lerp(x10,x11,fade (dy));
        
float result Mathf.Lerp(dif0,dif1,fade (dx));
        return 
result*0.0039215686274509803921568627451f;
        
    }

Миниатюры
Нажмите на изображение для увеличения
Название: perlin.jpg
Просмотров: 1910
Размер:	207.1 Кб
ID:	18890  

Последний раз редактировалось dsd, 04.03.2013 в 13:28.
(Offline)
 
Ответить с цитированием
Эти 2 пользователя(ей) сказали Спасибо dsd за это полезное сообщение:
MadMedic (08.03.2013), pax (04.03.2013)
Старый 04.03.2013, 12:00   #5
pax
Unity/C# кодер
 
Аватар для pax
 
Регистрация: 03.10.2005
Адрес: Россия, Рязань
Сообщений: 7,568
Написано 3,006 полезных сообщений
(для 5,323 пользователей)
Ответ: Simplex noise 2d 3d 4d

mix это наверное тоже самое что и Mathf.Lerp и есть еще Mathf.FloorToInt оно точно медленнее?
__________________
Blitz3d to Unity Wiki
(Offline)
 
Ответить с цитированием
Сообщение было полезно следующим пользователям:
dsd (04.03.2013)
Старый 04.03.2013, 13:28   #6
dsd
Мастер
 
Аватар для dsd
 
Регистрация: 13.06.2011
Сообщений: 1,103
Написано 481 полезных сообщений
(для 1,836 пользователей)
Ответ: Simplex noise 2d 3d 4d

Сообщение от pax Посмотреть сообщение
mix это наверное тоже самое что и Mathf.Lerp и есть еще Mathf.FloorToInt оно точно медленнее?
Тоже самое, а про медленей или быстрей я не в курсе, в туторе было написано что быстрей, а я доверчивый)

Ну на 225к вызовов разницы вроде не видно.
зы: код обновил.
(Offline)
 
Ответить с цитированием
Сообщение было полезно следующим пользователям:
pax (04.03.2013)
Старый 08.03.2013, 13:33   #7
Okay
Знающий
 
Регистрация: 21.11.2011
Сообщений: 284
Написано 17 полезных сообщений
(для 74 пользователей)
Ответ: Simplex noise 2d 3d 4d

Ничего себе код...
(Offline)
 
Ответить с цитированием
Старый 12.03.2013, 00:35   #8
dsd
Мастер
 
Аватар для dsd
 
Регистрация: 13.06.2011
Сообщений: 1,103
Написано 481 полезных сообщений
(для 1,836 пользователей)
Ответ: Simplex noise 2d 3d 4d


какая то фигня при отрисовке в текстуру напоминающая реки.
довольно шустрая для карты 1024х1024

using UnityEngine;
using System.Collections;

public class 
CalcRiverbend MonoBehaviour {
    public static 
int width 1024;
    
//карта высот
    
public static float [,] map = new float [width,width];
    
//количество воды прошедшей по клетке
    
public static int [,] water = new int [width,width];
    
//количество воды в клетке
    
public static int [,] waterNumber = new int [width,width];
    
//кто из соседей клетки самый нижний
    // значение от 0 до 9
    
public static byte [,] height = new byte [width,width];
    
//смещения для воды
    
public static Vector2 [] disp = {
        new 
Vector2(-1,-1), new Vector2(-1,0), new Vector2(-1,1), new Vector2(0,-1),
        new 
Vector2(0,0), new Vector2(0,1), new Vector2(1,-1), new Vector2(1,0), new Vector2(1,1)};
    
    
    public static 
void Init(){
        
//получение карты высот
        
for(int i 0widthi++){
            for(
int j 0widthj++) {
                
map[i,j] = PerlinNoise.perlin2d(i*0.01f,j*0.01f,0);
            }
        }
        
//вычисление самого низкого из ближайших соседей
        
for(int i 0widthi++){
            for(
int j 0widthj++) {        
                
height[i,j] = CalcLowest(i,j);
            }
        }
        
//теперь сбрасываю на каждую клетку карты по 1 капле воды
        
for(int i 0widthi++){
            for(
int j 0widthj++) {
                
waterNumber[i,j] = 1;
            }
        }
        
//а теперь пусть капли текут вниз
        //заодно считаю для каждой точки сколько капель прошло по ней
        //повторяю сколько то раз процедуру
        
for(int k 0200k++){
            for(
int i 0widthi++){
                for(
int j 0widthj++) {
                    
//если в точке есть капли
                    
if (waterNumber[i,j]>0) {
                        
//узнаю в какую из соседей она течет
                        
Vector2 displacement disp[height[i,j]];
                        
//номер ячейки
                        
int x0= (int)displacement.iy0 = (int)displacement.j;
                        
//если точки в границах
                        
if(x0>=&& y0>=&& x0<width && y0<width){
                            
//перевожу воду куда следует
                            
waterNumber[x0,y0] += waterNumber[i,j];
                            
//увеличиваю счетчик воды прошедшей по клетке
                            
water[i,j] += waterNumber[i,j]; 
                            
//убираю утекшую воду
                            
waterNumber[i,j] = 0;
                        }                    
                    }
                }
            }    
        }
    }
    
//вычисляет какое из девяти чисел самое маленькое
    
private static byte CalcLowest(int xint y){
        
//пусть нижняя центральная по умолчанию
        
byte result 4;
        
//создаю массив для значений высот
        
float [] heights = {0f,0f,0f,0f,0f,0f,0f,0f,0f};
        
//теперь заполняю его значения высот
        
for(int i = -1<=1i++){
            for(
int j = -1<=1j++) {    
                
int x0x+iy0 y+j;
                if(
x0>=&& y0>=&& x0<width && y0<width){
                    
heights[(i+1)*3+j+1] = map[x0,y0];    
                }
            }
        }    
        
//рисую где находится нижняя точка из текущих 9-ти    
        
for(int i 0heights.Lengthi++){
            if(
heights[result]>heights[i]){result = (byte)i;}
        }
        return 
result;
    }


Миниатюры
Нажмите на изображение для увеличения
Название: rivers.jpg
Просмотров: 1452
Размер:	151.7 Кб
ID:	18926  
(Offline)
 
Ответить с цитированием
Старый 07.05.2013, 02:51   #9
dsd
Мастер
 
Аватар для dsd
 
Регистрация: 13.06.2011
Сообщений: 1,103
Написано 481 полезных сообщений
(для 1,836 пользователей)
Ответ: Simplex noise 2d 3d 4d

3д шум наподобие одной октавы из 3д шума перлина выдает значения от 0 до 1


using UnityEngine;
using System.Collections;
using System;

public class 
Noise3D MonoBehaviour {
    
        private static 
System.Random randGen
        private static 
int[] randData = new int[512];
    
    public static 
void init int seed) {
        
randGen = new System.Random(seed);
        for(
int i=0i<511i++) randData[i] = randGen.Next(0,255); 
    }
    
//сплайн для апроксимации
     
private static float fade(float t) {
         return 
t*t*t*(t*(t*6-15)+10);
    }    
    
     
//выдает по координате значение из фэйкового бесконечного массива
    
private static int rand(int xint yint z){
        
int x0 =(256+(x%256))%256;
        
int y0 =(256+(y%256))%256;
        
int z0 =(256+(z%256))%256;    
        return 
randDatax0 randDatay0 randDataz0 ] ] ];     
    }
    public static 
float noise(Vector3 pos){
        
int x0 Mathf.FloorToInt(pos.x);
        
int y0 Mathf.FloorToInt(pos.y);
        
int z0 Mathf.FloorToInt(pos.z);
        
//смещение внутри ячейки
        
float dx pos.x-x0;
        
float dy pos.y-y0;
        
float dz pos.z-z0;
        
//читаю 8 точек из фэйкового рандома
        
int x000 rand(x0,y0,z0);
        
int x001 rand(x0,y0,z0+1);
        
int x010 rand(x0,y0+1,z0);
        
int x011 rand(x0,y0+1,z0+1);
        
int x100 rand(x0+1,y0,z0);
        
int x101 rand(x0+1,y0,z0+1);
        
int x110 rand(x0+1,y0+1,z0);
        
int x111 rand(x0+1,y0+1,z0+1);    
        
//смешиваю
        
float dif00 Mathf.Lerp(x000,x001,fade(dz));
        
float dif01 Mathf.Lerp(x010,x011,fade(dz));
        
float dif10 Mathf.Lerp(x100,x101,fade(dz));
        
float dif11 Mathf.Lerp(x110,x111,fade(dz));
        
        
float diff0 Mathf.Lerp(dif00,dif01,fade(dy));
        
float diff1 Mathf.Lerp(dif10,dif11,fade(dy));
        
        return 
Mathf.Lerp(diff0,diff1,fade(dx))*0.0039215686274509803921568627451f;
    }
    
    
// Use this for initialization
    
void Start () {
    }
    
    
// Update is called once per frame
    
void Update () {
    }

Миниатюры
Нажмите на изображение для увеличения
Название: 165468.jpg
Просмотров: 1300
Размер:	40.3 Кб
ID:	19145  
(Offline)
 
Ответить с цитированием
Сообщение было полезно следующим пользователям:
pax (07.05.2013)
Ответ


Опции темы

Ваши права в разделе
Вы не можете создавать темы
Вы не можете отвечать на сообщения
Вы не можете прикреплять файлы
Вы не можете редактировать сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.


Часовой пояс GMT +4, время: 05:59.


vBulletin® Version 3.6.5.
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Перевод: zCarot
Style crйe par Allan - vBulletin-Ressources.com