Example #1
0
    def __init__(self,
                 film_width,
                 film_height,
                 camera2world,
                 vfov,
                 aperture=0.0,
                 focus_dist=1.0):
        self.m_film = Film(film_width, film_height)
        self.m_sv_camera2world = vki.SVMat4x4(camera2world)
        theta = vfov * math.pi / 180.0
        half_height = math.tan(theta * 0.5) * focus_dist
        size_pix = half_height * 2.0 / film_height
        lens_radius = aperture * 0.5
        self.m_sv_size_pix = vki.SVFloat(size_pix)
        self.m_sv_lens_radius = vki.SVFloat(lens_radius)
        self.m_sv_focus_dist = vki.SVFloat(focus_dist)
        self.m_cptr = SVCombine_Create(
            {
                'film': self.m_film,
                'camera2world': self.m_sv_camera2world,
                'size_pix': self.m_sv_size_pix,
                'lens_radius': self.m_sv_lens_radius,
                'focus_dist': self.m_sv_focus_dist
            }, '''
void generate_ray(in Comb_#hash# camera, float film_x, float film_y, float lens_x, float lens_y, out vec3 origin, out vec3 dir)
{
	origin = vec3(lens_x*camera.lens_radius, lens_y*camera.lens_radius, 0.0);
	origin = (camera.camera2world*vec4(origin, 1.0)).xyz;
	vec3 pos_pix = vec3((film_x - float(camera.film.width)*0.5)*camera.size_pix, (float(camera.film.height)*0.5 - film_y)*camera.size_pix, -camera.focus_dist);
	pos_pix = (camera.camera2world*vec4(pos_pix, 1.0)).xyz;
	dir = normalize(pos_pix - origin);	
}
''')
Example #2
0
def thread_func():
    darr_out = vki.SVVector('float', 5)
    darr_out2 = vki.SVVector('int', 5)
    forLoop.launch_n(5, [darr, darr_out, vki.SVFloat(10.0)])
    forLoop.launch_n(5, [darr2, darr_out2, vki.SVInt32(5)])
    print(darr_out.to_host())
    print(darr_out2.to_host())
Example #3
0
 def download_srgb(self, boost=1.0):
     sv_times_expo = vki.SVFloat(self.m_times_exposure)
     sv_boost = vki.SVFloat(boost)
     colorBuf = vki.Texture2D(self.m_width, self.m_height,
                              VK_FORMAT_R8G8B8A8_SRGB)
     self.film2srgb.launch([3], [colorBuf], None, [0.5, 0.5, 0.5, 1.0], 1.0,
                           [self, sv_times_expo, sv_boost])
     srgb = np.empty((self.m_height, self.m_width, 4), dtype=np.uint8)
     colorBuf.download(srgb)
     return srgb
Example #4
0
    def __init__(self, texId, transform=glm.identity(glm.mat3)):
        self.m_texId = vki.SVInt32(texId)
        self.m_trans = vki.SVMat3x3(transform)
        self.m_cptr = SVCombine_Create(
            {
                'texId': self.m_texId,
                'transform': self.m_trans
            }, '''
Spectrum get_sky_color(in Comb_#hash# sky, in vec3 dir)
{
	vec3 direction = sky.transform*dir;
	Spectrum col;
	from_rgb(col, texture(arr_cubemap[sky.texId], direction).rgb);
	return col;	
}
''')
Example #5
0
    def __init__(self, width, height):
        self.m_width = width
        self.m_height = height
        self.m_svwidth = vki.SVInt32(width)
        self.m_svheight = vki.SVInt32(height)
        self.m_svbuf = vki.SVBuffer('vec3', width * height)
        self.m_cptr = SVCombine_Create(
            {
                'data': self.m_svbuf,
                'width': self.m_svwidth,
                'height': self.m_svheight
            }, '''
vec3 read_pixel(in Comb_#hash# img, int x, int y)
{
    return img.data[x + y*img.width].v;
}

void write_pixel(in Comb_#hash# img, int x, int y, in vec3 v)
{
    img.data[x + y*img.width].v = v;
}

void incr_pixel(in Comb_#hash# img, int x, int y, in vec3 v)
{
	vec3 col = read_pixel(img, x, y);
	write_pixel(img, x, y, col + v);
}

void incr_pixel(in Comb_#hash# img, int x, int y, in Spectrum col)
{
	incr_pixel(img, x, y, to_xyz(col));
}

void incr_pixel_atomic(in Comb_#hash# img, int x, int y, in vec3 v)
{
	atomicAdd(img.data[x + y*img.width].v.x, v.x);
	atomicAdd(img.data[x + y*img.width].v.y, v.y);
	atomicAdd(img.data[x + y*img.width].v.z, v.z);
}

void incr_pixel_atomic(in Comb_#hash# img, int x, int y, in Spectrum col)
{
	incr_pixel_atomic(img, x, y, to_xyz(col));
}
''')
        self.m_times_exposure = 0.0
