实现波纹效果

cuda用来算像素颜色+openGL用来显示(mdzz)
波纹的颜色函数直接用的书上建议不要花太多时间去理解的函数
放代码

#include "cuda_runtime.h"
#include "device_launch_parameters.h"

#include 
#include 

#include "myGL.h"
using namespace std;
const GLuint WIDTH = 1920;
const GLuint HEIGHT = 1080;
void HANDLE_ERROR(cudaError_t status);
void drawPixels(unsigned char *res, int width, int height, double time);
int main() {
    unsigned char *p = new unsigned char[WIDTH*HEIGHT * 4];

    HANDLE_ERROR(cudaSetDevice(0));

    GLFWwindow *window = glfwStart(WIDTH, HEIGHT, "wave");
    Shader shader;
    shader.mkShader("shader.vert", NULL, "shader.frag");
    GLuint vao = mkVAO();

    double startTime = glfwGetTime();
    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glClearColor(0,0,0,0);
        glClear(GL_COLOR_BUFFER_BIT);

        double pastTime = glfwGetTime() - startTime;
        drawPixels(p, WIDTH, HEIGHT, pastTime);

        GLuint tex = mkTex(GL_RGBA, WIDTH, HEIGHT, p); 
        shader.Use();
        glBindTexture(GL_TEXTURE_2D, tex);
        glBindVertexArray(vao);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glDeleteTextures(1, &tex);
        glfwSwapBuffers(window);
        GLuint err = glGetError();
        if (err)
            cout << "Error: " << err << endl;
    }
    delete[]p;
    glfwTerminate();
    HANDLE_ERROR(cudaDeviceReset());
    return 0;
}

void HANDLE_ERROR(cudaError_t status) {
    if (status != cudaSuccess) {
        fprintf(stderr, "Error~\n");
        exit(0);
    }
}
__global__ void kernel(unsigned char *res, int width, int height, float time) {
    int x = blockIdx.x * blockDim.x + threadIdx.x;
    int y = blockIdx.y * blockDim.y + threadIdx.y;
    int offset = y * width + x;
    if (offset < width * height) {
        offset *= 4;
        float fx = x - width / 2;
        float fy = y - height / 2;
        float d = sqrtf(fx*fx+fy*fy);
        res[offset] = res[offset + 1] = res[offset + 2] = 
            (unsigned char)(128.0f+127.0f*cos(d/10.0f - time*100.0f/7.0f)/(d/10.0f+1.0f));
        res[offset + 3] = 0;
    }
}
void drawPixels(unsigned char *res, int width, int height, double time) {
    unsigned char *p = 0;
    HANDLE_ERROR(cudaMalloc((void**)&p, width*height*4));

    dim3 blockDim(32,32);
    dim3 gridDim((width + 31) / 32, (height + 31) / 32);
    kernel << > > (p, width, height, (float)time);

    cudaError_t status; 
    status = cudaGetLastError();
    if (status != cudaSuccess) {
        fprintf(stderr, "Build kernel failed.\n");
        goto Error;
    }
    status = cudaDeviceSynchronize();
    if (status != cudaSuccess) {
        fprintf(stderr, "kernel run failed.\n");
        goto Error;
    }
    status = cudaMemcpy(res, p, width*height*4, cudaMemcpyDeviceToHost);
    if (status != cudaSuccess) {
        fprintf(stderr, "Memcpy failed.\n");
        goto Error;
    }

Error:

    cudaFree(p);
    return ;
}

openGL里边比较冗长的代码块 放进了myGL.h里边
效果图:

(可见这个函数效果并不好

你可能感兴趣的:(cuda,openGL,cuda,opengl)