示例#1
0
void CL::loadData(std::vector<Vec4> pos, std::vector<Vec4> vel, std::vector<Vec4> col)
{
    //store the number of particles and the size in bytes of our arrays
    num = pos.size();
    array_size = num * sizeof(Vec4);
    //create VBOs (defined in util.cpp)
    p_vbo = createVBO(&pos[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
    c_vbo = createVBO(&col[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);

    //make sure OpenGL is finished before we proceed
    glFinish();
    printf("gl interop!\n");
    // create OpenCL buffer from GL VBO
    cl_vbos.push_back(cl::BufferGL(context, CL_MEM_READ_WRITE, p_vbo, &err));
    //printf("v_vbo: %s\n", oclErrorString(err));
    cl_vbos.push_back(cl::BufferGL(context, CL_MEM_READ_WRITE, c_vbo, &err));
    //we don't need to push any data here because it's already in the VBO


    //create the OpenCL only arrays
    cl_velocities = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err);
    cl_pos_gen = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err);
    cl_vel_gen = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err);
 
    printf("Pushing data to the GPU\n");
    //push our CPU arrays to the GPU
    //data is tightly packed in std::vector starting with the adress of the first element
    err = queue.enqueueWriteBuffer(cl_velocities, CL_TRUE, 0, array_size, &vel[0], NULL, &event);
    err = queue.enqueueWriteBuffer(cl_pos_gen, CL_TRUE, 0, array_size, &pos[0], NULL, &event);
    err = queue.enqueueWriteBuffer(cl_vel_gen, CL_TRUE, 0, array_size, &vel[0], NULL, &event);
    queue.finish();
}
bool EndPatchProgram::init()
{
	if( ! ShaderProgram::init( true ) ||  ! loadShaders() )
	{
		return false;
	}

	createVBO( "in_position", ShaderProgram::gl_Vertex );
	createVBO( "in_vertexID", ShaderProgram::gl_MultiTexCoord7 );

	if( ! finalizeProgram() )
	{
		return false;
	}

	use();

	ShaderProgram::createSBO( "valenceBuffer" );
	ShaderProgram::createSBO( "neighborIndexBuffer" );
	ShaderProgram::createSBO( "vertexData" );

	// tell GL to only draw onto a pixel if the shape is closer to the viewer
	glEnable( GL_DEPTH_TEST ); // enable depth-testing
	glDepthFunc( GL_LESS ); // depth-testing interprets a smaller value as "closer"

	return true;
}
void ParticleSystem::_initialize(int numParticles){
    assert(!m_bInitialized);
    m_numParticles = numParticles;

    //Allocate host storage
    m_hPos          = (float *)malloc(m_numParticles * 4 * sizeof(float));
    m_hVel          = (float *)malloc(m_numParticles * 4 * sizeof(float));
    m_hReorderedPos = (float *)malloc(m_numParticles * 4 * sizeof(float));
    m_hReorderedVel = (float *)malloc(m_numParticles * 4 * sizeof(float));
    m_hHash         = (uint  *)malloc(m_numParticles * sizeof(uint));
    m_hIndex        = (uint  *)malloc(m_numParticles * sizeof(uint));
    m_hCellStart    = (uint  *)malloc(m_numGridCells * sizeof(uint));
    m_hCellEnd      = (uint  *)malloc(m_numGridCells * sizeof(uint));

    memset(m_hPos, 0, m_numParticles * 4 * sizeof(float));
    memset(m_hVel, 0, m_numParticles * 4 * sizeof(float));
    memset(m_hCellStart, 0, m_numGridCells * sizeof(uint));
    memset(m_hCellEnd,   0, m_numGridCells * sizeof(uint));

    //Allocate GPU data
    shrLog("Allocating GPU Data buffers...\n\n");
    allocateArray(&m_dPos,          m_numParticles * 4 * sizeof(float));
    allocateArray(&m_dVel,          m_numParticles * 4 * sizeof(float));
    allocateArray(&m_dReorderedPos, m_numParticles * 4 * sizeof(float));
    allocateArray(&m_dReorderedVel, m_numParticles * 4 * sizeof(float));
    allocateArray(&m_dHash,         m_numParticles * sizeof(uint));
    allocateArray(&m_dIndex,        m_numParticles * sizeof(uint));
    allocateArray(&m_dCellStart,    m_numGridCells * sizeof(uint));
    allocateArray(&m_dCellEnd,      m_numGridCells * sizeof(uint));

    if (!m_bQATest)
    {
        //Allocate VBO storage
        m_posVbo   = createVBO(m_numParticles * 4 * sizeof(float));
        m_colorVBO = createVBO(m_numParticles * 4 * sizeof(float));

        //Fill color buffer
        glBindBufferARB(GL_ARRAY_BUFFER, m_colorVBO);
        float *data = (float *)glMapBufferARB(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
            float *ptr = data;
            for(uint i = 0; i < m_numParticles; i++){
                float t = (float)i / (float) m_numParticles;
                #if 0
                    *ptr++ = rand() / (float) RAND_MAX;
                    *ptr++ = rand() / (float) RAND_MAX;
                    *ptr++ = rand() / (float) RAND_MAX;
                #else
                    colorRamp(t, ptr);
                    ptr += 3;
                #endif
                *ptr++ = 1.0f;
            }
        glUnmapBufferARB(GL_ARRAY_BUFFER);
    }

    setParameters(&m_params);
    setParametersHost(&m_params);
    m_bInitialized = true;
}
示例#4
0
void genMeshGridObject(MeshGridObject *meshGridObj)
{
	createMeshGrid(&meshGridObj->u, &meshGridObj->v, &meshGridObj->uSize, &meshGridObj->vSize, 100, 100);
	createMeshGridIndices(&meshGridObj->indices, &meshGridObj->indicesLen, &meshGridObj->indicesSize, 100, 100);
	createVBO(GL_ARRAY_BUFFER, &meshGridObj->uID,meshGridObj->uSize,meshGridObj->u);
	printf("uID: %i\n",meshGridObj->uID);	
	createVBO(GL_ARRAY_BUFFER, &meshGridObj->vID,meshGridObj->vSize,meshGridObj->v);
	printf("vID: %i\n",meshGridObj->vID);	
	createVBO(GL_ELEMENT_ARRAY_BUFFER, &meshGridObj->iboID, meshGridObj->indicesSize, (GLfloat*)meshGridObj->indices);
	printf("iboID: %i\n",meshGridObj->iboID);	
}
示例#5
0
void WaterPlaneCUDA::initBuffer()
{
	//Start und Endkoordinaten für x-Richtung
	float startX = this->uLeft.x;
	float endX = this->lRight.x;

	//Start und Endkoordinaten für x-Richtung
	float startY = this->uLeft.z;
	float endY = this->lRight.z;

	cpu_newVertices = new float3[pointsX*pointsY];
	cpu_oldVertices = new float3[pointsX*pointsY];
	cpu_normals = new float3[pointsX*pointsY];
	unsigned int count = 0;
	for (float px = startX ; px< endX ; px+=stepSize){
		for (float py = startY; py < endY; py+=stepSize){
			cpu_newVertices[count].x = px;
			cpu_newVertices[count].y = 0;
			cpu_newVertices[count].z = py;
			cpu_oldVertices[count].x = px;
			cpu_oldVertices[count].y = 0;
			cpu_oldVertices[count].z = py;
			cpu_normals[count].x = 0;
			cpu_normals[count].y = 1;
			cpu_normals[count].z = 0;
			count++;
		}
	}


	createVBO(&newVertexBuffer, pointsX*pointsY*sizeof(float3));
	cutilSafeCall(cudaGraphicsGLRegisterBuffer(&cuda_newVertex_resource, newVertexBuffer, cudaGraphicsMapFlagsNone));
	createVBO(&oldVertexBuffer, pointsX*pointsY*sizeof(float3));
	cutilSafeCall(cudaGraphicsGLRegisterBuffer(&cuda_oldVertex_resource, oldVertexBuffer, cudaGraphicsMapFlagsNone));
	createVBO(&normalBuffer, pointsX*pointsY*sizeof(float3));
	cutilSafeCall(cudaGraphicsGLRegisterBuffer(&cuda_normalsVB_resource, normalBuffer, cudaGraphicsMapFlagsNone));
	createMeshIndexBuffer(&indexVertexBuffer, pointsX, pointsY);
	createMeshIndexBuffer(&indexNormalBuffer, pointsX, pointsY);

	glBindBuffer(GL_ARRAY_BUFFER, *&newVertexBuffer);
	glBufferData( GL_ARRAY_BUFFER, pointsY*pointsX*sizeof(float3), cpu_newVertices, GL_DYNAMIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, *&oldVertexBuffer);
	glBufferData( GL_ARRAY_BUFFER, pointsY*pointsX*sizeof(float3), cpu_oldVertices, GL_DYNAMIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, *&normalBuffer);
	glBufferData( GL_ARRAY_BUFFER, pointsY*pointsX*sizeof(float3), cpu_normals, GL_DYNAMIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, 0);
}
示例#6
0
/* Build VBOs for all geosets. */
void ModelGL::buildVBOs () {

  // Reserve memory and loop over all geosets.
  _VBOs = (GeosetVBO*) calloc (_nrGeosets, sizeof (GeosetVBO));
  for (int g = 0; g < _nrGeosets; g ++) {
    _VBOs[g].length = _geosets[g].nrG * 3;                     // Set vertex count.
    if (_texture != NULL) _VBOs[g].textureID = _texture->id(); // Set texture ID.

    // Build temporary arrays based on geometry definitions.
    int vsize = _geosets[g].nrG * 3 * 3; //| 3 vertices per geometry
    int nsize = _geosets[g].nrG * 3 * 3; //| with 3 points, 3 nv-points 
    int tsize = _geosets[g].nrG * 3 * 2; //| and 2 texture coords each.
    float* vdata = new float [vsize];
    float* ndata = new float [nsize];
    float* tdata = new float [tsize];

    // Extract data for each geoset.
    int vIdx, nIdx, tIdx;                        // Storage for index shortening.
    for (int i = 0; i < _geosets[g].nrG; i ++) { // i: Loop over geometries.
      for (int c = 0; c < 3; c ++) {             // c: Loop over geom indices.
        vIdx = _geosets[g].geometries[i].vIdx[c];
        nIdx = _geosets[g].geometries[i].nIdx[c];
        tIdx = _geosets[g].geometries[i].tIdx[c];

        vdata [i*9 + c*3 + 0] = _geosets[g].vertices[vIdx].x;  // Outer offset: 9 (3*inner).
        vdata [i*9 + c*3 + 1] = _geosets[g].vertices[vIdx].y;  // Inner offset: 3 (3 runs each).
        vdata [i*9 + c*3 + 2] = _geosets[g].vertices[vIdx].z;
        
        ndata [i*9 + c*3 + 0] = _geosets[g].normals[nIdx].x;
        ndata [i*9 + c*3 + 1] = _geosets[g].normals[nIdx].y;
        ndata [i*9 + c*3 + 2] = _geosets[g].normals[nIdx].z;
        
        tdata [i*6 + c*2 + 0] = _geosets[g].textures[tIdx].u;  // OO: 6 (2*3)
        tdata [i*6 + c*2 + 1] = _geosets[g].textures[tIdx].v;   
      }
    }

    // Create VBOs.
    _VBOs[g].vVBO = createVBO (vdata, vsize * sizeof(float), GL_ARRAY_BUFFER, GL_STATIC_DRAW);
    _VBOs[g].nVBO = createVBO (ndata, nsize * sizeof(float), GL_ARRAY_BUFFER, GL_STATIC_DRAW);
    _VBOs[g].tVBO = createVBO (tdata, tsize * sizeof(float), GL_ARRAY_BUFFER, GL_STATIC_DRAW);

    // Free temporary data.
    delete [] vdata;
    delete [] ndata;
    delete [] tdata;
  }
}
示例#7
0
	void RotatingCamera::load(){
		//blakommentar
		foreground_sh.load("shaders/lustigiSzene.vert","shaders/lustigiSzene.frag");
		foreground_sh.use();

		// Set model matrix
		GLfloat model_mat[16] = {
			 1.000000f,  0.000000f,  0.000000f, 0.000000f,
			 0.000000f,  1.000000f,  0.000000f, 0.000000f,
			 0.000000f,  0.000000f,  1.000000f, 0.000000f,
			 0.000000f,  0.000000f,  0.000000f, 1.0000000f
		};

		GLint location = glGetUniformLocation(foreground_sh.getProgramId(), "Model_mat");
		glUniformMatrix4fv(location, 1, false, model_mat);

		// Set projection*view Matrix
//		GLfloat projview_mat[16] = {
//			2.747478f, 0.000000f,  0.000000f,  0.000000f,
//			0.000000f, 2.457419f,  0.546594f,  0.447214f,
//			0.000000f, 1.228709f, -1.093189f, -0.894427f,
//			0.000000f, 0.000000f,  1.877236f,  3.354102f
//		};


		vmath::mat4 projview_mat = getProjectionViewMatrix(azimuth, polar, distance);
		location = glGetUniformLocation(foreground_sh.getProgramId(), "ProjectView_mat");
		glUniformMatrix4fv(location, 1, false, (float*)(projview_mat));

		createVBO();
	}
 StreamlineEffect::StreamlineEffect(ShaderLibrary* lib, GLuint width, GLuint height, unsigned int maxLength
                                    , unsigned int num, vector<unsigned int>& indices, CL* cli, RTPSSettings* settings):
                                     ParticleEffect( lib, width, height)
 {
     m_maxSLLength=maxLength;
     m_numSL = num;
     m_curSLIndex = 1;
     vector<float4> f4vec((m_maxSLLength+1)*m_numSL);
     std::fill(f4vec.begin(), f4vec.end(), float4(0.0f, 0.0f, 0.0f, 0.0f));
     m_streamLineCP = createVBO(&f4vec[0], f4vec.size()*sizeof(float4), GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
     m_streamLineColor = createVBO(&f4vec[0], f4vec.size()*sizeof(float4), GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
     m_clStreamLineCP=Buffer<float4>(cli,m_streamLineCP);
     m_clStreamLineColor=Buffer<float4>(cli,m_streamLineColor);
     m_clSampleIndices=Buffer<unsigned int>(cli,indices);
     sample = Sample(settings->GetSettingAs<string>("rtps_path") + "/" + std::string(COMMON_CL_SOURCE_DIR), cli);
 }
示例#9
0
文件: SGCTPlane.cpp 项目: Risca/sgct
/*!
	This constructor requires a valid openGL contex 
*/
sgct_utils::SGCTPlane::SGCTPlane(float width, float height)
{
	//init
	mVBO = GL_FALSE;
	mVAO = GL_FALSE;
	mVerts = NULL;

	mInternalDrawFn = &SGCTPlane::drawVBO;

	mVerts = new sgct_helpers::SGCTVertexData[4];
	memset(mVerts, 0, 4 * sizeof(sgct_helpers::SGCTVertexData));

	//populate the array
	mVerts[0].set(0.0f, 0.0f, 0.0f, 0.0f, 1.0f, -width / 2.0f, -height / 2.0f, 0.0f);
	mVerts[1].set(1.0f, 0.0f, 0.0f, 0.0f, 1.0f, width / 2.0f, -height / 2.0f, 0.0f);
	mVerts[2].set(0.0f, 1.0f, 0.0f, 0.0f, 1.0f, -width / 2.0f, height / 2.0f, 0.0f);
	mVerts[3].set(1.0f, 1.0f, 0.0f, 0.0f, 1.0f, width / 2.0f, height / 2.0f, 0.0f);
		
	createVBO();

	if( !sgct::Engine::checkForOGLErrors() ) //if error occured
	{
		sgct::MessageHandler::instance()->print(sgct::MessageHandler::NOTIFY_ERROR, "SGCT Utils: Plane creation error!\n");
		void cleanup();
	}

	//free data
	if( mVerts != NULL )
	{
		delete [] mVerts;
		mVerts = NULL;
	}
}
示例#10
0
////////////////////////////////////////////////////////////////////////////////
//! Run OpenGL
////////////////////////////////////////////////////////////////////////////////
bool runDisplay(int argc, char **argv)
{
    // Create the CUTIL timer
    sdkCreateTimer(&timer);

    // First initialize OpenGL context, so we can properly set the GL for CUDA.
    // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
    if (false == initGL(&argc, argv))
    {
        return false;
    }

    // register callbacks
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutIdleFunc(idle);

    // create VBO
    createVBO(&vbo, &cuda_vbo_resource, cudaGraphicsMapFlagsWriteDiscard);

    // start rendering mainloop
    glutMainLoop();

    // run the cuda part
    //refreshData(&cuda_vbo_resource);

    atexit(cleanup);
   
    return true;
}
示例#11
0
Sphere::Sphere(Material* mat, Program* prog, vec3 pos, vec3 scale):
	Object(mat, prog, pos, scale) {

	vLoc = glGetAttribLocation(prog->getID(), "in_position");
	nLoc = glGetAttribLocation(prog->getID(), "in_normal");
	populate();
	createVBO();
}
void btParticlesDynamicsWorld::postInitDeviceData()
{
	m_hashSize = getMaxPowOf2(m_numParticles);
	createVBO();
	allocateBuffers();
	adjustGrid();
	grabSimulationData();
}
//----------------------------------------------------------------------
int main(int argc, char** argv)
{
    printf("Hello\n");
    //Setup our GLUT window and OpenGL related things
    //glut callback functions are setup here too
    init_gl(argc, argv);

    //initialize our particle system with positions, velocities and color
    int num = NUM_PARTICLES;
    
	
    //create VBOs 
    
    //fill our vectors with initial data
    for(int i = 0; i < num; i++)
    {
        //distribute the particles in a random circle around z axis
        float rad = rand_float(.2, .5);
        float x = rad*sin(2*3.14 * i/num);
        float z = 0.0f;// -.1 + .2f * i/num;
        float y = rad*cos(2*3.14 * i/num);
        pos[i] = Vec4(x, y, z, 1.0f);
        pos_gen[i]=pos[i];
        //give some initial velocity 
        //float xr = rand_float(-.1, .1);
        //float yr = rand_float(1.f, 3.f);
        //the life is the lifetime of the particle: 1 = alive 0 = dead
        //as you will see in part2.cl we reset the particle when it dies
        float life_r = rand_float(0.f, 1.f);
        vel[i] = Vec4(0.0, 0.0, 3.0f, life_r);
		vel_gen[i]=vel[i];

        //just make them red and full alpha
        color[i] = Vec4(1.0f, 0.0f,0.0f, 1.0f);
		
    }
	p_vbo = createVBO(&pos[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
    c_vbo = createVBO(&color[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);

    
    //this starts the GLUT program, from here on out everything we want
    //to do needs to be done in glut callback functions
    glutMainLoop();

}
示例#14
0
////////////////////////////////////////////////////////////////////////////////
//! Run a simple test for CUDA
////////////////////////////////////////////////////////////////////////////////
CUTBoolean runTest(int argc, char** argv)
{
    if (!cutCheckCmdLineFlag(argc, (const char **)argv, "noqatest") ||
		cutCheckCmdLineFlag(argc, (const char **)argv, "noprompt")) 
	{
        g_bQAReadback = true;
        fpsLimit = frameCheckNumber;
    }

    // First initialize OpenGL context, so we can properly set the GL for CUDA.
    // This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
    if (CUTFalse == initGL(argc, argv)) {
        return CUTFalse;
    }

	// use command-line specified CUDA device, otherwise use device with highest Gflops/s
    if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") )
        cutilGLDeviceInit(argc, argv);
    else {
        cudaGLSetGLDevice( cutGetMaxGflopsDeviceId() );
    }

    // Create the CUTIL timer
    cutilCheckError( cutCreateTimer( &timer));

    // register callbacks
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);

    if (g_bQAReadback) {
        g_CheckRender = new CheckBackBuffer(window_width, window_height, 4);
        g_CheckRender->setPixelFormat(GL_RGBA);
        g_CheckRender->setExecPath(argv[0]);
        g_CheckRender->EnableQAReadback(true);
    }

    // create VBO
    createVBO(&vbo);

    // run the cuda part
    runCuda(vbo);

    // check result of Cuda step
    checkResultCuda(argc, argv, vbo);

    atexit(cleanup);

    // start rendering mainloop
    glutMainLoop();

    cudaThreadExit();

	return CUTTrue;
}
示例#15
0
NiceGrid::NiceGrid(GLfloat size, GLfloat rep)
: m_size(size),
  m_rep(rep),
  m_backFaceAlpha(0.2),
  m_ambient(0.12f, 0.12f, 0.1f),
  m_diffuse(1.0f, 1.0f, 0.9f),
  m_position(0.0f, 0.0f, 0.0f)
{
    createVBO();
}
示例#16
0
/////////////////////////////////////////////////////////
// render
//
/////////////////////////////////////////////////////////
void multimodel :: render(GemState *state)
{
  if(!m_loader) {
    return;
  }

  if ( !m_position.vbo || !m_texture.vbo || !m_color.vbo || !m_normal.vbo
       || m_size_change_flag ) {
    createVBO();
    m_size_change_flag = false;
  }
  getVBOarray();

  std::vector<unsigned int> sizeList;

  if(m_position.render()) {
    glVertexPointer(m_position.dimen, GL_FLOAT, 0, 0);
    glEnableClientState(GL_VERTEX_ARRAY);
    sizeList.push_back(m_position.size);
  }
  if(m_texture.render()) {
    glTexCoordPointer(m_texture.dimen, GL_FLOAT, 0, 0);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    sizeList.push_back(m_texture.size);
  }
  if(m_color.render()) {
    glColorPointer(m_color.dimen, GL_FLOAT, 0, 0);
    glEnableClientState(GL_COLOR_ARRAY);
    sizeList.push_back(m_color.size);
  }
  if(m_normal.render()) {
    glNormalPointer(GL_FLOAT, 0, 0);
    glEnableClientState(GL_NORMAL_ARRAY);
    sizeList.push_back(m_normal.size);
  }

  if ( sizeList.size() > 0 ) {
    unsigned int npoints = *std::min_element(sizeList.begin(),sizeList.end());
    glDrawArrays(m_drawType, 0, npoints);
  }

  if ( m_position.enabled ) {
    glDisableClientState(GL_VERTEX_ARRAY);
  }
  if ( m_color.enabled    ) {
    glDisableClientState(GL_COLOR_ARRAY);
  }
  if ( m_texture.enabled  ) {
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
  }
  if ( m_normal.enabled   ) {
    glDisableClientState(GL_NORMAL_ARRAY);
  }
}
示例#17
0
RectMesh::RectMesh(Material* mat, Program* prog, vec3 pos, vec3 scale,
		vec3* points, unsigned width, unsigned length):
	Object(mat, prog, pos, scale), points(points), width(width), length(length) {

	vertexCount = width * length;
	indicesCount = (length * 2) * (width - 1);

	vLoc = glGetAttribLocation(prog->getID(), "in_position");
	nLoc = glGetAttribLocation(prog->getID(), "in_normal");
	populate();
	createVBO();
}
示例#18
0
文件: Mesh.cpp 项目: dtorban/VRBase
bool Mesh::updateContextItem(bool changed) {
	if (_texture != NULL)
		_texture->updateContext();

	if (changed)
	{
		deleteVBO();
		createVBO();
	}

	return true;
}
示例#19
0
ParticleRenderer::ParticleRenderer(bool isGL)
    : m_vbo(0)
    , m_frameId(0)
    , m_eboArray(NULL)
    , m_eboCount(2)
    , m_isGL(isGL)
{
    m_particleSystem = new ParticleSystem();

    createShaders();
    createVBO();
    createEBOs();
}
示例#20
0
文件: galaxy.cpp 项目: vbud/galaxy
void CL::loadData(std::vector<Vec4> pos, std::vector<Vec4> vel, std::vector<Vec4> col)
{
    static int do_init = 1;

    num = pos.size();
    array_size = num * sizeof(Vec4);

    if (do_init)
    {   do_init = 0;
        // This is the first time we are loading particle data.
        // VBOs and OpenCL arrays must be initiialized

        // Create Position and Color VBOs for GL & CL
        p_vbo = createVBO(&pos[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
        c_vbo = createVBO(&col[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
        glFinish();

        // Create OpenCL buffer from GL VBO
        cl_vbos.push_back(cl::BufferGL(context, CL_MEM_READ_WRITE, p_vbo, &err));
        cl_vbos.push_back(cl::BufferGL(context, CL_MEM_READ_WRITE, c_vbo, &err));

        //Create the OpenCL only arrays
        cl_velocities = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err);
        cl_pos_gen = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err);
        cl_vel_gen = cl::Buffer(context, CL_MEM_WRITE_ONLY, array_size, NULL, &err);
    } else {
        // Reloading the position and color VBOs with new values.
        reload_buffer(p_vbo, &pos[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
        reload_buffer(c_vbo, &col[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
    }

    // Push data to the GPU
    printf("Pushing data to the GPU\n");
    err = queue.enqueueWriteBuffer(cl_velocities, CL_TRUE, 0, array_size, &vel[0], NULL, &event);
    err = queue.enqueueWriteBuffer(cl_pos_gen, CL_TRUE, 0, array_size, &pos[0], NULL, &event);
    err = queue.enqueueWriteBuffer(cl_vel_gen, CL_TRUE, 0, array_size, &vel[0], NULL, &event);
    queue.finish();
}
示例#21
0
void GameWindow::createVBOs() {
    for(short c = 0; c < 100; c++) {
        glGenBuffers(100, VBO[c]);
    }

    for(short c = 0; c < 100; c++) {
        for(short i = 0; i < 100; i++) {
            int id[2] = {c, i};
            float x = c/100.0f*2.0f;
            float y = -i/100.0f*2.0f;
            createVBO(id, {x-1, y+1, 0.0f});
        }
    }
}
示例#22
0
void MD::loadData(std::vector<cl_float4> pos, std::vector<cl_float4> force,
                  std::vector<cl_float4> vel, std::vector<cl_float4> col) {
  // Store the number of particles and the size in bytes of our arrays.
  num = pos.size();
  array_size = num * sizeof(cl_float4);
  // Create VBOs (defined in util.cpp).
  pos_vbo = createVBO(&pos[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
  col_vbo = createVBO(&col[0], array_size, GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);

  // Make sure OpenGL is finished before we proceed.
  glFinish();
  printf("Set up GL sharing.\n");
  try {
    // Create OpenCL buffer from GL VBO.
    // We don't need to push any data here because it's already in the VBO.
    cl_vbos.push_back(cl::BufferGL(context, CL_MEM_READ_WRITE, pos_vbo, &err));
    cl_vbos.push_back(cl::BufferGL(context, CL_MEM_READ_WRITE, col_vbo, &err));
  }
  catch (cl::Error er) {
    printf("ERROR: %s(%s)\n", er.what(), oclErrorString(er.err()));
    exit(EXIT_FAILURE);
  }

  // Create the OpenCL only arrays.
  cl_forces = cl::Buffer(context, CL_MEM_READ_WRITE, array_size, NULL, &err);
  cl_vel = cl::Buffer(context, CL_MEM_READ_WRITE, array_size, NULL, &err);

  printf("Pushing data to the GPU\n");
  // Push our CPU arrays to the GPU.
  // Data is tightly packed in std::vector starting with the adress of the first
  // element.
  err = queue.enqueueWriteBuffer(cl_forces, CL_TRUE, 0, array_size, &force[0],
                                 NULL, &event);
  err = queue.enqueueWriteBuffer(cl_vel, CL_TRUE, 0, array_size, &vel[0],
                                 NULL, &event);
  queue.finish();
}
示例#23
0
int main(int argc, char** argv)
{

	initGL(argc, argv);

	initData(INPUTFILENAME);

	//Create VBO
	createVBO();
	initializeVBOs();

	glutMainLoop();

	//Free CUDA variables
	return 0;
}
示例#24
0
void initObj(RenderObject *r)
{	
	if (r->vertices!=NULL)	
	{
		createVBO(GL_ARRAY_BUFFER, &r->vboID,r->verticesSize,r->vertices);
		printf("vboID: %i\n",r->vboID);
		printf("Size of Vertices: %d\n",r->verticesSize);
	}

	if (r->u!=NULL)
	{
		createVBO(GL_ARRAY_BUFFER, &r->uID,r->uSize,r->u);
		printf("uID: %i\n",r->uID);
		printf("Size of u: %d\n",r->uSize);		
	}

	if (r->v!=NULL)
	{
		createVBO(GL_ARRAY_BUFFER, &r->vID,r->vSize,r->v);
		printf("vID: %i\n",r->vID);
		printf("Size of v: %d\n",r->vSize);		
	}

	if (r->normals!=NULL)
	{
		createVBO(GL_ARRAY_BUFFER, &r->nboID, r->normalsSize, r->normals);
		printf("nboID: %i\n",r->nboID);
		printf("Size of normals: %d\n",r->normalsSize);
	}

	if (r->texCoords!=NULL)
	{
		createVBO(GL_ARRAY_BUFFER, &r->tcoID, r->texCoordsSize, r->texCoords);
		printf("tcoID: %i\n",r->tcoID);
		printf("Size of texCoords: %d\n",r->texCoordsSize);
	}

	if (r->indices!=NULL)
	{
		createVBO(GL_ELEMENT_ARRAY_BUFFER, &r->iboID, r->indicesSize, (GLfloat*)r->indices);
		printf("iboID: %i\n",r->iboID);
		printf("Size of Indices: %d\n",r->indicesSize);
	}

	r->mProjHandle = glGetUniformLocation(r->shaderProgram,"mProj");
	r->mViewHandle = glGetUniformLocation(r->shaderProgram,"mView");
	r->mModelHandle = glGetUniformLocation(r->shaderProgram,"mModel");
	r->colorHandle = glGetUniformLocation(r->shaderProgram,"color");
	r->samplerHandle[0] = glGetUniformLocation(r->shaderProgram,"samp");
	r->samplerHandle[1] = glGetUniformLocation(r->shaderProgram,"samp2");
}
示例#25
0
Mesh MeshLoader::getSubPlane(int x, int y, int width, int height, int w,
                             int h) {
  // Generate vertex array object
  GLuint vao;
  glGenVertexArrays(1, &vao);
  glBindVertexArray(vao);

  static constexpr int8_t vertices[4][3] = {
      {0, -1, 0}, {1, -1, 0}, {1, 0, 0}, {0, 0, 0}
  };

  const float texCoords[4][2] = {
      {static_cast<float>(x) / w,         static_cast<float>(y) / h},
      {static_cast<float>(x + width) / w, static_cast<float>(y) / h},
      {static_cast<float>(x + width) / w, static_cast<float>(y + height) / h},
      {static_cast<float>(x) / w,         static_cast<float>(y + height) / h}
  };

  static constexpr uint8_t vi[6] = {0, 1, 3, 2, 3, 1}, ti[6] = {3, 2, 0, 1, 0, 2};

  constexpr unsigned int vtxSize = 3 * sizeof(int8_t) + 2 * sizeof(float);
  TightDataPacker data(6 * vtxSize);
  for (int i = 0; i < 6; ++i) {
    const int8_t *v = vertices[vi[i]];
    data << v[0] << v[1] << v[2];
    const float *t = texCoords[ti[i]];
    data << t[0] << t[1];
  }

  assert(data.getSize() == 6 * vtxSize);

  // Put the vertex buffer into the VAO
  createVBO(GL_ARRAY_BUFFER, data.getSize(), data.getDataPtr(), vtxSize,
            { {0, 3, GL_BYTE, nullptr},
              {1, 2, GL_FLOAT, reinterpret_cast<GLvoid *>(3 * sizeof(int8_t))} });
  // Unbind VAO
  glBindVertexArray(0);

  // Store relevant data in the new mesh
  return Mesh{static_cast<int>(vao), 2, {}};
}
示例#26
0
//----------------------------------------------------------------------
void FLOCK::prepareSorted()
{

    vector<int4> i4Vec(max_num);
    vector<float4> f4Vec(max_num);
    fill(i4Vec.begin(), i4Vec.end(), int4(0,0,0,0));
    fill(f4Vec.begin(), f4Vec.end(), float4(0.0f, 0.0f, 0.0f, 1.0f));
    rotationVBO = createVBO(&f4Vec[0], f4Vec.size()*sizeof(float4), GL_ARRAY_BUFFER, GL_DYNAMIC_DRAW);
    cl_rotation_u = Buffer<float4>(cli,rotationVBO);
    fill(f4Vec.begin(), f4Vec.end(), float4(0.0f, 0.0f, 0.0f, 0.0f));
    cl_flockmates_s= Buffer<int4>(cli, i4Vec);
    cl_separation_s = Buffer<float4>(cli, f4Vec);
    cl_alignment_s = Buffer<float4>(cli, f4Vec);
    cl_cohesion_s = Buffer<float4>(cli, f4Vec);
    cl_goal_s = Buffer<float4>(cli, f4Vec);
    cl_avoid_s = Buffer<float4>(cli, f4Vec);
    cl_leaderfollowing_s = Buffer<float4>(cli, f4Vec);
    cl_veleval_u = Buffer<float4>(cli,f4Vec);
    cl_veleval_s = Buffer<float4>(cli,f4Vec);
            //TODO make a helper constructor for buffer to make a cl_mem from a struct
        //Setup Grid Parameter structs
        vector<GridParams> gparams(0);
        gparams.push_back(grid_params);
        cl_GridParams = Buffer<GridParams>(cli, gparams);

        //scaled Grid Parameters
        vector<GridParams> sgparams(0);
        sgparams.push_back(grid_params_scaled);
        cl_GridParamsScaled = Buffer<GridParams>(cli, sgparams);
                // Size is the grid size + 1, the last index is used to signify how many particles are within bounds
        // That is a problem since the number of
        // occupied cells could be much less than the number of grid elements.
        dout<<"Number of Grid Cells: "<< grid_params.nb_cells<<endl;
        vector<unsigned int> gcells(grid_params.nb_cells+1);
        int minus = 0xffffffff;
        std::fill(gcells.begin(), gcells.end(), 666);

        cl_cell_indices_start = Buffer<unsigned int>(cli, gcells);
        cl_cell_indices_end   = Buffer<unsigned int>(cli, gcells);

}
示例#27
0
void init() {
	createVBO();

	// Vertex Array Object
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	// Load shaders
	GLuint program = InitShader("vshader.glsl", "fshader.glsl");
	glUseProgram(program);

	// Set position and color for single cube
	glBindBuffer(GL_ARRAY_BUFFER, vbo);

	GLuint vPosition = glGetAttribLocation(program, "vPosition");
	glEnableVertexAttribArray(vPosition);
	glVertexAttribPointer(vPosition, 4, GL_FLOAT, GL_FALSE, 0, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);

	glBindVertexArray(0);

	// Handle depth info
	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
	glDepthFunc(GL_LEQUAL);
	glDepthRange(0.0, 1.0);

	// Set up uniform variables
	uRotationMat = glGetUniformLocation(program, "rotationMat");
	uScale = glGetUniformLocation(program, "scale");
	uPositions = glGetUniformLocation(program, "positions");
	uCubeId = glGetUniformLocation(program, "cubeId");
	uColors = glGetUniformLocation(program, "colors");
	uRotationAxes = glGetUniformLocation(program, "rotationAxes");
	uRotationProgress = glGetUniformLocation(program, "rotationProgress");

	glutPostRedisplay();
	glutSwapBuffers();
}
示例#28
0
// create fixed vertex buffer to store mesh vertices
void createMeshPositionVBO(GLuint *id, int w, int h)
{
    createVBO(id, w*h*4*sizeof(float));

    glBindBuffer(GL_ARRAY_BUFFER, *id);
    float *pos = (float *) glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
    if (!pos) {
        return;
    }
    
    for(int y=0; y<h; y++) {
        for(int x=0; x<w; x++) {
            float u = x / (float) (w-1);
            float v = y / (float) (h-1);
            *pos++ = u*2.0f-1.0f;
            *pos++ = 0.0f;
            *pos++ = v*2.0f-1.0f;
            *pos++ = 1.0f;
        }
    }

    glUnmapBuffer(GL_ARRAY_BUFFER);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void
ParticleSystem::_initialize(int numParticles)
{
    assert(!m_bInitialized);

    m_numParticles = numParticles;

    // allocate host storage
    m_hPos = new float[m_numParticles*4];
    m_hVel = new float[m_numParticles*4];
    memset(m_hPos, 0, m_numParticles*4*sizeof(float));
    memset(m_hVel, 0, m_numParticles*4*sizeof(float));

    m_hCellStart = new uint[m_numGridCells];
    memset(m_hCellStart, 0, m_numGridCells*sizeof(uint));

    m_hCellEnd = new uint[m_numGridCells];
    memset(m_hCellEnd, 0, m_numGridCells*sizeof(uint));

    // allocate GPU data
    unsigned int memSize = sizeof(float) * 4 * m_numParticles;

    if (m_bUseOpenGL)
    {
        m_posVbo = createVBO(memSize);
        registerGLBufferObject(m_posVbo, &m_cuda_posvbo_resource);
    }
    else
    {
        checkCudaErrors(cudaMalloc((void **)&m_cudaPosVBO, memSize)) ;
    }

    allocateArray((void **)&m_dVel, memSize);

    allocateArray((void **)&m_dSortedPos, memSize);
    allocateArray((void **)&m_dSortedVel, memSize);

    allocateArray((void **)&m_dGridParticleHash, m_numParticles*sizeof(uint));
    allocateArray((void **)&m_dGridParticleIndex, m_numParticles*sizeof(uint));

    allocateArray((void **)&m_dCellStart, m_numGridCells*sizeof(uint));
    allocateArray((void **)&m_dCellEnd, m_numGridCells*sizeof(uint));

    if (m_bUseOpenGL)
    {
        m_colorVBO = createVBO(m_numParticles*4*sizeof(float));
        registerGLBufferObject(m_colorVBO, &m_cuda_colorvbo_resource);

        // fill color buffer
        glBindBufferARB(GL_ARRAY_BUFFER, m_colorVBO);
        float *data = (float *) glMapBufferARB(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
        float *ptr = data;

        for (uint i=0; i<m_numParticles; i++)
        {
            float t = i / (float) m_numParticles;
#if 0
            *ptr++ = rand() / (float) RAND_MAX;
            *ptr++ = rand() / (float) RAND_MAX;
            *ptr++ = rand() / (float) RAND_MAX;
#else
            colorRamp(t, ptr);
            ptr+=3;
#endif
            *ptr++ = 1.0f;
        }

        glUnmapBufferARB(GL_ARRAY_BUFFER);
    }
    else
    {
        checkCudaErrors(cudaMalloc((void **)&m_cudaColorVBO, sizeof(float)*numParticles*4));
    }

    sdkCreateTimer(&m_timer);

    setParameters(&m_params);

    m_bInitialized = true;
}
示例#30
0
void PoiseuilleFlowSystem::_initialize(int numParticles){
	assert(!IsInitialized);

	numParticles = numParticles;

	hPos = new float[numParticles*4];
	hVel = new float[numParticles*4];
	hVelLeapFrog = new float[numParticles*4];		
	hMeasures = new float[numParticles*4];
	hAcceleration = new float[numParticles*4];
	memset(hPos, 0, numParticles*4*sizeof(float));
	memset(hVel, 0, numParticles*4*sizeof(float));
	memset(hVelLeapFrog, 0, numParticles*4*sizeof(float));
	memset(hAcceleration, 0, numParticles*4*sizeof(float));	
	memset(hMeasures, 0, numParticles*4*sizeof(float)); 

	for(uint i = 0; i < numParticles; i++) //todo: check density approximation
		hMeasures[4*i+0] = params.restDensity;

	unsigned int memSize = sizeof(float) * 4 * numParticles;

	if (IsOpenGL) {
		posVbo = createVBO(memSize);    
	registerGLBufferObject(posVbo, &cuda_posvbo_resource);
	} else {
		checkCudaErrors( cudaMalloc( (void **)&cudaPosVBO, memSize )) ;
	}

	allocateArray((void**)&dVel, memSize);
	allocateArray((void**)&dVelLeapFrog, memSize);
	allocateArray((void**)&dAcceleration, memSize);
	allocateArray((void**)&dMeasures, memSize);

	allocateArray((void**)&dSortedPos, memSize);
	allocateArray((void**)&dSortedVel, memSize);
	
	allocateArray((void**)&dHash, numParticles*sizeof(uint));
	allocateArray((void**)&dIndex, numParticles*sizeof(uint));

	allocateArray((void**)&dCellStart, numGridCells*sizeof(uint));
	allocateArray((void**)&dCellEnd, numGridCells*sizeof(uint));

	if (IsOpenGL) {
		colorVBO = createVBO(numParticles*4*sizeof(float));
	registerGLBufferObject(colorVBO, &cuda_colorvbo_resource);

		// fill color buffer
		glBindBufferARB(GL_ARRAY_BUFFER, colorVBO);
		float *data = (float *) glMapBufferARB(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
		float *ptr = data;
		uint fluidParticles = params.fluidParticlesSize.x * params.fluidParticlesSize.y * params.fluidParticlesSize.z;
		for(uint i=0; i < numParticles; i++) {
			float t = 0.7f;  
			if(i < fluidParticles)
				t = 0.5f;  
			if(((i % params.gridSize.x) == 0) && i < fluidParticles)
				t = 0.2f;    			
			colorRamp(t, ptr);
			ptr+=3;
			*ptr++ = 1.0f;
		}
		glUnmapBufferARB(GL_ARRAY_BUFFER);
	} else {
		checkCudaErrors( cudaMalloc( (void **)&cudaColorVBO, sizeof(float)*numParticles*4) );
	}	   

	setParameters(&params);

	IsInitialized = true;
}