Example #6
0
    def __init__(self):
        self.m_t = vki.SVFloat(0.0)
        self.m_light_id = vki.SVInt32(0)
        self.m_intensity = Spectrum()
        self.m_cptr = SVCombine_Create(
            {
                't': self.m_t,
                'light_id': self.m_light_id,
                'intensity': self.m_intensity
            }, '''
Spectrum Le(in Comb_#hash# self, in vec3 wo, int depth_iter)
{
    Spectrum ret = self.intensity;
    if (depth_iter>0)
    {
        from_rgb(ret, vec3(0.0));
    }
    return ret;
}
''')
Example #7
0
    def __init__(self, lst_svobjs, objIdOffset):
        self.m_size = vki.SVUInt32(len(lst_svobjs))
        self.m_buf = vki.SVObjBuffer(lst_svobjs)
        self.m_id_offset = vki.SVUInt32(objIdOffset)
        self.m_cptr = SVCombine_Create(
            {
                'size': self.m_size,
                'data': self.m_buf,
                'id_offset': self.m_id_offset
            }, '''
uint get_size(in Comb_#hash# vec)
{{
     return vec.size;
}}

{0} get_value(in Comb_#hash# vec, in uint id)
{{
    return vec.data[id].v;
}}
'''.format(self.name_elem_type()))
Example #8
0
    def __init__(self, center, r, color, intensity):
        modelMat = glm.identity(glm.mat4)
        modelMat = glm.translate(modelMat, glm.vec3(center))
        modelMat = glm.scale(modelMat, glm.vec3(r, r, r))
        Sphere.__init__(self, modelMat)
        self.m_r = r        
        self.d_center_radius = vki.SVVec4(glm.vec4(center[0],center[1],center[2], r))
        self.d_intensity = Spectrum(glm.vec3(color)*intensity)
        self.m_cptr = SVCombine_Create({'center_radius': self.d_center_radius, 'intensity': self.d_intensity }, '''
void closethit(in Comb_#hash# self, in vec3 hitpoint, inout {HitInfo_UniformEmissive} hitinfo)
{{
    hitinfo.intensity = self.intensity;
}}

Spectrum sample_l(in Comb_#hash# self, in vec3 ip, inout RNGState state, inout vec3 dirToLight, inout float distance, inout float pdfw)
{{
    vec3 dir = self.center_radius.xyz - ip;
    float dis2center = length(dir);
    dir *= 1.0/dis2center;

    float factor = (dis2center - self.center_radius.w)/dis2center;

    float r1 = rand01(state);
    float r2 = rand01(state) * radians(360.0);
    vec3 a, b;
    if (abs(dir.x)>0.8)
        a = vec3(0.0, 1.0, 0.0);
    else 
        a = vec3(1.0, 0.0, 0.0);

    a = normalize(cross(a, dir));
    b = cross(a, dir);

    float v_z = 1.0 - r1 * factor;
    float v_xy = sqrt(1.0 - v_z*v_z);
    float v_x = v_xy * cos(r2);
    float v_y = v_xy * sin(r2);

    vec3 offset_dir = a*v_x + b*v_y - v_z*dir;
    vec3 pos = self.center_radius.xyz + offset_dir *self.center_radius.w;

    dirToLight = pos - ip;
    distance = length(dirToLight);
    dirToLight *= 1.0/distance;

    float p = 1.0/(radians(360.0)*self.center_radius.w*self.center_radius.w*factor);
    pdfw = p*distance*distance/dot(dirToLight, -offset_dir);

    return self.intensity;

}}
'''.format(HitInfo_UniformEmissive = Name_HitInfo_UniformEmissive))
Example #9
0
    def render(self, cube, filename = None, up_face_only=False, up_face_id = 2, cross_mode = False):                
        colorBuf = vki.Texture2D(self.wh, self.wh, VK_FORMAT_R8G8B8A8_SRGB)             
        
        gpu_map = vki.device_vector_from_numpy(cube.map)
        gpu_colors = vki.device_vector_from_numpy(self.colors)

        if cross_mode:
            up_face_only = True

        if not up_face_only:
            up_face_id = -1

        gpu_up_face_id = vki.SVInt32(up_face_id)
        gpu_cross_mode = vki.SVInt32(cross_mode)
        self.rp.launch([(4*3+9)*6], [colorBuf], None, self.bg_color, 1.0, [gpu_map, gpu_colors, gpu_up_face_id, gpu_cross_mode])

        image_out = np.empty((self.wh, self.wh, 4), dtype=np.uint8)
        colorBuf.download(image_out)

        if not filename is None:
            Image.fromarray(image_out, 'RGBA').save(filename) 

        return image_out
