@@ -31,21 +31,16 @@ curandState *d_states;
3131Camera *d_camera;
3232HitableList *d_world;
3333glm::vec3 *d_image;
34-
35- struct DeviceImage {
36- uint8_t *image;
37- int height, width, components;
38- };
39-
40- DeviceImage d_earthmap;
34+ uint8_t *d_tex_image;
35+ cudaTextureObject_t tex;
4136
4237using glm::pi;
4338using glm::rotateX;
4439using glm::rotateY;
4540using glm::vec3;
4641
4742__global__ void InitWorld (HitableList *world, Camera *camera,
48- DeviceImage earthmap ) {
43+ cudaTextureObject_t tex ) {
4944 new (world) HitableList ();
5045 new (camera) Camera (vec3 (278 , 278 , -800 ), vec3 (278 , 278 , 0 ), vec3 (0 , 1 , 0 ),
5146 pi<double >() * 2 / 9 , double (WIDTH) / HEIGHT);
@@ -56,8 +51,7 @@ __global__ void InitWorld(HitableList *world, Camera *camera,
5651
5752 auto light_material_ptr =
5853 new DiffuseLight (new ConstantTexture (vec3 (1 , 1 , 1 )));
59- auto earthmap_texture_ptr = new ImageTexture (
60- earthmap.height , earthmap.width , earthmap.components , earthmap.image );
54+ auto earthmap_texture_ptr = new ImageTexture (tex);
6155 auto earthmap_material_ptr = new Lambertian (earthmap_texture_ptr);
6256 auto sky = new Sky ();
6357
@@ -79,22 +73,27 @@ __global__ void InitWorld(HitableList *world, Camera *camera,
7973 world->Append (new Sphere (vec3 (278 , 278 , 0 ), 100 , earthmap_material_ptr));
8074}
8175
82- void InitImageTextures (DeviceImage *earthmap) {
83- auto data = stbi_load (" resources/earthmap.jpg" , &earthmap->width ,
84- &earthmap->height , &earthmap->components , 0 );
85- int size = earthmap->height * earthmap->width * earthmap->components ;
86- cudaMalloc (&earthmap->image , size);
87- cudaMemcpy (earthmap->image , data, size, cudaMemcpyHostToDevice);
76+ cudaTextureObject_t InitImageTextures () {
77+ int width, height, channels;
78+ uint64_t pitch_in_bytes;
79+ auto data =
80+ stbi_load (" resources/earthmap.jpg" , &width, &height, &channels, 4 );
81+ cudaMallocPitch (&d_tex_image, &pitch_in_bytes, 4 * width, height);
82+ cudaMemcpy2D (d_tex_image, pitch_in_bytes, data, 4 * width, 4 * width, height,
83+ cudaMemcpyHostToDevice);
84+ auto tex = ImageTexture::CreateCudaTextureObj (d_tex_image, height, width,
85+ pitch_in_bytes);
8886 auto err = cudaGetLastError ();
8987 CHECK (err == cudaSuccess) << cudaGetErrorString (err);
88+ return tex;
9089}
9190
9291int main () {
9392 Main (
9493 &d_states, &d_camera, &d_world, &d_image,
9594 [](HitableList *world, Camera *camera) {
96- InitImageTextures (&d_earthmap );
97- InitWorld<<<1 , 1 >>> (world, camera, d_earthmap );
95+ auto tex = InitImageTextures ();
96+ InitWorld<<<1 , 1 >>> (world, camera, tex );
9897 },
9998 HEIGHT, WIDTH, 200 );
10099 return 0 ;
0 commit comments