Example #10
0
    def __init__(self):
        self.m_t = vki.SVFloat(0.0)
        self.m_normal = vki.SVVec3(glm.vec3(0.0))
        self.m_cptr = SVCombine_Create(
            {
                't': self.m_t,
                'normal': self.m_normal,
                'lambert': BxDF_Lambert.dummy
            }, '''
Spectrum evaluate_bsdf(in Comb_#hash# self, in vec3 wo, in vec3 wi)
{
    return f(self.lambert, self.normal, wo, wi);
}

float pdf_bsdf(in Comb_#hash# self, in vec3 wo, in vec3 wi)
{
    return pdf(self.lambert, self.normal, wo, wi);
}

Spectrum sample_bsdf(in Comb_#hash# self, in vec3 wo, inout vec3 wi, inout RNGState state, inout float path_pdf)
{
    return sample_f(self.lambert, self.normal, wo, wi, state, path_pdf);
}
''')
Example #11
0
    def __init__(self, modelMat=glm.identity(glm.mat4), color=(1.0, 1.0, 1.0)):
        Sphere.__init__(self, modelMat)
        self.d_normMat = vki.SVMat4x4(self.m_normMat)
        self.d_color = Spectrum(color)
        self.m_cptr = SVCombine_Create(
            {
                'normalMat': self.d_normMat,
                'color': self.d_color
            }, '''
void closethit(in Comb_#hash# self, in vec3 hitpoint, inout {HitInfo_Lambert} hitinfo)
{{
    hitinfo.lambert.color = self.color;
    hitinfo.normal = normalize((self.normalMat * vec4(hitpoint, 0.0)).xyz);   
}}
'''.format(HitInfo_Lambert=Name_HitInfo_Lambert))
Example #12
0
    def __init__(self,
                 positions,
                 normals,
                 indices_pos,
                 indices_norm,
                 modelMat=glm.identity(glm.mat4),
                 color=(1.0, 1.0, 1.0)):
        Geometry.__init__(self, modelMat)
        self.m_gpuPos = vki.device_vector_from_numpy(positions)
        self.m_gpuNorm = vki.device_vector_from_numpy(normals)
        self.m_gpuIndPos = vki.device_vector_from_numpy(indices_pos)
        self.m_gpuIndNorm = vki.device_vector_from_numpy(indices_norm)
        self.m_blas = vki.BaseLevelAS(self.m_gpuIndPos, self.m_gpuPos)

        vert0 = positions[0]
        self.m_aabb = np.array(
            [vert0[0], vert0[1], vert0[2], vert0[0], vert0[1], vert0[2]],
            dtype=np.float32)
        for vert in positions:
            self.m_aabb[0] = min(self.m_aabb[0], vert[0])
            self.m_aabb[1] = min(self.m_aabb[1], vert[1])
            self.m_aabb[2] = min(self.m_aabb[2], vert[2])
            self.m_aabb[3] = max(self.m_aabb[3], vert[0])
            self.m_aabb[4] = max(self.m_aabb[4], vert[1])
            self.m_aabb[5] = max(self.m_aabb[5], vert[2])

        self.d_normMat = vki.SVMat4x4(self.m_normMat)
        self.d_color = Spectrum(color)
        self.m_cptr = SVCombine_Create(
            {
                'indices': self.m_gpuIndNorm,
                'normals': self.m_gpuNorm,
                'normalMat': self.d_normMat,
                'color': self.d_color
            }, '''
void closethit(in Comb_#hash# self, int primitiveId, in vec3 barycentrics, inout {HitInfo_Lambert} hitinfo)
{{    
    uint i0 = get_value(self.indices, 3 * primitiveId);
    uint i1 = get_value(self.indices, 3 * primitiveId + 1);
    uint i2 = get_value(self.indices, 3 * primitiveId + 2);

    vec3 norm0 = get_value(self.normals, i0);
    vec3 norm1 = get_value(self.normals, i1);
    vec3 norm2 = get_value(self.normals, i2);

    vec3 normal = norm0 * barycentrics.x + norm1 * barycentrics.y + norm2 * barycentrics.z;
    normal = normalize((self.normalMat * vec4(normal, 0.0)).xyz);   

    hitinfo.lambert.color = self.color;    
    hitinfo.normal = normal;

}}
'''.format(HitInfo_Lambert=Name_HitInfo_Lambert))
Example #13
0
    def __init__(self, position, color, intensity):
        self.d_pos = vki.SVVec3(glm.vec3(position))
        self.d_intensity = Spectrum(glm.vec3(color) * intensity)
        self.m_cptr = SVCombine_Create(
            {
                'pos': self.d_pos,
                'intensity': self.d_intensity
            }, '''
Spectrum sample_l(in Comb_#hash# self, in vec3 ip, inout RNGState state, inout vec3 dirToLight, inout float distance, inout float pdfw)
{
    vec3 v = self.pos - ip;
    float len = length(v);
    dirToLight = v / len;
    pdfw = len*len;
    distance = len;
    return self.intensity;    
}
''')
Example #14
0
    def __init__(self, direction, radian, color, intensity):
        direction = glm.normalize(glm.vec3(direction))
        self.m_radian = radian
        self.d_dir_radian = vki.SVVec4(glm.vec4(direction, radian))
        self.d_intensity = Spectrum(glm.vec3(color) * intensity)
        self.m_cptr = SVCombine_Create(
            {
                'dir_radian': self.d_dir_radian,
                'intensity': self.d_intensity
            }, '''
Spectrum sample_l(in Comb_#hash# self, in vec3 ip, inout RNGState state, inout vec3 dirToLight, inout float distance, inout float pdfw)
{
    vec3 dir = self.dir_radian.xyz;
    float factor = 1.0 - cos(self.dir_radian.w);

    float r1 = rand01(state);
    float r2 = rand01(state) * radians(360.0);
    vec3 a, b;
    if (abs(dir.x)>0.8)
        a = vec3(0.0, 1.0, 0.0);
    else 
        a = vec3(1.0, 0.0, 0.0);

    a = normalize(cross(a, dir));
    b = cross(a, dir);

    float v_z = 1.0 - r1 * factor;
    float v_xy = sqrt(1.0 - v_z*v_z);
    float v_x = v_xy * cos(r2);
    float v_y = v_xy * sin(r2);

    dirToLight = v_z*dir + a*v_x + b*v_y;

    distance = -1.0;
    pdfw = 1.0/(radians(360.0)*factor);

    return self.intensity;
}
''')
Example #15
0
    def render(self, cube, filename = None):        
        colorBuf = vki.Texture2D(self.width, self.height, VK_FORMAT_R8G8B8A8_SRGB)
        colorBuf4x = vki.Texture2D(self.width, self.height, VK_FORMAT_R8G8B8A8_SRGB, samples=4)
        depthBuf4x = vki.Texture2D(self.width, self.height, VK_FORMAT_D32_SFLOAT, isDepth=True, samples=4)       
        
        gpu_matrix = vki.SVMat4x4(self.matrix)
        gpu_map = vki.device_vector_from_numpy(cube.map)
        gpu_dirs = vki.device_vector_from_numpy(cube.dirs)
        self.rp.launch([6*9*6], [colorBuf4x], depthBuf4x, self.bg_color, self.bg_depth, [gpu_matrix, gpu_map, gpu_dirs], resolveBufs=[colorBuf], cubemaps = [self.skin])

        image_out = np.empty((self.height, self.width, 4), dtype=np.uint8)
        colorBuf.download(image_out)

        if not filename is None:
            Image.fromarray(image_out, 'RGBA').save(filename)       

        return image_out
Example #16
0
    def __init__(self, power):
        sum_power = 0.0
        cdf = [0.0]
        for p in power:
            sum_power += p
            cdf += [sum_power]
        cdf = [f / sum_power for f in cdf]
        self.m_cdf = vki.device_vector_from_list(cdf, 'float')
        self.m_cptr = SVCombine_Create({'cdf': self.m_cdf}, '''
uint SampleDiscrete(in Comb_#hash# self, float u, inout float pdf)
{
    if (u<0.0) 
    {
        pdf = 0.0;
        return 0;
    }
    
    uint begin = 0;
    uint end = get_size(self.cdf);

    if (u>=1.0)
    {
        pdf = get_value(self.cdf, end-1) - get_value(self.cdf, end-2);
        return end-1;
    }
    
    while (end > begin +1)
    {
        uint mid = begin + ((end-begin)>>1);
        if (u<get_value(self.cdf, mid))
            end = mid;
        else
            begin = mid;
    }
    pdf = get_value(self.cdf, end) - get_value(self.cdf, end-1);
    return end;
}
''')
Example #17
0
import VkInline as vki
from VkInline.SVCombine import *
import glm

vki.Add_Built_In_Header(
    'spectrum.shinc', '''

mat3 mat_rgb2xyz = mat3(
0.412453, 0.212671, 0.019334,
0.357580, 0.715160, 0.119193,
0.180423, 0.072169, 0.950227);

mat3 mat_xyz2rgb = mat3(
3.240479, -0.969256, 0.055648,
-1.537150, 1.875991, -0.204043,
-0.498535, 0.041556, 1.057311);

vec3 rgb2xyz(in vec3 rgb)
{
    return mat_rgb2xyz * rgb;
}

vec3 xyz2rgb(in vec3 xyz)
{
    return mat_xyz2rgb * xyz;
}
''')

vki.Add_Inlcude_Filename('spectrum.shinc')

Example #18
0
import VkInline as vki
import numpy as np

darr = vki.device_vector_from_list(range(1,1025), 'int')
BLOCK_SIZE = 256

kernel = vki.Computer(['dst', 'src', 'n'],
'''
shared {0} s_buf[{1}];
void main()
{{
	uint tid = gl_LocalInvocationID.x;
	uint i = gl_GlobalInvocationID.x;
	if (i<n) s_buf[tid] = get_value(src, i);
	barrier();
	for (uint s = {1}/2; s>0; s>>=1)
	{{
		if (tid < s && i+s<n)
    		s_buf[tid] += s_buf[tid + s];
    	barrier();
	}}
	if (tid==0) set_value(dst, gl_WorkGroupID.x, s_buf[tid]);	
}}
'''.format('int',str(BLOCK_SIZE)))

dst  = darr
while dst.size()>1:
	src = dst
	n = src.size()
	blocks = int((n + BLOCK_SIZE - 1) / BLOCK_SIZE)
	dst = vki.SVVector("int", blocks)
Example #19
0
    for ind in shape.mesh.indices:
        lst_vertex_inds += [ind.vertex_index]
        lst_normal_inds += [ind.normal_index]

vertex_inds = np.array(lst_vertex_inds, dtype=np.uint32)
normal_inds = np.array(lst_normal_inds, dtype=np.uint32)

VK_FORMAT_R8G8B8A8_SRGB = 43

width = 900
height = 600

scene = fri.Scene()

sky_cube = np.array(Image.open('cubemap.png').convert('RGBA'))
gpu_sky_cube = vki.Cubemap(512, 512, VK_FORMAT_R8G8B8A8_SRGB)
gpu_sky_cube.upload(sky_cube)
'''
sky = fri.TexturedSky(scene.add_cubemap(gpu_sky_cube))
scene.set_sky(sky)
'''

sky = fri.GradientSky((0.0, 0.0, 0.0), (0.0, 0.0, 0.0))
scene.set_sky(sky)
'''
point_light0 = fri.PointLight((-5.0, 20.0, -5.0), (0.5, 1.0, 0.5), 1000.0)
scene.add_object(point_light0)

point_light1 = fri.PointLight((5.0, 20.0, 5.0), (1.0, 0.5, 0.5), 1000.0)
scene.add_object(point_light1)
'''
Example #20
0
    def __init__(self, fn_skin = "skin_default.png", backface = False):
        self.width = 640
        self.height = 480
        proj_mat = glm.perspective(glm.radians(45.0), self.width/self.height, 0.1, 1000.0)
        view_mat = glm.lookAt(glm.vec3(10.0,10.0,10.0), glm.vec3(0.0,0.0,0.0), glm.vec3(0.0, 1.0, 0.0))
        self.matrix = proj_mat*view_mat

        self.bg_color = [1.0, 1.0, 1.0, 1.0]
        self.bg_depth = 1.0

        options = {}
        if backface:
            self.bg_depth = 0.0
            options['depth_compare_op'] = VK_COMPARE_OP_GREATER

        skin_in =  np.array(Image.open(fn_skin).convert('RGBA'))
        self.skin = vki.Cubemap(skin_in.shape[1], skin_in.shape[0]//6, VK_FORMAT_R8G8B8A8_SRGB)
        self.skin.upload(skin_in)

        self.rp = vki.Rasterizer(["matrix", "map", "dirs"], type_locked=True)

        

        self.rp.add_draw_call(vki.DrawCall(
'''
const vec3 positions[18] = { 
    vec3(3.0, 3.0, 3.0), vec3(3.0, 3.0, -3.0), vec3(3.0, -3.0, 3.0),
    vec3(-3.0, 3.0, -3.0), vec3(-3.0, 3.0, 3.0), vec3(-3.0, -3.0, -3.0),
    vec3(-3.0, 3.0, -3.0), vec3(3.0, 3.0, -3.0), vec3(-3.0, 3.0, 3.0),
    vec3(-3.0, -3.0, 3.0), vec3(3.0, -3.0, 3.0), vec3(-3.0, -3.0, -3.0),
    vec3(-3.0, 3.0, 3.0), vec3(3.0, 3.0, 3.0), vec3(-3.0, -3.0, 3.0),
    vec3(3.0, 3.0, -3.0), vec3(-3.0, 3.0, -3.0), vec3(3.0, -3.0, -3.0) };

const vec2 indices[24] = { 
    vec2(0.0,0.0), vec2(0.0,1.0), vec2(1.0,1.0), vec2(1.0,1.0), vec2(1.0,0.0), vec2(0.0,0.0),
    vec2(1.0,0.0), vec2(0.0,0.0), vec2(0.0,1.0), vec2(0.0,1.0), vec2(1.0,1.0), vec2(1.0,0.0), 
    vec2(1.0,1.0), vec2(1.0,0.0), vec2(0.0,0.0), vec2(0.0,0.0), vec2(0.0,1.0), vec2(1.0,1.0),
    vec2(0.0,1.0), vec2(1.0,1.0), vec2(1.0,0.0), vec2(1.0,0.0), vec2(0.0,0.0), vec2(0.0,1.0) };

layout (location = 0) out vec3 pos;

void main() 
{   
    uint id_vert = gl_VertexIndex % 6; 
    uint id_sq_out = gl_VertexIndex / 6;    
    uint id_in_face_out = id_sq_out % 9;
    uint id_face_out = id_sq_out / 9;    
    uint id_x_out = id_in_face_out % 3;
    uint id_y_out = id_in_face_out / 3;

    vec3 o_out = positions[id_face_out*3];
    vec3 ox_out = positions[id_face_out*3+1] - o_out;
    vec3 oy_out = positions[id_face_out*3+2] - o_out;

    vec2 idv_out = indices[id_vert];
    vec3 pos_out = o_out + ox_out *(float(id_x_out)+idv_out.x)/3.0 + oy_out *(float(id_y_out)+idv_out.y)/3.0;    

    vec4 wpos = vec4(pos_out, 1.0);
    vec4 ppos = matrix * wpos;    
    ppos.y = -ppos.y;
    ppos.z = (ppos.z + ppos.w) / 2.0;
    gl_Position = ppos;

    uint id_sq_in = get_value(map, id_sq_out);    
    uint id_in_face_in = id_sq_in % 9;
    uint id_face_in = id_sq_in / 9;    
    uint id_x_in = id_in_face_in % 3;
    uint id_y_in = id_in_face_in / 3;

    uint dir_in = get_value(dirs, id_sq_out);

    vec3 o_in = positions[id_face_in*3];
    vec3 ox_in = positions[id_face_in*3+1] - o_in;
    vec3 oy_in = positions[id_face_in*3+2] - o_in;

    vec2 idv_in = indices[6*dir_in + id_vert];
    vec3 pos_in = o_in + ox_in *(float(id_x_in)+idv_in.x)/3.0 + oy_in *(float(id_y_in)+idv_in.y)/3.0; 

    pos = pos_in;
}
''',
'''
layout (location = 0) in vec3 pos;
layout (location = 0) out vec4 outColor;

void main() 
{
    vec3 dir = normalize(pos);
    outColor = texture(arr_cubemap[0], dir);
}
''', options=options))
Example #21
0
import FeiRaysInline as fri
from PIL import Image

VK_FORMAT_R8G8B8A8_SRGB = 43

width = 640
height = 480

world2camera = glm.lookAt(glm.vec3(0.0, 0.0, 0.0), glm.vec3(1.0, 0.0, 0.0), glm.vec3(0.0, 1.0, 0.0))
camera2world = glm.inverse(world2camera)
camera = fri.PerspectiveCamera(width, height, camera2world , 90.0)

# sky = fri.GradientSky()

sky_cube = np.array(Image.open('cubemap.png').convert('RGBA'))
gpu_sky_cube = vki.Cubemap(512, 512, VK_FORMAT_R8G8B8A8_SRGB)
gpu_sky_cube.upload(sky_cube)

sky = fri.TexturedSky(0)


kernel = vki.Computer(['camera', 'sky'],
'''
void main()
{
    int x = int(gl_GlobalInvocationID.x);
    int y = int(gl_GlobalInvocationID.y);
    if (x >= camera.film.width || y>=camera.film.height) return;

    float fx = float(x)+0.5;
    float fy = float(y)+0.5;
Example #22
0
lst_normal_inds = []
for shape in shapes:
    for ind in shape.mesh.indices:
        lst_vertex_inds += [ind.vertex_index]
        lst_normal_inds += [ind.normal_index]

vertex_inds = np.array(lst_vertex_inds, dtype=np.int32)
normal_inds = np.array(lst_normal_inds, dtype=np.int32)

VK_FORMAT_R8G8B8A8_SRGB = 43
VK_FORMAT_D32_SFLOAT = 126

width = 640
height = 480

colorBuf = vki.Texture2D(width, height, VK_FORMAT_R8G8B8A8_SRGB)
depthBuf = vki.Texture2D(width, height, VK_FORMAT_D32_SFLOAT, isDepth=True)
gpuPos = vki.device_vector_from_numpy(positions)
gpuNormals = vki.device_vector_from_numpy(normals)
gpuInd_pos = vki.device_vector_from_numpy(vertex_inds)
gpuInd_norm = vki.device_vector_from_numpy(normal_inds)

rp = vki.Rasterizer(
    ['arr_pos', 'arr_norm', 'ind_pos', 'ind_norm', 'mat_pos', 'mat_norm'])

rp.add_draw_call(
    vki.DrawCall(
        '''
layout (location = 0) out vec3 vNorm;
void main() 
{
Example #23
0
    def __init__(self):
        xorwow_data = np.fromfile(os.path.dirname(__file__) + '/' +
                                  'xor_wow_data.bin',
                                  dtype=np.uint32)
        self.d_xorwow_data = vki.device_vector_from_numpy(xorwow_data)
        self.m_cptr = SVCombine_Create({'data': self.d_xorwow_data}, '''
void matvec_i(int i, uint v_i, in Comb_#hash# initializer, int offset, inout V5 result)
{
    for (int j = 0; j < 32; j++)
        if ((v_i & (1 << j))!=0)
        {
            int k = (i * 32 + j)*5 + offset;            
            result.v0 ^= get_value(initializer.data, k);
            result.v1 ^= get_value(initializer.data, k + 1);
            result.v2 ^= get_value(initializer.data, k + 2);
            result.v3 ^= get_value(initializer.data, k + 3);
            result.v4 ^= get_value(initializer.data, k + 4);
        }
}

void matvec(in V5 vector, in Comb_#hash# initializer, int offset, inout V5 result)
{
    result.v0 = result.v1 = result.v2 = result.v3 = result.v4 = 0;
    matvec_i(0, vector.v0, initializer, offset, result);
    matvec_i(1, vector.v1, initializer, offset, result);
    matvec_i(2, vector.v2, initializer, offset, result);
    matvec_i(3, vector.v3, initializer, offset, result);
    matvec_i(4, vector.v4, initializer, offset, result);                    
}

void state_init(in Comb_#hash# initializer, uint64_t seed, uint64_t subsequence, inout RNGState state)
{
    if (subsequence>= (1<<18) ) subsequence= (1<<18) -1;

    uint s0 = uint(seed) ^ 0xaad26b49U;
    uint s1 = uint(seed >> 32) ^ 0xf7dcefddU;
    uint t0 = 1099087573U * s0;
    uint t1 = 2591861531U * s1;
    state.d = 6615241 + t1 + t0;
    state.v.v0 = 123456789U + t0;
    state.v.v1 = 362436069U ^ t0;
    state.v.v2 = 521288629U + t1;
    state.v.v3 = 88675123U ^ t1;
    state.v.v4 = 5783321U + t0;

    // apply sequence matrix
    V5 result;
    uint64_t p = subsequence;
    int i_mat = 0;

    while (p!=0 && i_mat<7)
    {
        for (uint t = 0; t < (p & 3); t++)
        {
            matvec(state.v, initializer, i_mat*800, result);
            state.v = result;
        }
        p >>= 2;
        i_mat++;
    }
    
    for (uint t = 0; t < (p & 0xF); t++)
    {
        matvec(state.v, initializer, i_mat*800, result);
        state.v = result;
    }
}
''')
Example #24
0
class RNGInitializer(vki.ShaderViewable):
    def __init__(self):
        xorwow_data = np.fromfile(os.path.dirname(__file__) + '/' +
                                  'xor_wow_data.bin',
                                  dtype=np.uint32)
        self.d_xorwow_data = vki.device_vector_from_numpy(xorwow_data)
        self.m_cptr = SVCombine_Create({'data': self.d_xorwow_data}, '''
void matvec_i(int i, uint v_i, in Comb_#hash# initializer, int offset, inout V5 result)
{
    for (int j = 0; j < 32; j++)
        if ((v_i & (1 << j))!=0)
        {
            int k = (i * 32 + j)*5 + offset;            
            result.v0 ^= get_value(initializer.data, k);
            result.v1 ^= get_value(initializer.data, k + 1);
            result.v2 ^= get_value(initializer.data, k + 2);
            result.v3 ^= get_value(initializer.data, k + 3);
            result.v4 ^= get_value(initializer.data, k + 4);
        }
}

void matvec(in V5 vector, in Comb_#hash# initializer, int offset, inout V5 result)
{
    result.v0 = result.v1 = result.v2 = result.v3 = result.v4 = 0;
    matvec_i(0, vector.v0, initializer, offset, result);
    matvec_i(1, vector.v1, initializer, offset, result);
    matvec_i(2, vector.v2, initializer, offset, result);
    matvec_i(3, vector.v3, initializer, offset, result);
    matvec_i(4, vector.v4, initializer, offset, result);                    
}

void state_init(in Comb_#hash# initializer, uint64_t seed, uint64_t subsequence, inout RNGState state)
{
    if (subsequence>= (1<<18) ) subsequence= (1<<18) -1;

    uint s0 = uint(seed) ^ 0xaad26b49U;
    uint s1 = uint(seed >> 32) ^ 0xf7dcefddU;
    uint t0 = 1099087573U * s0;
    uint t1 = 2591861531U * s1;
    state.d = 6615241 + t1 + t0;
    state.v.v0 = 123456789U + t0;
    state.v.v1 = 362436069U ^ t0;
    state.v.v2 = 521288629U + t1;
    state.v.v3 = 88675123U ^ t1;
    state.v.v4 = 5783321U + t0;

    // apply sequence matrix
    V5 result;
    uint64_t p = subsequence;
    int i_mat = 0;

    while (p!=0 && i_mat<7)
    {
        for (uint t = 0; t < (p & 3); t++)
        {
            matvec(state.v, initializer, i_mat*800, result);
            state.v = result;
        }
        p >>= 2;
        i_mat++;
    }
    
    for (uint t = 0; t < (p & 0xF); t++)
    {
        matvec(state.v, initializer, i_mat*800, result);
        state.v = result;
    }
}
''')

    rand_init = vki.Computer(['initializer', 'arr_out'],
                             '''
void main()
{
    uint id = gl_GlobalInvocationID.x;
    if (id >= get_size(arr_out)) return;
    RNGState state;
    state_init(initializer, 1234, uint64_t(id), state);
    set_value(arr_out, id, state);
}
''',
                             type_locked=True)

    def InitRNGVector(self, arr_out):
        blocks = int((arr_out.size() + 127) / 128)
        self.rand_init.launch(blocks, 128, [self, arr_out])
Example #25
0
    def __init__(self, colors = [[0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.2, 0.0], [0.2, 0.2, 0.2]]):
        self.wh = 512
        self.bg_color = [0.0,0.0,0.0,1.0]
        self.colors = np.array(colors, dtype = np.float32)
        self.rp = vki.Rasterizer(["map", "colors", "up_face_id", "cross_mode"], type_locked=True)
        self.rp.add_draw_call(vki.DrawCall(
'''
const vec2 positions[6] = { vec2(0.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0), vec2(1.0, 1.0), vec2(1.0, 0.0), vec2(0.0, 0.0) };    

layout (location = 0) flat out uint v_id_face_in;
layout (location = 1) flat out uint v_id_in_face_in;

void main() 
{   
    uint id_vert = gl_VertexIndex % 6; 
    uint id_sq_out = gl_VertexIndex / 6;
    uint id_in_face_out, id_face_out;

    vec2 k = positions[id_vert];
    vec2 pos;

    if (id_sq_out<9)
    {
        id_in_face_out = id_sq_out;
        id_face_out = 2;        
        uint id_x_out = id_in_face_out % 3;
        uint id_y_out = id_in_face_out / 3;       

        pos.x = -0.77 + 0.52*float(id_x_out) + k.x*0.5;
        pos.y = -0.77 + 0.52*float(id_y_out) + k.y*0.5;
    }
    else if(id_sq_out<12)
    {
        id_in_face_out = id_sq_out - 9;
        id_face_out = 0;

        pos.x = 0.78 + k.x*0.05;
        pos.y = -0.77 + 0.52*float(2 - id_in_face_out) + k.y*0.5;
    }
    else if(id_sq_out<15)
    {
        id_in_face_out = id_sq_out - 12;
        id_face_out = 1;
        pos.x = -0.83 + k.x*0.05;
        pos.y = -0.77 + 0.52*float(id_in_face_out) + k.y*0.5;
    }
    else if(id_sq_out<18)
    {
        id_in_face_out = id_sq_out - 15;
        id_face_out = 4;
        pos.x = -0.77 + 0.52*float(id_in_face_out) + k.x*0.5;
        pos.y = 0.78 + k.y*0.05;

    }
    else
    {
        id_in_face_out = id_sq_out - 18;
        id_face_out = 5;
        pos.x = -0.77 + 0.52*float(2 - id_in_face_out) + k.x*0.5;
        pos.y = -0.83 + k.y*0.05;
    }
    
    gl_Position = vec4(pos, 0.5, 1.0);

    id_sq_out = id_face_out * 9 + id_in_face_out;
    uint id_sq_in = get_value(map, id_sq_out);
    v_id_face_in = id_sq_in / 9;
    v_id_in_face_in = id_sq_in % 9;
}
''',
'''
layout (location = 0) flat in uint v_id_face_in;
layout (location = 1) flat in uint v_id_in_face_in;
layout (location = 0) out vec4 outColor;

void main() 
{    
    if (up_face_id!=-1 && v_id_face_in != up_face_id)
    {    
        outColor = vec4(get_value(colors,6),1.0);
    }
    else if (cross_mode!=0 && v_id_in_face_in/3!=1 && v_id_in_face_in%3!=1)
    {
        outColor = vec4(get_value(colors,6),1.0);
    }
    else
    {
        outColor = vec4(get_value(colors,v_id_face_in),1.0);
    }    
}
'''))
Example #26
0
import VkInline as vki
import numpy as np
import threading

harr = np.array([1.0, 2.0, 3.0, 4.0, 5.0], dtype='float32')
darr = vki.device_vector_from_numpy(harr)

forLoop = vki.For(['arr_in', 'arr_out', 'k'], "inner", '''
void inner(uint idx)
{
    set_value(arr_out, idx, get_value(arr_in, idx)*k);
}
''')


def thread_func():
    darr_out = vki.SVVector('float', 5)
    forLoop.launch_n(5, [darr, darr_out, vki.SVFloat(10.0)])
    print(darr_out.to_host())


a = threading.Thread(target=thread_func)
b = threading.Thread(target=thread_func)
c = threading.Thread(target=thread_func)

a.start()
b.start()
c.start()
c.join()
b.join()
a.join()
Example #27
0
import numpy as np
import VkInline as vki
import FeiRaysInline as fri

count = 1 << 18
d_states = vki.SVVector('RNGState', count)
initializer = fri.RNGInitializer()
initializer.InitRNGVector(d_states)

states = np.empty((count, 6), dtype=np.uint32)
d_states.m_buf.to_host(states.__array_interface__['data'][0])

print(states)
Example #28
0
    def __init__(self, color=(0.0, 0.0, 0.0)):
        self.m_rgb = glm.vec3(color)
        self.m_svdata = vki.SVVec3(self.m_rgb)
        self.m_cptr = SVCombine_Create({'data': self.m_svdata}, '''
void incr(inout Comb_#hash# a, in Comb_#hash# b)
{
    a.data += b.data;
}

Comb_#hash# add(in Comb_#hash# a, in Comb_#hash# b)
{
    Comb_#hash# ret;
    ret.data = a.data + b.data;
    return ret;
}

Comb_#hash# sub(in Comb_#hash# a, in Comb_#hash# b)
{
    Comb_#hash# ret;
    ret.data = a.data - b.data;
    return ret;
}

Comb_#hash# mult(in Comb_#hash# a, in Comb_#hash# b)
{
    Comb_#hash# ret;
    ret.data = a.data * b.data;
    return ret;
}

Comb_#hash# div(in Comb_#hash# a, in Comb_#hash# b)
{
    Comb_#hash# ret;
    ret.data = a.data / b.data;
    return ret;
}

Comb_#hash# mult(in Comb_#hash# a, float b)
{
    Comb_#hash# ret;
    ret.data = a.data * b;
    return ret;
}

Comb_#hash# mult(float b, in Comb_#hash# a)
{
    Comb_#hash# ret;
    ret.data = a.data * b;
    return ret;
}


void amplify(inout Comb_#hash# a, in Comb_#hash# b )
{
    a.data *= b.data;
}

void amplify(inout Comb_#hash# a, float b )
{
    a.data *= b;
}

Comb_#hash# div(in Comb_#hash# a, float b)
{
    Comb_#hash# ret;
    ret.data = a.data / b;
    return ret;
}

void diminish(inout Comb_#hash# a, float b )
{
    a.data /= b;
}

Comb_#hash# neg(in Comb_#hash# a)
{
    Comb_#hash# ret;
    ret.data =  -a.data;
    return ret; 
}

void from_rgb(out Comb_#hash# a, in vec3 rgb)
{
    a.data = rgb;
}

vec3 to_rgb(in Comb_#hash# a)
{
    return a.data;
}

void from_xyz(out Comb_#hash# a, in vec3 xyz)
{
    a.data = xyz2rgb(xyz);
}

vec3 to_xyz(in Comb_#hash# a)
{
    return rgb2xyz(a.data);
}

float max_component_value(in Comb_#hash# a)
{
    return max(max(a.data.x, a.data.y), a.data.z);
}

#define Spectrum Comb_#hash#

''')
Example #29
0
import VkInline as vki
import numpy as np
from PIL import Image

image_in = np.array(Image.open('fei.png').convert('RGBA'))

VK_FORMAT_R8G8B8A8_SRGB = 43

width = image_in.shape[1]
height = image_in.shape[0]

tex2d = vki.Texture2D(width, height, VK_FORMAT_R8G8B8A8_SRGB)
tex2d.upload(image_in)

colorBuf = vki.Texture2D(width, height, VK_FORMAT_R8G8B8A8_SRGB)

positions = np.array([[0.0, -0.5, 0.5], [0.5, 0.5, 0.5], [-0.5, 0.5, 0.5]],
                     dtype=np.float32)
gpuPos = vki.device_vector_from_numpy(positions)

colors = np.array([[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]],
                  dtype=np.float32)
gpuColors = vki.device_vector_from_numpy(colors)

rp = vki.Rasterizer(['pos', 'col'])

rp.add_draw_call(
    vki.DrawCall(
        '''
layout (location = 0) out vec2 vUV;
void main() 
Example #30
0
vki.Add_Built_In_Header(
    'rand_xorwow.shinc', '''
struct V5
{
    uint v0;
    uint v1;
    uint v2;
    uint v3;
    uint v4;
};

struct RNGState 
{
    V5 v;
    uint d;
};

uint rand(inout RNGState state)
{
    uint t;
    t = (state.v.v0 ^ (state.v.v0 >> 2));
    state.v.v0 = state.v.v1;
    state.v.v1 = state.v.v2;
    state.v.v2 = state.v.v3;
    state.v.v3 = state.v.v4;
    state.v.v4 = (state.v.v4 ^ (state.v.v4 << 4)) ^ (t ^ (t << 1));
    state.d += 362437;
    return state.v.v4 + state.d;
}

float rand01(inout RNGState state)
{
    uint64_t urand = rand(state);
    return float(urand) / float(1UL << 32);
}

vec3 rand_in_unit_sphere(inout RNGState rstate)
{
    vec3 ret;
    do{
        ret = vec3(rand01(rstate)*2.0 - 1.0, rand01(rstate)*2.0 - 1.0, rand01(rstate)*2.0 - 1.0);
    } while (length(ret) > 1.0);
    return ret;
}

vec2 rand_in_unit_disk(inout RNGState rstate)
{
    vec2 ret;
    do {
        ret = vec2(rand01(rstate)*2.0 - 1.0, rand01(rstate)*2.0 - 1.0);
    } while (length(ret) > 1.0);
    return ret;
}

vec3 rand_on_unit_sphere(inout RNGState rstate)
{
    float theta = rand01(rstate) * radians(360.0);
    float z = rand01(rstate)*2.0 - 1.0;
    float r = 1.0 - z*z;
    if (r<0.0) r = 0.0;
    r = sqrt(r);
    vec3 ret;
    ret.z = z;
    ret.x = r*cos(theta);
    ret.y = r*sin(theta);
    return ret;
}

vec2 rand_on_unit_circle(inout RNGState rstate)
{
    float theta = rand01(rstate) * radians(360.0);
    vec2 ret;
    ret.x = cos(theta);
    ret.y = sin(theta);
    return ret;
}
''')