Esempio n. 1
0
void GLWidget::paintGL()
{
    glPopMatrix(); // pop the matrix pushed in the pbuffer list

    // push the projection matrix and the entire GL state before
    // doing any rendering into our framebuffer object
    glPushAttrib(GL_ALL_ATTRIB_BITS);
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();

    glViewport(0, 0, fbo->size().width(), fbo->size().height());
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1, 1, -1, 1, -99, 99);
    glTranslatef(-0.5f, -0.5f, 0.0f);
    glMatrixMode(GL_MODELVIEW);

    // render to the framebuffer object
    fbo->bind();
    glBindTexture(GL_TEXTURE_2D, cubeTexture);
    glCallList(pbufferList);
    fbo->release();

    // pop the projection matrix and GL state back for rendering
    // to the actual widget
    glPopAttrib();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();

    glBindTexture(GL_TEXTURE_2D, fbo->texture());
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // draw the background
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();

    glVertexPointer(2, GL_INT, 0, faceArray);
    glTranslatef(-1.2f, -0.8f, 0.0f);
    glScalef(0.2f, 0.2f, 0.2f);
    for (int y = 0; y < 5; ++y) {
	for (int x = 0; x < 5; ++x) {
	    glTranslatef(2.0f, 0, 0);
	    glColor4f(0.8f, 0.8f, 0.8f, 1.0f);
	    glDrawArrays(GL_QUADS, 0, 4);
	}
 	glTranslatef(-10.0f, 2.0f, 0);
    }
    glVertexPointer(3, GL_INT, 0, cubeArray);

    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);

    // draw the bouncing cubes
    drawCube(0, 0.0f, 1.5f, 2.5f, 1.5f);
    drawCube(1, 1.0f, 2.0f, 2.5f, 2.0f);
    drawCube(2, 2.0f, 3.5f, 2.5f, 2.5f);
    glPopMatrix();
}
Esempio n. 2
0
void RenderSystem::startFrame(const View& view) {
    glClear(GL_COLOR_BUFFER_BIT);
    m_View = view;
}
Esempio n. 3
0
void renderSpace(sf::RenderTarget& window, sf::Vector3f cameraPosition, float yaw, float pitch, float roll)
{
    window.pushGLStates();

    glClearDepth(1.f);
    glClear(GL_DEPTH_BUFFER_BIT);
    glDepthMask(GL_TRUE);
    glEnable(GL_CULL_FACE);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    _glPerspective(60.f, 320.0/240.0, 1.f, 16000.f);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glRotatef(90, 1, 0, 0);
    glScalef(1,1,-1);
    glRotatef(-roll, 0,1, 0);
    glRotatef(-pitch, 0, 1, 0);
    glRotatef(-yaw, 0, 0, 1);
  
    textureManager.getTexture("Stars")->setSmooth(true);
    sf::Texture::bind(textureManager.getTexture("Stars"), sf::Texture::Pixels);
    glBegin(GL_TRIANGLE_STRIP);
    glTexCoord2f(1024,    0); glVertex3f( 100, 100, 100);
    glTexCoord2f(   0,    0); glVertex3f( 100, 100,-100);
    glTexCoord2f(1024, 1024); glVertex3f(-100, 100, 100);
    glTexCoord2f(   0, 1024); glVertex3f(-100, 100,-100);
    glEnd();
    glBegin(GL_TRIANGLE_STRIP);
    glTexCoord2f(1024,    0); glVertex3f(-100, 100, 100);
    glTexCoord2f(   0,    0); glVertex3f(-100, 100,-100);
    glTexCoord2f(1024, 1024); glVertex3f(-100,-100, 100);
    glTexCoord2f(   0, 1024); glVertex3f(-100,-100,-100);
    glEnd();
    glBegin(GL_TRIANGLE_STRIP);
    glTexCoord2f(1024,    0); glVertex3f(-100,-100, 100);
    glTexCoord2f(   0,    0); glVertex3f(-100,-100,-100);
    glTexCoord2f(1024, 1024); glVertex3f( 100,-100, 100);
    glTexCoord2f(   0, 1024); glVertex3f( 100,-100,-100);
    glEnd();
    glBegin(GL_TRIANGLE_STRIP);
    glTexCoord2f(1024,    0); glVertex3f( 100,-100, 100);
    glTexCoord2f(   0,    0); glVertex3f( 100,-100,-100);
    glTexCoord2f(1024, 1024); glVertex3f( 100, 100, 100);
    glTexCoord2f(   0, 1024); glVertex3f( 100, 100,-100);
    glEnd();
    glBegin(GL_TRIANGLE_STRIP);
    glTexCoord2f(1024,    0); glVertex3f( 100,-100, 100);
    glTexCoord2f(   0,    0); glVertex3f(-100,-100, 100);
    glTexCoord2f(1024, 1024); glVertex3f( 100, 100, 100);
    glTexCoord2f(   0, 1024); glVertex3f(-100, 100, 100);
    glEnd();
    glBegin(GL_TRIANGLE_STRIP);
    glTexCoord2f(1024,    0); glVertex3f( 100,-100,-100);
    glTexCoord2f(   0,    0); glVertex3f(-100,-100,-100);
    glTexCoord2f(1024, 1024); glVertex3f( 100, 100,-100);
    glTexCoord2f(   0, 1024); glVertex3f(-100, 100,-100);
    glEnd();
    
    for(unsigned int n=0; n<nebulaInfo.size(); n++)
    {
        sf::Texture::bind(textureManager.getTexture(nebulaInfo[n].textureName), sf::Texture::Pixels);
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE);
        glPushMatrix();
        glRotatef(180, nebulaInfo[n].vector.x, nebulaInfo[n].vector.y, nebulaInfo[n].vector.z);
        glColor4f(1,1,1,0.3);
        glBegin(GL_TRIANGLE_STRIP);
        glTexCoord2f(1024,    0); glVertex3f( 100, 100, 100);
        glTexCoord2f(   0,    0); glVertex3f( 100, 100,-100);
        glTexCoord2f(1024, 1024); glVertex3f(-100, 100, 100);
        glTexCoord2f(   0, 1024); glVertex3f(-100, 100,-100);
        glEnd();
        glPopMatrix();
    }
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    sf::Texture::bind(NULL);
    
    sf::Vector2f cameraPosition2D(cameraPosition.x, cameraPosition.y);
    glDisable(GL_DEPTH_TEST);

    //Shade the objects with light from the first sun.
    //TODO: Fix for multiple suns.
    P<Sun> sun = sunList[0];
    
    if (lightShader == NULL)
    {
        lightShader = new sf::Shader();
        lightShader->loadFromFile("resources/perPixelLight.vert", "resources/perPixelLight.frag");
    }
    
    sf::Vector2f viewVector = sf::vector2FromAngle(yaw);
    std::vector<RenderSortInfo> renderList;
    foreach(SpaceObject, obj, spaceObjectList)
    {
        RenderSortInfo info;
        info.obj = *obj;
        info.objectDepth = sf::dot(viewVector, obj->getPosition() - cameraPosition2D);
        
        renderList.push_back(info);
    }
Esempio n. 4
0
void RenderScene() {
	std::cout << "entered renderscene" << std::endl;
	glClear(GL_COLOR_BUFFER_BIT);
	Mesh mesh;
	mesh.LoadMesh("/home/feiyu/devTools/ogldev-source/Content/jeep.obj");

//transform
	static float Scale = 0.0f;
	Matrix44f mat44;
	Scale += 0.001f;
	mat44(0, 0) = cosf(Scale);
	mat44(0, 1) = 0;
	mat44(0, 2) = -sinf(Scale);
	mat44(0, 3) = 0;
	mat44(1, 0) = 0;
	mat44(1, 1) = 1;
	mat44(1, 2) = 0;
	mat44(1, 3) = 0;
	mat44(2, 0) = sinf(Scale);
	mat44(2, 1) = 0;
	mat44(2, 2) = cosf(Scale);
	mat44(2, 3) = 0;
	mat44(3, 0) = 0;
	mat44(3, 1) = 0;
	mat44(3, 2) = 0;
	mat44(3, 3) = 1;
	glUniformMatrix4fv(gWorldLocation, 1, GL_TRUE, &mat44(0, 0));
//end transform

	mesh.Render();

	glutSwapBuffers();
	glutPostRedisplay();
	std::cout << "left renderscene" << std::endl;
	/*glClear(GL_COLOR_BUFFER_BIT);
	 static float Scale = 0.0f;
	 Matrix44f mat44;

	 Scale += 0.001f;
	 mat44(0,0)=cosf(Scale);
	 mat44(0,1)=0;
	 mat44(0,2)=-sinf(Scale);
	 mat44(0,3)=0;
	 mat44(1,0)=0;
	 mat44(1,1)=1;
	 mat44(1,2)=0;
	 mat44(1,3)=0;
	 mat44(2,0)=sinf(Scale);
	 mat44(2,1)=0;
	 mat44(2,2)=cosf(Scale);
	 mat44(2,3)=0;
	 mat44(3,0)=0;
	 mat44(3,1)=0;
	 mat44(3,2)=0;
	 mat44(3,3)=1;

	 glUniformMatrix4fv(gWorldLocation, 1, GL_TRUE, &mat44(0,0));

	 glEnableVertexAttribArray(0);
	 glBindBuffer(GL_ARRAY_BUFFER, VBO);
	 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
	 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);

	 glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, 0);

	 glDisableVertexAttribArray(0);

	 glutSwapBuffers();*/
}
Esempio n. 5
0
static void screen_opengl_render_apply(OGLRender *oglrender)
{
    Scene *scene = oglrender->scene;
    ARegion *ar = oglrender->ar;
    View3D *v3d = oglrender->v3d;
    RegionView3D *rv3d = oglrender->rv3d;
    RenderResult *rr;
    Object *camera = NULL;
    ImBuf *ibuf;
    void *lock;
    float winmat[4][4];
    int sizex = oglrender->sizex;
    int sizey = oglrender->sizey;
    const short view_context = (v3d != NULL);
    bool draw_bgpic = true;
    bool draw_sky = (scene->r.alphamode == R_ADDSKY);
    unsigned char *rect = NULL;

    rr = RE_AcquireResultRead(oglrender->re);

    if (oglrender->is_sequencer) {
        SeqRenderData context;
        SpaceSeq *sseq = oglrender->sseq;
        int chanshown = sseq ? sseq->chanshown : 0;
        struct bGPdata *gpd = (sseq && (sseq->flag & SEQ_SHOW_GPENCIL)) ? sseq->gpd : NULL;

        context = BKE_sequencer_new_render_data(oglrender->bmain->eval_ctx, oglrender->bmain,
                                                scene, oglrender->sizex, oglrender->sizey, 100.0f);

        ibuf = BKE_sequencer_give_ibuf(&context, CFRA, chanshown);

        if (ibuf) {
            ImBuf *linear_ibuf;

            BLI_assert((oglrender->sizex == ibuf->x) && (oglrender->sizey == ibuf->y));

            linear_ibuf = IMB_dupImBuf(ibuf);
            IMB_freeImBuf(ibuf);

            if (linear_ibuf->rect_float == NULL) {
                /* internally sequencer working in display space and stores both bytes and float buffers in that space.
                 * It is possible that byte->float onversion didn't happen in sequencer (e.g. when adding image sequence/movie
                 * into sequencer) there'll be only byte buffer. Create float buffer from existing byte buffer, making it linear
                 */

                IMB_float_from_rect(linear_ibuf);
            }
            else {
                /* ensure float buffer is in linear space, not in display space */
                BKE_sequencer_imbuf_from_sequencer_space(scene, linear_ibuf);
            }

            memcpy(rr->rectf, linear_ibuf->rect_float, sizeof(float) * 4 * oglrender->sizex * oglrender->sizey);

            IMB_freeImBuf(linear_ibuf);
        }

        if (gpd) {
            int i;
            unsigned char *gp_rect;

            GPU_offscreen_bind(oglrender->ofs);

            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            wmOrtho2(0, sizex, 0, sizey);
            glTranslatef(sizex / 2, sizey / 2, 0.0f);

            ED_gpencil_draw_ex(gpd, sizex, sizey, scene->r.cfra);

            gp_rect = MEM_mallocN(sizex * sizey * sizeof(unsigned char) * 4, "offscreen rect");
            GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, gp_rect);

            for (i = 0; i < sizex * sizey * 4; i += 4) {
                float  col_src[4];
                rgba_uchar_to_float(col_src, &gp_rect[i]);
                blend_color_mix_float(&rr->rectf[i], &rr->rectf[i], col_src);
            }
            GPU_offscreen_unbind(oglrender->ofs);

            MEM_freeN(gp_rect);
        }
    }
    else if (view_context) {
        ED_view3d_draw_offscreen_init(scene, v3d);

        GPU_offscreen_bind(oglrender->ofs); /* bind */

        /* render 3d view */
        if (rv3d->persp == RV3D_CAMOB && v3d->camera) {
            /*int is_ortho = scene->r.mode & R_ORTHO;*/
            camera = v3d->camera;
            RE_GetCameraWindow(oglrender->re, camera, scene->r.cfra, winmat);

        }
        else {
            rctf viewplane;
            float clipsta, clipend;

            bool is_ortho = ED_view3d_viewplane_get(v3d, rv3d, sizex, sizey, &viewplane, &clipsta, &clipend, NULL);
            if (is_ortho) orthographic_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, -clipend, clipend);
            else perspective_m4(winmat, viewplane.xmin, viewplane.xmax, viewplane.ymin, viewplane.ymax, clipsta, clipend);
        }

        rect = MEM_mallocN(sizex * sizey * sizeof(unsigned char) * 4, "offscreen rect");

        if ((scene->r.mode & R_OSA) == 0) {
            ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat, draw_bgpic, draw_sky);
            GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, rect);
        }
        else {
            /* simple accumulation, less hassle then FSAA FBO's */
            static float jit_ofs[32][2];
            float winmat_jitter[4][4];
            int *accum_buffer = MEM_mallocN(sizex * sizey * sizeof(int) * 4, "accum1");
            int i, j;

            BLI_jitter_init(jit_ofs, scene->r.osa);

            /* first sample buffer, also initializes 'rv3d->persmat' */
            ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat, draw_bgpic, draw_sky);
            GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, rect);

            for (i = 0; i < sizex * sizey * 4; i++)
                accum_buffer[i] = rect[i];

            /* skip the first sample */
            for (j = 1; j < scene->r.osa; j++) {
                copy_m4_m4(winmat_jitter, winmat);
                window_translate_m4(winmat_jitter, rv3d->persmat,
                                    (jit_ofs[j][0] * 2.0f) / sizex,
                                    (jit_ofs[j][1] * 2.0f) / sizey);

                ED_view3d_draw_offscreen(scene, v3d, ar, sizex, sizey, NULL, winmat_jitter, draw_bgpic, draw_sky);
                GPU_offscreen_read_pixels(oglrender->ofs, GL_UNSIGNED_BYTE, rect);

                for (i = 0; i < sizex * sizey * 4; i++)
                    accum_buffer[i] += rect[i];
            }

            for (i = 0; i < sizex * sizey * 4; i++)
                rect[i] = accum_buffer[i] / scene->r.osa;

            MEM_freeN(accum_buffer);
        }

        GPU_offscreen_unbind(oglrender->ofs); /* unbind */
    }
    else {
        /* shouldnt suddenly give errors mid-render but possible */
        char err_out[256] = "unknown";
        ImBuf *ibuf_view = ED_view3d_draw_offscreen_imbuf_simple(scene, scene->camera, oglrender->sizex, oglrender->sizey,
                           IB_rect, OB_SOLID, false, true,
                           (draw_sky) ? R_ADDSKY : R_ALPHAPREMUL, err_out);
        camera = scene->camera;

        if (ibuf_view) {
            /* steal rect reference from ibuf */
            rect = (unsigned char *)ibuf_view->rect;
            ibuf_view->mall &= ~IB_rect;

            IMB_freeImBuf(ibuf_view);
        }
        else {
            fprintf(stderr, "%s: failed to get buffer, %s\n", __func__, err_out);
        }
    }

    /* note on color management:
     *
     * OpenGL renders into sRGB colors, but render buffers are expected to be
     * linear So we convert to linear here, so the conversion back to bytes can make it
     * sRGB (or other display space) again, and so that e.g. openexr saving also saves the
     * correct linear float buffer.
     */

    if (rect) {
        int profile_to;

        if (BKE_scene_check_color_management_enabled(scene))
            profile_to = IB_PROFILE_LINEAR_RGB;
        else
            profile_to = IB_PROFILE_SRGB;

        /* sequencer has got trickier conversion happened above
         * also assume opengl's space matches byte buffer color space */
        IMB_buffer_float_from_byte(rr->rectf, rect,
                                   profile_to, IB_PROFILE_SRGB, true,
                                   oglrender->sizex, oglrender->sizey, oglrender->sizex, oglrender->sizex);
    }

    /* rr->rectf is now filled with image data */

    if ((scene->r.stamp & R_STAMP_ALL) && (scene->r.stamp & R_STAMP_DRAW))
        BKE_stamp_buf(scene, camera, rect, rr->rectf, rr->rectx, rr->recty, 4);

    RE_ReleaseResult(oglrender->re);

    /* update byte from float buffer */
    ibuf = BKE_image_acquire_ibuf(oglrender->ima, &oglrender->iuser, &lock);

    if (ibuf) {
        ibuf->userflags |= IB_DISPLAY_BUFFER_INVALID;

        /* write file for animation */
        if (oglrender->write_still) {
            char name[FILE_MAX];
            int ok;

            if (scene->r.im_format.planes == R_IMF_CHAN_DEPTH_8) {
                IMB_color_to_bw(ibuf);
            }

            BKE_makepicstring(name, scene->r.pic, oglrender->bmain->name, scene->r.cfra,
                              &scene->r.im_format, (scene->r.scemode & R_EXTENSION) != 0, false);
            ok = BKE_imbuf_write_as(ibuf, name, &scene->r.im_format, true); /* no need to stamp here */
            if (ok) printf("OpenGL Render written to '%s'\n", name);
            else printf("OpenGL Render failed to write '%s'\n", name);
        }
    }

    BKE_image_release_ibuf(oglrender->ima, ibuf, lock);

    if (rect)
        MEM_freeN(rect);
}
Esempio n. 6
0
void
clear_display() {
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void DynamicGameAppDelegate::willRedisplay(const Window &, float deltaTime)
{
    (void)deltaTime;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    drawField();
}
Esempio n. 8
0
window::window(int width, int height, bool fullScreen, std::wstring ptitle) : width (width), height(height), fullScreen(fullScreen), title(ptitle) {
	
	windowHandle = 0;
	deviceContext = 0;
	renderingContext = 0;

	WNDCLASSEX windowClass = {0};
	windowClass.cbSize = sizeof(windowClass);
	windowClass.hInstance = GetModuleHandle(0);
	windowClass.style = CS_OWNDC;
	windowClass.hIcon = LoadIcon(windowClass.hInstance, MAKEINTRESOURCE(129));
	windowClass.lpfnWndProc = wndproc;
	windowClass.lpszClassName = L"classy class";

	ZeroMemory(keyDown, 256*sizeof(bool));
	mouseLeft = mouseRight = false;

	RegisterClassEx(&windowClass);

	HWND temporaryWindow = CreateWindowEx(WS_EX_APPWINDOW, L"classy class", L"temporary", WS_SYSMENU|WS_BORDER|WS_MINIMIZEBOX, 0, 0, 0, 0, 0, 0, windowClass.hInstance, 0);
	HDC temporaryDeviceContext = GetDC(temporaryWindow);
	
	PIXELFORMATDESCRIPTOR pixelFormat = {0};

	pixelFormat.nSize = sizeof(pixelFormat);
	pixelFormat.nVersion = 1;
	pixelFormat.dwFlags = PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER;
	pixelFormat.cColorBits = 32;
	pixelFormat.cDepthBits = 24;
	
	SetPixelFormat(temporaryDeviceContext, ChoosePixelFormat(temporaryDeviceContext, &pixelFormat), &pixelFormat);
	
	HGLRC temporaryRenderingContext = wglCreateContext(temporaryDeviceContext);

	wglMakeCurrent(temporaryDeviceContext, temporaryRenderingContext);

	const int formatAttributes[] = 
	{
		WGL_DRAW_TO_WINDOW_ARB,    1,
		WGL_SUPPORT_OPENGL_ARB,    1,
		WGL_ACCELERATION_ARB, 0x2027,
		WGL_DOUBLE_BUFFER_ARB,     1,
		WGL_PIXEL_TYPE_ARB,   0x202B,
		WGL_COLOR_BITS_ARB,       32,
		WGL_DEPTH_BITS_ARB,       24,
		0
	};

	const int contextAttributes[] = 
	{
		WGL_CONTEXT_PROFILE_MASK_ARB, 1,
		WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
		WGL_CONTEXT_MINOR_VERSION_ARB, 3,
		0
	};

	int format, formatcount;
	
	RECT windowArea = {0, 0, width, height};
	DWORD displayFlags = WS_POPUP;

	if(fullScreen) {
		DEVMODE dev = {0};
		dev.dmSize = sizeof(DEVMODE);
		dev.dmFields = DM_PELSWIDTH|DM_PELSHEIGHT|DM_BITSPERPEL;
		dev.dmPelsWidth = width;
		dev.dmPelsHeight = height;
		dev.dmBitsPerPel = 32;
		ChangeDisplaySettings(&dev, CDS_FULLSCREEN);
	}
	else {
		displayFlags = WS_SYSMENU|WS_CAPTION|WS_MINIMIZEBOX|WS_BORDER;
		AdjustWindowRect(&windowArea, displayFlags, 0);
		windowArea.right -= windowArea.left;
		windowArea.bottom -= windowArea.top;
		windowArea.left = (GetSystemMetrics(SM_CXSCREEN)-windowArea.right )/2;
		windowArea.top  = (GetSystemMetrics(SM_CYSCREEN)-windowArea.bottom)/2;
	}
	
	windowHandle = CreateWindowEx(WS_EX_APPWINDOW, L"classy class", title.c_str(), displayFlags, windowArea.left, windowArea.top, windowArea.right, windowArea.bottom, 0, 0, windowClass.hInstance, 0);
	deviceContext = GetDC(windowHandle);
	
	((PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"))(deviceContext, formatAttributes, 0, 1, &format, (UINT*)&formatcount);

	SetPixelFormat(deviceContext, format, &pixelFormat);

	renderingContext = ((PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"))(deviceContext, 0, contextAttributes);
	
	wglMakeCurrent(deviceContext, renderingContext);
	
	wglDeleteContext(temporaryRenderingContext);
	ReleaseDC(temporaryWindow, temporaryDeviceContext);
	DestroyWindow(temporaryWindow);
	MSG message;
	while(PeekMessage(&message, 0, 0, 0, PM_REMOVE));

	#include "glloading.h"

	printf("Vendor         : %s\nRenderer       : %s\nOpenGL version : %s\nGLSL version   : %s\n",glGetString(GL_VENDOR), glGetString(GL_RENDERER), glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION));

	ShowWindow(windowHandle, SW_SHOW);
	glViewport(0, 0, width, height);
	glClearColor(.0f,.0f,.0f,.0f);
	glClear(GL_COLOR_BUFFER_BIT);
	SwapBuffers(deviceContext);

	Gdiplus::GdiplusStartupInput gdiInput;
	ZeroMemory(&gdiInput, sizeof(gdiInput));
	gdiInput.GdiplusVersion = 1;

	Gdiplus::GdiplusStartup((ULONG_PTR*)&gdiToken, &gdiInput, 0);
	
	/*int charsize = 64;
	int fontsize = 16*charsize;

	Gdiplus::Font f(L"Segoe UI Light", float(charsize)*.7f, Gdiplus::FontStyleItalic, Gdiplus::UnitPixel, 0);
	Gdiplus::Bitmap canvas(fontsize, fontsize, PixelFormat32bppARGB);
	Gdiplus::Graphics gfx((Gdiplus::Image*)&canvas);
	gfx.Clear(Gdiplus::Color(0,0,0));
	Gdiplus::SolidBrush brush(Gdiplus::Color(255,255,255));
	Gdiplus::Rect r(0,0, fontsize, fontsize);

	for(int i = 0; i<16; i++)
	for(int j = 0; j<16; j++) {
		wchar_t k = i*16+j;
		Gdiplus::PointF point(float(charsize)*(float(i)+.2f), float(charsize)*(float(j)+.1f));
		gfx.DrawString(&k, 1, &f, point, &brush);
	}*/

	startTime = GetTickCount();
	frameStartTime = startTime+1000;
	frameCount = 0;
	defaultid = 0;
}
Esempio n. 9
0
void render(void)
{
	Rect r;

	//Clear the screen
	glClearColor(1.0, 1.0, 1.0, 1.0);
	glClear(GL_COLOR_BUFFER_BIT);

	//
	//
	//draw a quad with texture
	float wid = 120.0f;
	glColor3f(1.0, 1.0, 1.0);
	if (forest) {
		glBindTexture(GL_TEXTURE_2D, forestTexture);
		glBegin(GL_QUADS);
			glTexCoord2f(0.0f, 1.0f); glVertex2i(0, 0);
			glTexCoord2f(0.0f, 0.0f); glVertex2i(0, yres);
			glTexCoord2f(1.0f, 0.0f); glVertex2i(xres, yres);
			glTexCoord2f(1.0f, 1.0f); glVertex2i(xres, 0);
		glEnd();
	}
	if (show_bigfoot) {
		glPushMatrix();
		glTranslatef(bigfoot.pos[0], bigfoot.pos[1], bigfoot.pos[2]);
		if (!silhouette) {
			glBindTexture(GL_TEXTURE_2D, bigfootTexture);
		} else {
			glBindTexture(GL_TEXTURE_2D, silhouetteTexture);
			glEnable(GL_ALPHA_TEST);
			glAlphaFunc(GL_GREATER, 0.0f);
			glColor4ub(255,255,255,255);
		}
		glBegin(GL_QUADS);
			if (bigfoot.vel[0] > 0.0) {
				glTexCoord2f(0.0f, 1.0f); glVertex2i(-wid,-wid);
				glTexCoord2f(0.0f, 0.0f); glVertex2i(-wid, wid);
				glTexCoord2f(1.0f, 0.0f); glVertex2i( wid, wid);
				glTexCoord2f(1.0f, 1.0f); glVertex2i( wid,-wid);
			} else {
				glTexCoord2f(1.0f, 1.0f); glVertex2i(-wid,-wid);
				glTexCoord2f(1.0f, 0.0f); glVertex2i(-wid, wid);
				glTexCoord2f(0.0f, 0.0f); glVertex2i( wid, wid);
				glTexCoord2f(0.0f, 1.0f); glVertex2i( wid,-wid);
			}
		glEnd();
		glPopMatrix();
		//
		if (trees && silhouette) {
			glBindTexture(GL_TEXTURE_2D, forestTransTexture);
			glBegin(GL_QUADS);
				glTexCoord2f(0.0f, 1.0f); glVertex2i(0, 0);
				glTexCoord2f(0.0f, 0.0f); glVertex2i(0, yres);
				glTexCoord2f(1.0f, 0.0f); glVertex2i(xres, yres);
				glTexCoord2f(1.0f, 1.0f); glVertex2i(xres, 0);
			glEnd();
		}
		glDisable(GL_ALPHA_TEST);
	}

	glDisable(GL_TEXTURE_2D);
	//glColor3f(1.0f, 0.0f, 0.0f);
	//glBegin(GL_QUADS);
	//	glVertex2i(10,10);
	//	glVertex2i(10,60);
	//	glVertex2i(60,60);
	//	glVertex2i(60,10);
	//glEnd();
	//return;
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
	if (show_rain)
		draw_raindrops();
	glDisable(GL_BLEND);
	glEnable(GL_TEXTURE_2D);
	//
	#ifdef USE_UMBRELLA
	if (show_umbrella)
		draw_umbrella();
	#endif //USE_UMBRELLA
	glBindTexture(GL_TEXTURE_2D, 0);
	//
	//
	r.bot = yres - 20;
	r.left = 10;
	r.center = 0;
	unsigned int cref = 0x00ffffff;
	ggprint8b(&r, 16, cref, "B - Bigfoot");
	ggprint8b(&r, 16, cref, "F - Forest");
	ggprint8b(&r, 16, cref, "S - Silhouette");
	ggprint8b(&r, 16, cref, "T - Trees");
	ggprint8b(&r, 16, cref, "U - Umbrella");
	ggprint8b(&r, 16, cref, "R - Rain");
	ggprint8b(&r, 16, cref, "D - Deflection");
	ggprint8b(&r, 16, cref, "N - Sounds");
}
Esempio n. 10
0
GLFWAPI GLFWwindow* glfwCreateWindow(int width, int height,
                                     const char* title,
                                     GLFWmonitor* monitor,
                                     GLFWwindow* share)
{
    _GLFWfbconfig fbconfig;
    _GLFWctxconfig ctxconfig;
    _GLFWwndconfig wndconfig;
    _GLFWwindow* window;
    _GLFWwindow* previous;

    _GLFW_REQUIRE_INIT_OR_RETURN(NULL);

    if (width <= 0 || height <= 0)
    {
        _glfwInputError(GLFW_INVALID_VALUE, "Invalid window size");
        return NULL;
    }

    // Set up desired framebuffer config
    fbconfig.redBits        = _glfw.hints.redBits;
    fbconfig.greenBits      = _glfw.hints.greenBits;
    fbconfig.blueBits       = _glfw.hints.blueBits;
    fbconfig.alphaBits      = _glfw.hints.alphaBits;
    fbconfig.depthBits      = _glfw.hints.depthBits;
    fbconfig.stencilBits    = _glfw.hints.stencilBits;
    fbconfig.accumRedBits   = _glfw.hints.accumRedBits;
    fbconfig.accumGreenBits = _glfw.hints.accumGreenBits;
    fbconfig.accumBlueBits  = _glfw.hints.accumBlueBits;
    fbconfig.accumAlphaBits = _glfw.hints.accumAlphaBits;
    fbconfig.auxBuffers     = _glfw.hints.auxBuffers;
    fbconfig.stereo         = _glfw.hints.stereo;
    fbconfig.samples        = _glfw.hints.samples;
    fbconfig.sRGB           = _glfw.hints.sRGB;
    fbconfig.doublebuffer   = _glfw.hints.doublebuffer ? GL_TRUE : GL_FALSE;

    // Set up desired window config
    wndconfig.width         = width;
    wndconfig.height        = height;
    wndconfig.title         = title;
    wndconfig.resizable     = _glfw.hints.resizable ? GL_TRUE : GL_FALSE;
    wndconfig.visible       = _glfw.hints.visible ? GL_TRUE : GL_FALSE;
    wndconfig.decorated     = _glfw.hints.decorated ? GL_TRUE : GL_FALSE;
    wndconfig.autoIconify   = _glfw.hints.autoIconify ? GL_TRUE : GL_FALSE;
    wndconfig.floating      = _glfw.hints.floating ? GL_TRUE : GL_FALSE;
    wndconfig.monitor       = (_GLFWmonitor*) monitor;

    // Set up desired context config
    ctxconfig.api           = _glfw.hints.api;
    ctxconfig.major         = _glfw.hints.major;
    ctxconfig.minor         = _glfw.hints.minor;
    ctxconfig.forward       = _glfw.hints.forward ? GL_TRUE : GL_FALSE;
    ctxconfig.debug         = _glfw.hints.debug ? GL_TRUE : GL_FALSE;
    ctxconfig.profile       = _glfw.hints.profile;
    ctxconfig.robustness    = _glfw.hints.robustness;
    ctxconfig.share         = (_GLFWwindow*) share;

    // Check the OpenGL bits of the window config
    if (!_glfwIsValidContextConfig(&ctxconfig))
        return NULL;

    window = calloc(1, sizeof(_GLFWwindow));
    window->next = _glfw.windowListHead;
    _glfw.windowListHead = window;

    if (wndconfig.monitor)
    {
        wndconfig.resizable = GL_TRUE;
        wndconfig.visible   = GL_TRUE;

        // Set up desired video mode
        window->videoMode.width       = width;
        window->videoMode.height      = height;
        window->videoMode.redBits     = _glfw.hints.redBits;
        window->videoMode.greenBits   = _glfw.hints.greenBits;
        window->videoMode.blueBits    = _glfw.hints.blueBits;
        window->videoMode.refreshRate = _glfw.hints.refreshRate;
    }

    window->monitor     = wndconfig.monitor;
    window->resizable   = wndconfig.resizable;
    window->decorated   = wndconfig.decorated;
    window->autoIconify = wndconfig.autoIconify;
    window->floating    = wndconfig.floating;
    window->cursorMode  = GLFW_CURSOR_NORMAL;

    // Save the currently current context so it can be restored later
    previous = _glfwPlatformGetCurrentContext();

    // Open the actual window and create its context
    if (!_glfwPlatformCreateWindow(window, &wndconfig, &ctxconfig, &fbconfig))
    {
        glfwDestroyWindow((GLFWwindow*) window);
        _glfwPlatformMakeContextCurrent(previous);
        return NULL;
    }

    _glfwPlatformMakeContextCurrent(window);

    // Retrieve the actual (as opposed to requested) context attributes
    if (!_glfwRefreshContextAttribs(&ctxconfig))
    {
        glfwDestroyWindow((GLFWwindow*) window);
        _glfwPlatformMakeContextCurrent(previous);
        return NULL;
    }

    // Verify the context against the requested parameters
    if (!_glfwIsValidContext(&ctxconfig))
    {
        glfwDestroyWindow((GLFWwindow*) window);
        _glfwPlatformMakeContextCurrent(previous);
        return NULL;
    }

    // Clearing the front buffer to black to avoid garbage pixels left over
    // from previous uses of our bit of VRAM
    glClear(GL_COLOR_BUFFER_BIT);
    _glfwPlatformSwapBuffers(window);

    // Restore the previously current context (or NULL)
    _glfwPlatformMakeContextCurrent(previous);

    if (wndconfig.monitor)
    {
        int width, height;
        _glfwPlatformGetWindowSize(window, &width, &height);

        window->cursorPosX = width / 2;
        window->cursorPosY = height / 2;

        _glfwPlatformSetCursorPos(window, window->cursorPosX, window->cursorPosY);
    }
    else
    {
        if (wndconfig.visible)
            _glfwPlatformShowWindow(window);
    }

    return (GLFWwindow*) window;
}
Esempio n. 11
0
void display(){
  glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

  /* Set up transformation */
  sceneTransformation();

  /*
	GLdouble V[3],U[3]= {0,1,0},R[3];

	V[0] = -current_view[0];
	V[1] = -current_view[1];
	V[2] = -current_view[2];
	Scross_product(&R[0],&R[1],&R[2],U[0],U[1],U[2],V[0],V[1],V[2]);
	Snormalize(&R[0],&R[1],&R[2]);
	GLdouble mx,my;

	mx = startX-prevx;
	my = startY-prevy;

	GLdouble newViewPoint[3] = {current_view[0] + (mx*distanceX *R[0]) + (my*distanceY*U[0]),
		current_view[1] + (mx*distanceX *R[1]) + (my*distanceY*U[1]),
		current_view[2] + (mx*distanceX *R[2]) + (my*distanceY*U[2])};
	GLdouble length_nvp = sqrt((newViewPoint[0]*newViewPoint[0])+
		(newViewPoint[1]*newViewPoint[1])+(newViewPoint[2]*newViewPoint[2]));
	
	current_view[0] = newViewPoint[0]*distanceX/length_nvp;
	current_view[1] = newViewPoint[1]*distanceY/length_nvp;
	current_view[2] = newViewPoint[2]*distanceZ/length_nvp;

	Scross_product(&U[0],&U[1],&U[2],R[0],R[1],R[2],V[0],V[1],V[2]);
	Snormalize(&U[0],&U[1],&U[2]);

	gluLookAt(-V[0],-V[1],-V[2],0,0,0,U[0],U[1],U[2]);

	prevx = startX;
	prevy = startY;
	*/

  /* Draw the scene into the back buffer */

  //draw rotator (larger cube)
  
  glPushMatrix();
  glLoadIdentity();
  glScalef(0.5f,0.5f,0.5f);
  gluLookAt(-1.0, -6.0, -2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
  glTranslatef(0.0f, 0.0f, 0.0f);
  glRotated(anglex,1,0,0);
  drawScene();
  glPopMatrix();
  

  //draw spinner (smaller cube)
  
  glPushMatrix();
  glRotated(angley,0,1,0);
  glTranslatef(-0.0f, 4.5f, -0.0f);
  glScalef(0.25f, 0.25f, 0.25f);
  drawScene();
  glPopMatrix();
  
  /*
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(45.0,20.0,1.0,100.0);
  glMatrixMode(GL_MODELVIEW);
  */
  /* Swap the front buffer with the back buffer - assumes double buffering */
  glutSwapBuffers();
}
Esempio n. 12
0
int main(int argc, char **argv) {
    
    int i;
    int filecount = 0;
    char* filename = NULL;
    
    {
        int c, option_index = 0;
        static struct option long_options[] = {
            {"help", 0, 0, 0},
            {"output", 2, 0, 0},
            {"size", 1, 0, 0},
            {NULL, 0, NULL, 0}
        };
        char* endptr = NULL;
        bool opt_fail = false;
        bool help = false;
        while ((c = getopt_long(argc, argv, "ho::s:",
                long_options, &option_index)) != -1) {
            switch (c) {
                case 0:
                    switch(option_index) {
                    case 0: // help
                        goto help;
                    case 1: // output
                        goto output;
                    case 2: // size
                        goto size;
                    default:
                        goto unknown;
                    }
                    break;
                help:
                case 'h':   // help
                    help = true;
                    break;
                output:
                case 'o':   // output
                    filecount = 1;
                    // avoid leakiness if the user provided multiple --output
                    // free(NULL) is a no-op, so this should be safe:
                    free(filename);
                    filename = NULL;
                    if(optarg != NULL) {
                        int tmp = strtol(optarg, &endptr, 10);
                        if (endptr == optarg || (endptr != NULL && *endptr != '\0')) {
                            int len = strlen(optarg);
                            filename = malloc(len + 1);
                            strcpy(filename, optarg);
                            filename[len] = '\0';
                        } else {
                            filecount = tmp;
                        }
                    }
                    break;
                size:
                case 's':
                    i = 0;
                    while(optarg[i] != '*' && optarg[i] != '\0') i++;
                    if(optarg[i] == '\0') {
                        goto size_fail;
                    }
                    optarg[i] = '\0';
                    width = strtol(optarg, &endptr, 10);
                    if (endptr == optarg || (endptr != NULL && *endptr != '\0')) {
                        goto size_fail;
                    }
                    height = strtol(optarg + i + 1, &endptr, 10);
                    if (endptr == optarg || (endptr != NULL && *endptr != '\0')) {
                        goto size_fail;
                    }
                    printf("width: %d, height: %d\n", width, height);
                    break;
                size_fail:
                    fprintf(stderr, "Invalid size string '%s'\n", optarg);
                    print_help(1);
                    break;
                unknown:
                case '?':
                    opt_fail = true;
                    break;
                default:
                    fprintf(stderr, "?? getopt returned character code 0%o ??\n", c);
            }
        }
        if(opt_fail) {
            print_help(1);
        }
        if(optind < argc) {
            fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], argv[optind]);
            print_help(1);
        }
        if(help) {
            print_help(0);
        }
    }
    
    scale = max(width, height);
    srand(get_time_us());

    GLFWwindow* window;

    glfwSetErrorCallback(error_callback);

    // Initialize the library
    if (!glfwInit())
        return -1;

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);


    // Create a windowed mode window and its OpenGL context
    if(filecount) {
        glfwWindowHint(GLFW_VISIBLE, false);
        window = glfwCreateWindow(1, 1, "SpaceScape", NULL, NULL);
    } else {
        window = glfwCreateWindow(width, height, "SpaceScape", NULL, NULL);
    }
    if (!window) {
        glfwTerminate();
        return -1;
    }

    // Make the window's context current
    glfwMakeContextCurrent(window);

    glfwSetKeyCallback(window, key_callback);

    // Init GLEW
    glewExperimental = true;
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    fprintf(stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION));
    if (!GLEW_ARB_vertex_buffer_object) {
        fputs("VBO not supported\n", stderr);
        exit(1);
    }

    render_init();

    if(filename) {
        render_to_png(filename);
    } else if(filecount) {
        for(i = 0; i < filecount; i++) {
            render_to_png(NULL);
        }
    } else {
        // Render to our framebuffer
        render_to_screen();

        while (!glfwWindowShouldClose(window)) {

            // Clear the screen
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            // 1rst attribute buffer : vertices
            glEnableVertexAttribArray(0);
            glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
            glVertexAttribPointer(
                    0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
                    3, // size
                    GL_FLOAT, // type
                    GL_FALSE, // normalized?
                    0, // stride
                    (void*) 0 // array buffer offset
                    );

            // Draw the triangles !
            glDrawArrays(GL_TRIANGLES, 0, 6); // 2*3 indices starting at 0 -> 2 triangles

            glDisableVertexAttribArray(0);

            // Swap buffers
            glfwSwapBuffers(window);
            glfwPollEvents();
        }
    }

    render_cleanup();

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}
Esempio n. 13
0
void CurrentApp::DefferedDraw(float dt)
{
	IconShader* IS = IconShader::GetInstance();

	// G-Pass: render out the albedo, position and normal
	glEnable(GL_DEPTH_TEST);
	glDisable(GL_BLEND);

	m_gPassTarget->SetAsActiveRenderTarget();
	glClearColor(0, 0, 0, 0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	m_program = IS->UseProgram("GBuffer");

	// bind camera transforms
	int loc = glGetUniformLocation(m_program, "ProjectionView");
	glUniformMatrix4fv(loc, 1, GL_FALSE, &(m_camera->GetProjectionView()[0][0]));

	loc = glGetUniformLocation(m_program, "View");
	glUniformMatrix4fv(loc, 1, GL_FALSE, &(m_camera->GetView()[0][0]));

	m_snowEmitter->draw(CurrentTime(), m_camera->GetTransform(), m_camera->GetProjectionView());
	//m_terrain->Render(m_camera->GetProjectionView());

	// Light Pass: render lights as geometry, sampling position and
	// normals disable depth testing and enable additive blending
	m_lightPassTarget->SetAsActiveRenderTarget();
	glClear(GL_COLOR_BUFFER_BIT);
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_ONE, GL_ONE);
	
	m_program = IS->UseProgram("Light");

	loc = glGetUniformLocation(m_program, "positionTexture");
	glUniform1i(loc, 0);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, m_lightPassTarget->GetRenderTexture(0));

	//loc = glGetUniformLocation(m_program, "normalTexture");
	//glUniform1i(loc, 1);

	//glActiveTexture(GL_TEXTURE1);
	//glBindTexture(GL_TEXTURE_2D, m_normalTexture);

	//drawDirectionalLight(m_lightDir, glm::vec3(1, 1, 1));

	glDisable(GL_BLEND);
	glEnable(GL_DEPTH_TEST);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, 0);

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, 0);

	// Composite Pass: render a quad and combine albedo and light
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	m_program = IS->UseProgram("Composite");

	loc = glGetUniformLocation(m_program, "albedoTexture");
	glUniform1i(loc, 0);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, m_gPassTarget->GetRenderTexture(0));

	loc = glGetUniformLocation(m_program, "lightTexture");
	glUniform1i(loc, 1);

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, m_lightPassTarget->GetRenderTexture(0));

	glBindVertexArray(m_fullscreenQuad);
	glDrawArrays(GL_TRIANGLES, 0, 6);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, 0);

	glActiveTexture(GL_TEXTURE1);
	glBindTexture(GL_TEXTURE_2D, 0);
}
Esempio n. 14
0
void MyWindow::render()
{
    if(!isVisible() || !isExposed())
        return;

    if (!mContext->makeCurrent(this))
        return;

    static bool initialized = false;
    if (!initialized) {
        initialize();
        initialized = true;
    }

    if (mUpdateSize) {
        glViewport(0, 0, size().width(), size().height());
        mUpdateSize = false;
    }

    float deltaT = currentTimeS - tPrev;
    if(tPrev == 0.0f) deltaT = 0.0f;
    tPrev = currentTimeS;
    angle += 0.25f * deltaT;
    if (angle > TwoPI) angle -= TwoPI;

    static float EvolvingVal = 0;
    EvolvingVal += 0.1f;

    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //QMatrix4x4 RotationMatrix;
    //RotationMatrix.rotate(EvolvingVal, QVector3D(0.1f, 0.0f, 0.1f));
    //ModelMatrix.rotate(0.3f, QVector3D(0.1f, 0.0f, 0.1f));
    QVector4D worldLight = QVector4D(10.0f * cos(angle), 10.0f, 10.0f * sin(angle), 1.0f);

    // *** Draw teapot
    mFuncs->glBindVertexArray(mVAOTeapot);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    mProgram->bind();
    {
        QMatrix4x4 mv1 = ViewMatrix * ModelMatrixTeapot;
        mProgram->setUniformValue("ModelViewMatrix", mv1);
        mProgram->setUniformValue("NormalMatrix", mv1.normalMatrix());
        mProgram->setUniformValue("MVP", ProjectionMatrix * mv1);

        mProgram->setUniformValue("Light.Position", ViewMatrix * worldLight);
        mProgram->setUniformValue("Light.Intensity", QVector3D(0.9f, 0.9f, 0.9f));

        mProgram->setUniformValue("Material.Kd", 0.9f, 0.5f, 0.3f);
        mProgram->setUniformValue("Material.Ks", 0.95f, 0.95f, 0.95f);
        mProgram->setUniformValue("Material.Ka", 0.9f * 0.3f, 0.5f * 0.3f, 0.3f * 0.3f);
        mProgram->setUniformValue("Material.Shininess", 100.0f);       

        glDrawElements(GL_TRIANGLES, 6 * mTeapot->getnFaces(), GL_UNSIGNED_INT, ((GLubyte *)NULL + (0)));

        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
    }
    mProgram->release();

    // *** Draw plane
    mFuncs->glBindVertexArray(mVAOPlane);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    mProgram->bind();
    {
        QMatrix4x4 mv1 = ViewMatrix * ModelMatrixPlane;
        mProgram->setUniformValue("ModelViewMatrix", mv1);
        mProgram->setUniformValue("NormalMatrix", mv1.normalMatrix());
        mProgram->setUniformValue("MVP", ProjectionMatrix * mv1);

        mProgram->setUniformValue("Light.Position", ViewMatrix * worldLight);
        mProgram->setUniformValue("Light.Intensity", QVector3D(0.9f, 0.9f, 0.9f));

        mProgram->setUniformValue("Material.Kd", 0.7f, 0.7f, 0.7f);
        mProgram->setUniformValue("Material.Ks", 0.9f, 0.9f, 0.9f);
        mProgram->setUniformValue("Material.Ka", 0.2f, 0.2f, 0.2f);
        mProgram->setUniformValue("Material.Shininess", 180.0f);

        glDrawElements(GL_TRIANGLES, 6 * mPlane->getnFaces(), GL_UNSIGNED_INT, ((GLubyte *)NULL + (0)));

        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
    }
    mProgram->release();

    // *** Draw torus
    mFuncs->glBindVertexArray(mVAOTorus);

    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    mProgram->bind();
    {
        QMatrix4x4 mv1 = ViewMatrix * ModelMatrixTorus;
        mProgram->setUniformValue("ModelViewMatrix", mv1);
        mProgram->setUniformValue("NormalMatrix", mv1.normalMatrix());
        mProgram->setUniformValue("MVP", ProjectionMatrix * mv1);

        mProgram->setUniformValue("Light.Position", ViewMatrix * worldLight);
        mProgram->setUniformValue("Light.Intensity", QVector3D(0.9f, 0.9f, 0.9f));

        mProgram->setUniformValue("Material.Kd", 0.9f, 0.5f, 0.3f);
        mProgram->setUniformValue("Material.Ks", 0.95f, 0.95f, 0.95f);
        mProgram->setUniformValue("Material.Ka", 0.9f * 0.3f, 0.5f * 0.3f, 0.3f * 0.3f);
        mProgram->setUniformValue("Material.Shininess", 100.0f);

        glDrawElements(GL_TRIANGLES, 6 * mTorus->getnFaces(), GL_UNSIGNED_INT, ((GLubyte *)NULL + (0)));

        glDisableVertexAttribArray(0);
        glDisableVertexAttribArray(1);
    }
    mProgram->release();

    mContext->swapBuffers(this);
}
Esempio n. 15
0
	void DisplayDeviceOpenGL::clear(ClearFlags clr)
	{
		glClear((clr & ClearFlags::COLOR ? GL_COLOR_BUFFER_BIT : 0) 
			| (clr & ClearFlags::DEPTH ? GL_DEPTH_BUFFER_BIT : 0) 
			| (clr & ClearFlags::STENCIL ? GL_STENCIL_BUFFER_BIT : 0));
	}
Esempio n. 16
0
void Compositor::process() {

    if(!inport1_.isReady() && pipeThroughIfSecondNotReady_.get()) {
        outport_.activateTarget();
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // bind input image to tex unit
        TextureUnit imageUnit, imageUnitDepth;
        inport0_.bindTextures(imageUnit.getEnum(), imageUnitDepth.getEnum());

        // copy input image to outport
        copyShader_->activate();
        setGlobalShaderParameters(copyShader_);
        inport0_.setTextureParameters(copyShader_, "texParams_");
        copyShader_->setUniform("colorTex_", imageUnit.getUnitNumber());
        copyShader_->setUniform("depthTex_", imageUnitDepth.getUnitNumber());
        renderQuad();
        copyShader_->deactivate();
        outport_.deactivateTarget();
        tgt::TextureUnit::setZeroUnit();
        LGL_ERROR;
        return;
    }
    else if(!inport1_.isReady())
        return;

    if (getInvalidationLevel() >= Processor::INVALID_PROGRAM)
        compile();

    outport_.activateTarget();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glDepthFunc(GL_ALWAYS);

    TextureUnit colorUnit, depthUnit;
    TextureUnit colorUnit1, depthUnit1;
    inport0_.bindTextures(colorUnit.getEnum(), depthUnit.getEnum());
    inport1_.bindTextures(colorUnit1.getEnum(), depthUnit1.getEnum());

    // initialize shader
    program_->activate();
    setGlobalShaderParameters(program_);
    if (compositingMode_.get() != "take-second") {
        program_->setUniform("colorTex0_", colorUnit.getUnitNumber());
        program_->setUniform("depthTex0_", depthUnit.getUnitNumber());
        inport0_.setTextureParameters(program_, "textureParameters0_");
    }
    if (compositingMode_.get() != "take-first") {
        program_->setUniform("colorTex1_", colorUnit1.getUnitNumber());
        program_->setUniform("depthTex1_", depthUnit1.getUnitNumber());
        inport1_.setTextureParameters(program_, "textureParameters1_");
    }
    if (compositingMode_.get() == "take-second-if-ready") {
        if(inport1_.isReady()) {
            program_->setUniform("colorTex0_", colorUnit1.getUnitNumber());
            program_->setUniform("depthTex0_", depthUnit1.getUnitNumber());
            inport1_.setTextureParameters(program_, "textureParameters0_");
        }
        else if(inport0_.isReady()){
            program_->setUniform("colorTex0_", colorUnit.getUnitNumber());
            program_->setUniform("depthTex0_", depthUnit.getUnitNumber());
            inport0_.setTextureParameters(program_, "textureParameters0_");
        }
    }
    if (compositingMode_.get() == "weighted-average")
        program_->setUniform("weightingFactor_", weightingFactor_.get());

    if (compositingMode_.get() == "add") {
            program_->setUniform("weightFirst_", weightFirst_.get());
            program_->setUniform("weightSecond_", weightSecond_.get());
            program_->setUniform("addDepth_", addDepth_.get());
        }

    renderQuad();

    glDepthFunc(GL_LESS);

    program_->deactivate();
    outport_.deactivateTarget();
    TextureUnit::setZeroUnit();
    LGL_ERROR;
}
Esempio n. 17
0
	void DisplayDeviceOpenGL::render(const Renderable* r) const
	{
		if(!r->isEnabled()) {
			// Renderable item not enabled then early return.
			return;
		}

		StencilScopePtr stencil_scope;
		if(r->hasClipSettings()) {
			ModelManager2D mm(static_cast<int>(r->getPosition().x), static_cast<int>(r->getPosition().y));
			auto clip_shape = r->getStencilMask();
			bool cam_set = false;
			if(clip_shape->getCamera() == nullptr && r->getCamera() != nullptr) {
				cam_set = true;
				clip_shape->setCamera(r->getCamera());
			}
			stencil_scope.reset(new StencilScopeOGL(r->getStencilSettings()));
			glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
			glDepthMask(GL_FALSE);
			glClear(GL_STENCIL_BUFFER_BIT);
			render(clip_shape.get());
			stencil_scope->applyNewSettings(keep_stencil_settings);
			glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
			glDepthMask(GL_TRUE);

			if(cam_set) {
				clip_shape->setCamera(nullptr);
			}
		}

		auto shader = r->getShader();
		shader->makeActive();

		BlendEquationScopeOGL be_scope(*r);
		BlendModeScopeOGL bm_scope(*r);

		// apply lighting/depth check/depth write here.
		bool use_lighting = r->isLightingStateSet() ? r->useLighting() : false;

		// Set the depth enable.
		if(r->isDepthEnableStateSet()) {
			if(get_current_depth_enable() != r->isDepthEnabled()) {
				if(r->isDepthEnabled()) {
					glEnable(GL_DEPTH_TEST);
				} else {
					glDisable(GL_DEPTH_TEST);
				}
				get_current_depth_enable() = r->isDepthEnabled();
			}
		} else {
			// We assume that depth is disabled if not specified.
			if(get_current_depth_enable() == true) {
				glDisable(GL_DEPTH_TEST);
				get_current_depth_enable() = false;
			}
		}

		glm::mat4 pmat(1.0f);
		glm::mat4 vmat(1.0f);
		if(r->getCamera()) {
			// set camera here.
			pmat = r->getCamera()->getProjectionMat();
			vmat = r->getCamera()->getViewMat();
		} else if(get_default_camera() != nullptr) {
			pmat = get_default_camera()->getProjectionMat();
			vmat = get_default_camera()->getViewMat();
		}

		if(use_lighting) {
			for(auto lp : r->getLights()) {
				/// xxx need to set lights here.
			}
		}
		
		if(r->getRenderTarget()) {
			r->getRenderTarget()->apply();
		}

		if(shader->getPUniform() != ShaderProgram::INVALID_UNIFORM) {
			shader->setUniformValue(shader->getPUniform(), glm::value_ptr(pmat));
		}

		if(shader->getMvUniform() != ShaderProgram::INVALID_UNIFORM) {
			glm::mat4 mvmat = vmat;
			if(is_global_model_matrix_valid() && !r->ignoreGlobalModelMatrix()) {
				mvmat *= get_global_model_matrix() * r->getModelMatrix();
			} else {
				mvmat *= r->getModelMatrix();
			}
			shader->setUniformValue(shader->getMvUniform(), glm::value_ptr(mvmat));
		}

		if(shader->getMvpUniform() != ShaderProgram::INVALID_UNIFORM) {
			glm::mat4 pvmat(1.0f);
			if(is_global_model_matrix_valid() && !r->ignoreGlobalModelMatrix()) {
				pvmat = pmat * vmat * get_global_model_matrix() * r->getModelMatrix();
			} else {
				pvmat = pmat * vmat * r->getModelMatrix();
			}
			shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(pvmat));
		}

		if(shader->getColorUniform() != ShaderProgram::INVALID_UNIFORM) {
			if(r->isColorSet()) {
				shader->setUniformValue(shader->getColorUniform(), r->getColor().asFloatVector());
			} else {
				shader->setUniformValue(shader->getColorUniform(), ColorScope::getCurrentColor().asFloatVector());
			}
		}

		shader->setUniformsForTexture(r->getTexture());

		// XXX we should make this either or with setting the mvp/color uniforms above.
		auto uniform_draw_fn = shader->getUniformDrawFunction();
		if(uniform_draw_fn) {
			uniform_draw_fn(shader);
		}

		// Loop through uniform render variables and set them.
		/*for(auto& urv : r->UniformRenderVariables()) {
			for(auto& rvd : urv->VariableDescritionList()) {
				auto rvdd = std::dynamic_pointer_cast<RenderVariableDeviceData>(rvd->GetDisplayData());
				ASSERT_LOG(rvdd != nullptr, "Unable to cast DeviceData to RenderVariableDeviceData.");
				shader->SetUniformValue(rvdd->GetActiveMapIterator(), urv->Value());
			}
		}*/

		// Need to figure the interaction with shaders.
		/// XXX Need to create a mapping between attributes and the index value below.
		for(auto as : r->getAttributeSet()) {
			if(!as->isEnabled()) {
				continue;
			}
			//ASSERT_LOG(as->getCount() > 0, "No (or negative) number of vertices in attribute set. " << as->getCount());
			if((!as->isMultiDrawEnabled() && as->getCount() <= 0) || (as->isMultiDrawEnabled() && as->getMultiDrawCount() <= 0)) {
				//LOG_WARN("No (or negative) number of vertices in attribute set. " << as->getCount());
				continue;
			}
			GLenum draw_mode = convert_drawing_mode(as->getDrawMode());

			// apply blend, if any, from attribute set.
			BlendEquationScopeOGL be_scope(*as);
			BlendModeScopeOGL bm_scope(*as);

			if(shader->getColorUniform() != ShaderProgram::INVALID_UNIFORM && as->isColorSet()) {
				shader->setUniformValue(shader->getColorUniform(), as->getColor().asFloatVector());
			}

			for(auto& attr : as->getAttributes()) {
				if(attr->isEnabled()) {
					shader->applyAttribute(attr);
				}
			}

			if(as->isInstanced()) {
				if(as->isIndexed()) {
					as->bindIndex();
					// XXX as->GetIndexArray() should be as->GetIndexArray()+as->GetOffset()
					glDrawElementsInstanced(draw_mode, static_cast<GLsizei>(as->getCount()), convert_index_type(as->getIndexType()), as->getIndexArray(), as->getInstanceCount());
					as->unbindIndex();
				} else {
					glDrawArraysInstanced(draw_mode, static_cast<GLint>(as->getOffset()), static_cast<GLsizei>(as->getCount()), as->getInstanceCount());
				}
			} else {
				if(as->isIndexed()) {
					as->bindIndex();
					// XXX as->GetIndexArray() should be as->GetIndexArray()+as->GetOffset()
					glDrawElements(draw_mode, static_cast<GLsizei>(as->getCount()), convert_index_type(as->getIndexType()), as->getIndexArray());
					as->unbindIndex();
				} else {
					if(as->isMultiDrawEnabled()) {
						glMultiDrawArrays(draw_mode, as->getMultiOffsetArray().data(), as->getMultiCountArray().data(), as->getMultiDrawCount());
					} else {
						glDrawArrays(draw_mode, static_cast<GLint>(as->getOffset()), static_cast<GLsizei>(as->getCount()));
					}
				}
			}

			shader->cleanUpAfterDraw();
			glBindBuffer(GL_ARRAY_BUFFER, 0);
		}

		if(r->getRenderTarget()) {
			r->getRenderTarget()->unapply();
		}
	}
Esempio n. 18
0
//现在我们绘制贴图『译者注:其实贴图就是纹理映射。将术语换来换去不好,我想少打俩字。^_^』过的立方体。
//这段代码被狂注释了一把,应该很好懂。
//开始两行代码 glClear() 和 glLoadIdentity() 是第一课中就有的代码。
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) 清除屏幕并设为我们在 InitGL() 中选定的颜色,本例中是黑色。
//深度缓存也被清除。模型观察矩阵也使用glLoadIdentity()重置。
void MyGLWidget::paintGL()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);			// 清除屏幕和深度缓存
	glLoadIdentity();							// 重置当前的模型观察矩阵
	glTranslatef(0.0f,0.0f,mZ);						// 移入屏幕z个单位
	//下三行代码放置并旋转贴图立方体。glTranslatef(0.0f,0.0f,z)将立方体沿着Z轴移动Z单位。
	//glRotatef(xrot,1.0f,0.0f,0.0f)将立方体绕X轴旋转xrot。
	//glRotatef(yrot,0.0f,1.0f,0.0f)将立方体绕Y轴旋转yrot。
	glRotatef(mXRotate,1.0f,0.0f,0.0f);						// X轴旋转
	glRotatef(mYRotate,0.0f,1.0f,0.0f);						// Y轴旋转

	//下一行与我们在第六课中的类似。有所不同的是,这次我们绑定的纹理是texture[filter],而不是上一课中的texture[0]。
	//任何时候,我们按下F键,filter 的值就会增加。如果这个数值大于2,变量filter 将被重置为0。
	//程序初始时,变量filter 的值也将设为0。使用变量filter 我们就可以选择三种纹理中的任意一种。
	glBindTexture(GL_TEXTURE_2D, mTexture[mFilter]);				// 选择由filter决定的纹理
	//为了将纹理正确的映射到四边形上,您必须将纹理的右上角映射到四边形的右上角,纹理的左上角映射到四边形的左上角,
	//纹理的右下角映射到四边形的右下角,纹理的左下角映射到四边形的左下角。
	//如果映射错误的话,图像显示时可能上下颠倒,侧向一边或者什么都不是。
	//glTexCoord2f 的第一个参数是X坐标。 0.0f 是纹理的左侧。 0.5f 是纹理的中点, 1.0f 是纹理的右侧。
	//glTexCoord2f 的第二个参数是Y坐标。 0.0f 是纹理的底部。 0.5f 是纹理的中点, 1.0f 是纹理的顶部。
	//所以纹理的左上坐标是 X:0.0f,Y:1.0f ,四边形的左上顶点是 X: -1.0f,Y:1.0f 。其余三点依此类推。
	//试着玩玩 glTexCoord2f X, Y坐标参数。把 1.0f 改为 0.5f 将只显示纹理的左半部分,把 0.0f 改为 0.5f 将只显示纹理的右半部分。
	//glNormal3f是这一课的新东西。Normal就是法线的意思,所谓法线是指经过面(多边形)上的一点且垂直于这个面(多边形)的直线。
	//使用光源的时候必须指定一条法线。法线告诉OpenGL这个多边形的朝向,并指明多边形的正面和背面。
	//如果没有指定法线,什么怪事情都可能发生:不该照亮的面被照亮了,多边形的背面也被照亮....。对了,法线应该指向多边形的外侧。
	//看着木箱的前面您会注意到法线与Z轴正向同向。这意味着法线正指向观察者-您自己。这正是我们所希望的。
	//对于木箱的背面,也正如我们所要的,法线背对着观察者。如果立方体沿着X或Y轴转个180度的话,
	//前侧面的法线仍然朝着观察者,背面的法线也还是背对着观察者。换句话说,不管是哪个面,只要它朝着观察者这个面的法线就指向观察者。
	//由于光源紧邻观察者,任何时候法线对着观察者时,这个面就会被照亮。并且法线越朝着光源,就显得越亮一些。
	//如果您把观察点放到立方体内部,你就会法线里面一片漆黑。因为法线是向外指的。如果立方体内部没有光源的话,当然是一片漆黑。
	glBegin(GL_QUADS);
		// 前面
		glNormal3f( 0.0f, 0.0f, 1.0f);					// 法线指向观察者
		glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);	// 纹理和四边形的左下
		glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);	// 纹理和四边形的右下
		glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f,  1.0f);	// 纹理和四边形的右上
		glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f,  1.0f);	// 纹理和四边形的左上
		// 后面
		glNormal3f( 0.0f, 0.0f,-1.0f);					// 法线背向观察者
		glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);	// 纹理和四边形的右下
		glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);	// 纹理和四边形的右上
		glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);	// 纹理和四边形的左上
		glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);	// 纹理和四边形的左下
		// 顶面
		glNormal3f( 0.0f, 1.0f, 0.0f);					// 法线向上
		glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);	// 纹理和四边形的左上
		glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f,  1.0f,  1.0f);	// 纹理和四边形的左下
		glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f,  1.0f,  1.0f);	// 纹理和四边形的右下
		glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);	// 纹理和四边形的右上
		// 底面
		glNormal3f( 0.0f,-1.0f, 0.0f);					// 法线朝下
		glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);	// 纹理和四边形的右上
		glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f);	// 纹理和四边形的左上
		glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);	// 纹理和四边形的左下
		glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);	// 纹理和四边形的右下

		// 右面
		glNormal3f( 1.0f, 0.0f, 0.0f);					// 法线朝右
		glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);	// 纹理和四边形的右下
		glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f,  1.0f, -1.0f);	// 纹理和四边形的右上
		glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f,  1.0f,  1.0f);	// 纹理和四边形的左上
		glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f,  1.0f);	// 纹理和四边形的左下

		// 左面
		glNormal3f(-1.0f, 0.0f, 0.0f);					// 法线朝左
		glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);	// 纹理和四边形的左下
		glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f,  1.0f);	// 纹理和四边形的右下
		glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f,  1.0f,  1.0f);	// 纹理和四边形的右上
		glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f,  1.0f, -1.0f);	// 纹理和四边形的左上
	glEnd();

}
Esempio n. 19
0
void glutDisplay(void)   
{
	static DWORD frames = 0;
	DWORD elapsed = 0;
	static bool bInit = false;
	static LARGE_INTEGER tSetposStart,tSetposEnd;

	if(!g_pVideoMixer)	return;

	if(!bInit)
	{
		bInit  = true;
	 	QueryPerformanceFrequency(&coutFreq);
		QueryPerformanceCounter (&tSetposStart);
	}

	QueryPerformanceCounter (&tSetposEnd);
	elapsed= 1000*(tSetposEnd.QuadPart - tSetposStart.QuadPart)/coutFreq.QuadPart ;


	static char prtinfo[MAX_PATH] = {0};
	if(elapsed >2000)
	{
		sprintf(prtinfo, "fps:%d \n", frames*1000/(elapsed));
		DP(prtinfo);
		frames = 0;
		QueryPerformanceCounter (&tSetposStart);
	}
	
	frames++;

	QueryPerformanceCounter (&st);



	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


	static GLfloat rotate = 0.0f;
	rotate += 0.03f;
	if(rotate > 360)
		rotate = 0;
	
	for(int i=0;i<4;i++)
	{
		switch(i)
		{
			case 0:
				glViewport( 0, g_wndHeight/2, g_wndWidth/2, g_wndHeight/2);
				glMatrixMode(GL_PROJECTION);	
				glLoadIdentity();					
				glOrtho(-0.5,0.5, -0.5, 0.5,  0.0,100.0);

				break;
			case 1:
				glViewport( g_wndWidth/2, g_wndHeight/2, g_wndWidth/2, g_wndHeight/2);
				glMatrixMode(GL_PROJECTION);	
				glLoadIdentity();					

				gluPerspective(20,(float)g_wndWidth/(float)g_wndWidth,0.0,10.0);
				gluLookAt(0.0f,0.0f,1.0f, 
					0.0f,0.0f,0.0f, 
					0.0f,1.0f,0.0f );
				break;
			case 2:
				glViewport( 0, 0, g_wndWidth/2, g_wndHeight/2);
				glMatrixMode(GL_PROJECTION);	
				glLoadIdentity();					
				gluPerspective(20,(float)g_wndWidth/(float)g_wndWidth,0.0,10.0);
				gluLookAt(0.0f + 10*cos(rotate),0.0f,10*sin(rotate), 
					0.0f,0.0f,0.0f, 
					0.0f,1.0f,0.0f );

				break;
			case 3:
				glViewport( g_wndWidth/2, 0, g_wndWidth/2, g_wndHeight/2);
				glMatrixMode(GL_PROJECTION);	
				glLoadIdentity();					
				gluPerspective(20,(float)g_wndWidth/(float)g_wndWidth,0.0,10.0);
				gluLookAt(0.0f,4.0f,4.0f,
					0.0f,0.0f,-4.0f, 
					0.0f,0.0f,-1.0f );

				break;
			default:
				break;
		}

		glMatrixMode(GL_MODELVIEW);	
		glLoadIdentity();		

		g_pVideoMixer->Display();


	}


	glutDispMsg(prtinfo);
	glutSwapBuffers();

	QueryPerformanceCounter (&ed);
	//DP("c:%d \n", 1000*(ed.QuadPart - st.QuadPart)/coutFreq.QuadPart );
}
Esempio n. 20
0
/**
 * http://cse.csusb.edu/tongyu/courses/cs420/notes/lighting.php
 * Sombreado por medio de la técnica Gouraud Shading.
 */
int main(int argc, char* argv[])
{
	// Crear una ventana de 750x750 pixels.
	int cw = 750;
	int ch = 750;

	cg_init(cw, ch, NULL);

	// Actualizar la pantalla:
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glMatrixMode(GL_PROJECTION);
	glViewport(0,0,cw, ch);
	glFrustum(-1,1,-1,1,1,1000);

	//Habilito la iluminación del pipeline estático de OpenGL.
	glEnable(GL_LIGHTING);
    glEnable(GL_DEPTH_TEST);

    // GL_LIGHT0
    Vec4 *vec4La0 = vec4Contructor(0.10f, 0.10f, 0.10f, 1.0f);
    Vec4 *vec4Ld0 = vec4Contructor(1.0f, 1.0f, 1.0f, 1.0f);
    Vec4 *vec4Ls0 = vec4Contructor(1.0f, 1.0f, 1.0f, 1.0f);
    Vec4 *vec4Lp0 = vec4Contructor(1.0f, 1.0f, 1.0f, 0.0f);
    loadLight(GL_LIGHT0, vec4La0, vec4Ld0, vec4Lp0, vec4Ls0);

    // GL_LIGHT1
    Vec4 *vec4La1 = vec4Contructor(0.5f,0.5f,0.5f,1.0f);
    Vec4 *vec4Ld1 = vec4Contructor(0.5f, 0.3f, 0.2f, 1.0f);
    Vec4 *vec4Ls1 = vec4Contructor(1.0f,1.0f,1.0f,1.0f);
    Vec4 *vec4Lp1 = vec4Contructor(1.0f, 1.0f, 1.0f, 0.0f);
    loadLight(GL_LIGHT1, vec4La1, vec4Ld1, vec4Lp1, vec4Ls1);
//    GLfloat spot_direction[] = { -1.0, -1.0, 0.0 };
//    glLightf(GL_LIGHT1, GL_CONSTANT_ATTENUATION, 1.5);
//    glLightf(GL_LIGHT1, GL_LINEAR_ATTENUATION, 0.5);
//    glLightf(GL_LIGHT1, GL_QUADRATIC_ATTENUATION, 0.2);
//    glLightf(GL_LIGHT1, GL_SPOT_CUTOFF, 45.0);
//    glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, spot_direction);
//    glLightf(GL_LIGHT1, GL_SPOT_EXPONENT, 2.0);

    // GL_LIGHT2
    Vec4 *vec4La2 = vec4Contructor( 0.2f, 0.2f, 0.2f, 1.0f);
    Vec4 *vec4Ld2 = vec4Contructor(0.8f, 0.8f, 0.8, 1.0f );
    Vec4 *vec4Lp2 = vec4Contructor(-1.5f, 1.0f, -4.0f, 1.0f );
    Vec4 *vec4Ls2 = vec4Contructor(0.5f, 0.5f, 0.5f, 1.0f );
    loadLight(GL_LIGHT2, vec4La2, vec4Ld2, vec4Lp2, vec4Ls2);


    // TODO, GL_LIGHT3, GL_LIGHT4, GL_LIGHT5, GL_LIGHT6, GL_LIGHT7

    Obj* obj = obj_load("../Models/knight.obj");

	float ang = 0.0f;
	float pitch = 0.0f;
	float ang_vel = 1.0f;

	char done = 0;
	char wireframe = 0;
	char gourandShading = 0;
	char bfc = 0;
	char zbuff = 1;
    char enableLight0 = 0;
    char enableLight1 = 0;
    char enableLight2 = 0;
    char enableLight3 = 0;
    char enableLight4 = 0;
    char enableLight5 = 0;
    char enableLight6 = 0;
    char enableLight7 = 0;
	unsigned char key_pressed[1024];
	memset(key_pressed, 0, 1024);

	while (!done)
	{
		SDL_Event event;
		while(SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				case SDL_KEYDOWN:
					key_pressed[event.key.keysym.sym] = 1;

					if (event.key.keysym.sym == SDLK_z)
					{
						zbuff = !zbuff;
						if(zbuff)
							glEnable(GL_DEPTH_TEST);
						else
							glDisable(GL_DEPTH_TEST);
						break;
					}
					else if (event.key.keysym.sym == SDLK_b)
					{
						bfc = !bfc;
						if(bfc)
						{
							glEnable(GL_CULL_FACE);
							glCullFace(GL_BACK);
							glFrontFace(GL_CW);
						}
						else
							glDisable(GL_CULL_FACE);
						break;
					}
					else if (event.key.keysym.sym == SDLK_m)
					{
						wireframe = !wireframe;
						if(wireframe)
							glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
						else
							glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
						break;
					}
                    else if (event.key.keysym.sym == SDLK_g)
                    {
                        gourandShading = !gourandShading;
                        if(gourandShading)
                            glShadeModel(GL_FLAT);
                        else
                            glShadeModel(GL_SMOOTH);
                        break;
                    }
                    else if (event.key.keysym.sym == SDLK_0)
                    {
                        enableLight0 = !enableLight0;
                        if(enableLight0) glEnable(GL_LIGHT0);
                        else glDisable(GL_LIGHT0);
                        break;
                    }
                    else if (event.key.keysym.sym == SDLK_1)
                    {
                        enableLight1 = !enableLight1;
                        if(enableLight1) glEnable(GL_LIGHT1);
                        else glDisable(GL_LIGHT1);
                        break;
                    }
                    else if (event.key.keysym.sym == SDLK_2)
                    {
                        enableLight2 = !enableLight2;
                        if(enableLight2) glEnable(GL_LIGHT2);
                        else glDisable(GL_LIGHT2);
                        break;
                    }
                    else if (event.key.keysym.sym == SDLK_3)
                    {
                        enableLight3 = !enableLight3;
                        if(enableLight3) glEnable(GL_LIGHT3);
                        else glDisable(GL_LIGHT3);
                        break;
                    }
                    else if (event.key.keysym.sym == SDLK_4)
                    {
                        enableLight4 = !enableLight4;
                        if(enableLight4) glEnable(GL_LIGHT4);
                        else glDisable(GL_LIGHT4);
                        break;
                    }
                    else if (event.key.keysym.sym == SDLK_5)
                    {
                        enableLight5 = !enableLight5;
                        if(enableLight5) glEnable(GL_LIGHT5);
                        else glDisable(GL_LIGHT5);
                        break;
                    }
                    else if (event.key.keysym.sym == SDLK_6)
                    {
                        enableLight6 = !enableLight6;
                        if(enableLight6) glEnable(GL_LIGHT6);
                        else glDisable(GL_LIGHT6);
                        break;
                    }
                    else if (event.key.keysym.sym == SDLK_7)
                    {
                        enableLight7 = !enableLight7;
                        if(enableLight7) glEnable(GL_LIGHT7);
                        else glDisable(GL_LIGHT7);
                        break;
                    }
					else if (event.key.keysym.sym != SDLK_ESCAPE)
						break;
				case SDL_QUIT :
					done = 1;
					break;
				case SDL_KEYUP:
					key_pressed[event.key.keysym.sym] = 0;

			}
		}

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glTranslatef(0.0f, 0.0f, -50.0f);
		glRotatef(pitch, 1.0f, 0.0f, 0.0f);
		glRotatef(ang, 0.0f, 1.0f, 0.0f);
		glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);

		if(key_pressed[SDLK_RIGHT]) ang += ang_vel;
		if(key_pressed[SDLK_LEFT]) ang -= ang_vel;
		if(key_pressed[SDLK_UP]) pitch += ang_vel;
		if(key_pressed[SDLK_DOWN]) pitch -= ang_vel;

		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
		obj_render(obj);
		cg_repaint();
	}

	// Liberar recursos:

    obj_free(obj);
	cg_close();

	return 0;
}
Esempio n. 21
0
void RadarCanvas::Render(wxPaintEvent &evt) {
  int w, h;

  if (!IsShown() || !m_pi->m_initialized) {
    return;
  }

  GetClientSize(&w, &h);
  wxPaintDC(this);  // only to be used in paint events. use wxClientDC to paint
                    // outside the paint event

  if (!m_pi->m_opengl_mode) {
    LOG_DIALOG(wxT("BR24radar_pi: %s cannot render non-OpenGL mode"), m_ri->m_name.c_str());
    return;
  }
  if (!m_pi->m_opencpn_gl_context && !m_pi->m_opencpn_gl_context_broken) {
    LOG_DIALOG(wxT("BR24radar_pi: %s skip render as no context known yet"), m_ri->m_name.c_str());
    return;
  }
  LOG_DIALOG(wxT("BR24radar_pi: %s render OpenGL canvas %d by %d "), m_ri->m_name.c_str(), w, h);

  SetCurrent(*m_context);

  glPushMatrix();
  glPushAttrib(GL_ALL_ATTRIB_BITS);

  wxFont font = GetOCPNGUIScaledFont_PlugIn(_T("StatusBar"));
  m_FontNormal.Build(font);
  wxFont bigFont = GetOCPNGUIScaledFont_PlugIn(_T("Dialog"));
  bigFont.SetPointSize(bigFont.GetPointSize() + 2);
  bigFont.SetWeight(wxFONTWEIGHT_BOLD);
  m_FontBig.Build(bigFont);
  bigFont.SetPointSize(bigFont.GetPointSize() + 2);
  bigFont.SetWeight(wxFONTWEIGHT_NORMAL);
  m_FontMenu.Build(bigFont);
  bigFont.SetPointSize(bigFont.GetPointSize() + 10);
  bigFont.SetWeight(wxFONTWEIGHT_BOLD);
  m_FontMenuBold.Build(bigFont);

  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);                // Black Background
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);  // Clear the canvas
  glEnable(GL_TEXTURE_2D);                             // Enable textures
  glEnable(GL_COLOR_MATERIAL);
  glEnable(GL_BLEND);
  // glDisable(GL_DEPTH_TEST);
  glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

  glViewport(0, 0, w, h);
  glMatrixMode(GL_PROJECTION);  // Next two operations on the project matrix stack
  glLoadIdentity();             // Reset projection matrix stack
  glOrtho(0, w, h, 0, -1, 1);
  glMatrixMode(GL_MODELVIEW);  // Reset matrick stack target back to GL_MODELVIEW

  RenderRangeRingsAndHeading(w, h);
  Render_EBL_VRM(w, h);

  glViewport(0, 0, w, h);
  glMatrixMode(GL_PROJECTION);  // Next two operations on the project matrix stack
  glLoadIdentity();             // Reset projection matrix stack
  if (w >= h) {
    glScaled(1.0, (float)-w / h, 1.0);
  } else {
    glScaled((float)h / w, -1.0, 1.0);
  }
  glMatrixMode(GL_MODELVIEW);  // Reset matrick stack target back to GL_MODELVIEW

  m_ri->RenderRadarImage(wxPoint(0, 0), 1.0, 0.0, false);

  glViewport(0, 0, w, h);
  glMatrixMode(GL_PROJECTION);  // Next two operations on the project matrix stack
  glLoadIdentity();             // Reset projection matrix stack
  glOrtho(0, w, h, 0, -1, 1);
  glMatrixMode(GL_MODELVIEW);  // Reset matrick stack target back to GL_MODELVIEW

  glEnable(GL_TEXTURE_2D);

  RenderTexts(w, h);
  RenderCursor(w, h);

#ifdef NEVER
  glDisable(GL_TEXTURE_2D);

  glMatrixMode(GL_PROJECTION);  // Next two operations on the project matrix stack
  glLoadIdentity();             // Reset projection matrix stack
  glMatrixMode(GL_MODELVIEW);   // Reset matrick stack target back to GL_MODELVIEW
#endif

  glPopAttrib();
  glPopMatrix();
  glFlush();
  glFinish();
  SwapBuffers();

  if (m_pi->m_opencpn_gl_context) {
    SetCurrent(*m_pi->m_opencpn_gl_context);
  } else {
    SetCurrent(*m_zero_context);  // Make sure OpenCPN -at least- doesn't overwrite our context info
  }
}
Esempio n. 22
0
void NBodyWorldApp::draw(){
    long tstart = getCPUticks();
    glClearColor( 0.9f, 0.9f, 0.9f, 0.0f );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    long t1 = getCPUticks();
    world.update();
    long t2 = getCPUticks();

    Vec2d pa,pb,fout; pa.set(0.0,0.0); pb.set(0.0,0.0);
    int nsamp = 100;
    double dx = 4.0/nsamp;
    double ox = 0;
    double oy = 0;
    glColor3f( 0.9f, 0.2f, 0.2f ); ox=0; oy=0; for( int i=0; i<nsamp; i++ ){ pb.x = i * dx; pairwiseForce( pa, pb, -1, fout ); double x=pb.x*5;double y=-0.2*fout.x; Draw2D::drawLine_d( {ox,oy},{x,y} ); ox=x; oy=y; }
    glColor3f( 0.2f, 0.2f, 0.2f ); ox=0; oy=0; for( int i=0; i<nsamp; i++ ){ pb.x = i * dx; pairwiseForce( pa, pb,  0, fout ); double x=pb.x*5;double y=-0.2*fout.x; Draw2D::drawLine_d( {ox,oy},{x,y} ); ox=x; oy=y; }
    glColor3f( 0.2f, 0.2f, 0.9f ); ox=0; oy=0; for( int i=0; i<nsamp; i++ ){ pb.x = i * dx; pairwiseForce( pa, pb, +1, fout ); double x=pb.x*5;double y=-0.2*fout.x; Draw2D::drawLine_d( {ox,oy},{x,y} ); ox=x; oy=y; }
    glColor3f( 0.2f, 0.2f, 0.2f );
    Draw2D::drawLine_d( {0.0,-10.0},{0.0,+10.0} );
    Draw2D::drawLine_d( {-10.0,0.0},{+10.0,0.0} );


    Particle2D* screenObjects[65536];

/*
    glColor3f( 0.2f, 0.2f, 0.2f );
    for( int i=0; i<world.nParticles; i++ ){
        Particle2D* pi = &(world.particles[i]);
        ULONG icell = world.map.getBucket( pi->pos.x, pi->pos.y );
        double x,y;
        world.map.unfoldBucket( icell, x, y );
        Draw2D::drawRectangle( (float)x, (float)y, (float)(x+world.map.step), (float)(y+world.map.step), false );
    }
*/

    glColor3f( 0.2f, 0.2f, 0.2f );
    for( ULONG icell : world.activeCells ){
        double x,y;
        world.map.unfoldBucket( icell, x, y );
        Draw2D::drawRectangle( (float)x, (float)y, (float)(x+world.map.step), (float)(y+world.map.step), false );
/*
        UINT nfound = world.map.HashMap<Particle2D>::getBucketObjects( icell, screenObjects );
        if( nfound <= 0 ){
            UHALF ix,iy;
            world.map.unfoldBucketInt( icell, ix, iy );
            printf( "!!! activeCell %i=(%i,%i) is empty\n", icell, ix, iy  );
            int i= 97; printf( "!!! particle %i-th (%3.3f,%3.3f) \n", i, world.particles[i].pos.x, world.particles[i].pos.y  );
            exit(0);
        }
*/
    }


    glColor3f( 0.7f, 0.7f, 0.7f );
    for( ULONG icell : world.activeCellsNeighbors ){
        double x,y;
        world.map.unfoldBucket( icell, x, y );
        Draw2D::drawRectangle( (float)x, (float)y, (float)(x+world.map.step), (float)(y+world.map.step), false );
    }

/*
    glColor3f( 0.9f, 0.9f, 0.9f );
    for( int i=0; i<world.nActiveParticles; i++ ){
        Draw2D::drawPointCross_d( world.activeParticles[i]->pos, 0.5 );
    }
*/

    //float camXmin_ =-1; float camXmax_ =+1;
    //float camYmin_ =-1; float camYmax_ =+1;
    float camXmin_ =camXmin; float camXmax_ =camXmax;
    float camYmin_ =camYmin; float camYmax_ =camYmax;
/*
    Draw2D::drawRectangle( camXmin_, camYmin_, camXmax_, camYmax_, false );
	UINT nfound = world.map.getObjectsInRect( camXmin_, camYmin_, camXmax_, camYmax_, &(screenObjects[0]) );
	//glBegin(GL_POINTS);
	for( int i=0; i<nfound; i++ ){
        Particle2D* p = screenObjects[i];
		//glVertex3f( (float) p->pos.x, (float)p->pos.y, 1.0f );
		Draw2D::drawCircle_d( p->pos, 0.25, 8, true );
	}
	//glEnd();
	printf( "nfound %i filled %i \n", nfound, world.map.filled );
*/
    UHALF ix0 = world.map.getIx( camXmin_ );  UHALF iy0 = world.map.getIy( camYmin_ );
    UHALF ix1 = world.map.getIx( camXmax_ );  UHALF iy1 = world.map.getIy( camYmax_ );
    UINT nfound_tot = 0;
    int ncells  = 0;
    for( UHALF iy = iy0; iy<=iy1; iy++ ){
        for( UHALF ix = ix0; ix<=ix1; ix++ ){
            UINT nfoundi = world.map.getBucketObjectsInt( ix, iy, screenObjects );
            nfound_tot += nfoundi;
            for( int i=0; i<nfoundi; i++ ){
                Particle2D* p = screenObjects[i];
                if( p->charge > 0 ){ glColor3f( 0.0f, 0.5f, 1.0f ); }else{ glColor3f( 1.0f, 0.5f, 0.0f ); }
                Draw2D::drawCircle_d( p->pos, 0.5, 8, true );

                //Vec2d pos_f; pos_f.set_mul( p->force, 1.0 ); pos_f.add( p->pos );
                //Draw2D::drawLine_d( p->pos, pos_f );
            }
            /*
            if( nfoundi > 0 ){
                glColor3f( 0.3f, 0.3f, 0.3f );
                double x = world.map.getX(ix);
                double y = world.map.getY(iy);
                Draw2D::drawRectangle( (float)x, (float)y, (float)(x+world.map.step), (float)(y+world.map.step), false );
            }
            */
            //printf( " ix %i iy %i  \n", ix, iy, ni );
        }
    }

    Draw2D::drawPointCross_d( world.anchor, 0.5 );
    if( world.picked != NULL ) Draw2D::drawLine_d( world.anchor, world.picked->pos );

    long tend = getCPUticks();

    //printf( " ======== frame %i DONE ( map.filled %i nfound_tot %i )\n", frameCount, world.map.filled, nfound_tot );
    printf( " ======== frame %i DONE T=%3.3f Mticks/frame( %3.3f Mticks simulation )\n", frameCount, (tend-tstart)*1.0e-6, (t2-t1)*1.0e-6 );
	//STOP = true;

};
Esempio n. 23
0
void AlignPairWidget::paintEvent(QPaintEvent *)
{
  QPainter painter(this);
  painter.beginNativePainting();
  makeCurrent();
  if(!isValid() )return;

  glEnable(GL_DEPTH_TEST);
  glDepthMask(GL_TRUE);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    if(freeMesh==0 || gluedTree==0) return;

    for(int i=0;i<2;++i)
    {
      if(i==0)
        glViewport (0, 0, (GLsizei) QTLogicalToDevice(this,width()/2), (GLsizei) QTLogicalToDevice(this,height()));
      else
        glViewport (QTLogicalToDevice(this,width()/2), 0, (GLsizei) QTLogicalToDevice(this,width()/2), (GLsizei) QTLogicalToDevice(this,height()));

      glMatrixMode(GL_PROJECTION);
      glLoadIdentity();
      gluPerspective(30, (AlignPairWidget::width()/2)/(float)AlignPairWidget::height(), 0.1, 100);
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
      gluLookAt(0,0,6,   0,0,0,   0,1,0);
      tt[i]->center=vcg::Point3f(0, 0, 0);
      tt[i]->radius= 1;
      tt[i]->GetView();
      tt[i]->Apply();
      vcg::Box3f bb;
      if(i==0) bb=freeMesh->bbox();
      else	   bb=gluedTree->gluedBBox();
      vcg::GLW::DrawMode localDM=vcg::GLW::DMFlat;
      vcg::GLW::ColorMode localCM = vcg::GLW::CMPerMesh;
      if((freeMesh->m->hasDataMask(MeshModel::MM_VERTCOLOR))&&(isUsingVertexColor)) localCM = vcg::GLW::CMPerVert;
      if((freeMesh->m->cm.fn==0)||(usePointRendering)) localDM=vcg::GLW::DMPoints;
      glPushMatrix();
      bool allowScaling = qobject_cast<AlignPairDialog *>(parent())->allowScalingCB->isChecked();
      if(allowScaling)  vcg::glScale(3.0f/bb.Diag());
      else vcg::glScale(3.0f/gluedTree->gluedBBox().Diag());
      vcg::glTranslate(-bb.Center());
      if(i==0)
      {
        freeMesh->m->render(localDM,localCM,vcg::GLW::TMNone);
        drawPickedPoints(&painter, freePickedPointVec,vcg::Color4b(vcg::Color4b::Red));
      } else				{
        foreach(MeshNode *mn, gluedTree->nodeList)
          if(mn->glued && mn != freeMesh && mn->m->visible) mn->m->render(localDM,localCM,vcg::GLW::TMNone);
        drawPickedPoints(&painter, gluedPickedPointVec,vcg::Color4b(vcg::Color4b::Blue));
      }

      int pickSide= ( pointToPick[0] < QTLogicalToDevice(this,(width()/2)) )? 0 : 1;
      if(hasToPick && pickSide==i)
      {
        vcg::Point3f pp;
        hasToPick=false;
        if(vcg::Pick<vcg::Point3f>(pointToPick[0],pointToPick[1],pp))
        {
          std::vector<vcg::Point3f> &curVec = pickSide?gluedPickedPointVec:freePickedPointVec;

          qDebug("Picked point %i %i -> %f %f %f",pointToPick[0],pointToPick[1],pp[0],pp[1],pp[2]);

          if(hasToDelete)
          {
            int bestInd = -1;
            double bestDist =10e100;
            for(int i=0;i<curVec.size();++i)
              if(Distance(pp,curVec[i])<bestDist)
              {
                bestDist = Distance(pp,curVec[i]);
                bestInd=i;
              }
            hasToDelete=false;
            if(bestInd>=0)
              curVec.erase(curVec.begin()+bestInd);
          }
          else curVec.push_back(pp);
          hasToPick=false;
          update();
        }
      }
      glPopMatrix();
      tt[i]->DrawPostApply();
    }
    doneCurrent();
    painter.endNativePainting();
}
void CARenderImage::draw()
{
    if( m_bAutoDraw)
    {
        begin();
		
        if (m_uClearFlags)
        {
            GLfloat oldClearColor[4] = {0.0f};
			GLfloat oldDepthClearValue = 0.0f;
			GLint oldStencilClearValue = 0;
			
			// backup and set
			if (m_uClearFlags & GL_COLOR_BUFFER_BIT)
            {
				glGetFloatv(GL_COLOR_CLEAR_VALUE, oldClearColor);
				glClearColor(m_sClearColor.r, m_sClearColor.g, m_sClearColor.b, m_sClearColor.a);
			}
			
			if (m_uClearFlags & GL_DEPTH_BUFFER_BIT)
            {
				glGetFloatv(GL_DEPTH_CLEAR_VALUE, &oldDepthClearValue);
				glClearDepth(m_fClearDepth);
			}
			
			if (m_uClearFlags & GL_STENCIL_BUFFER_BIT)
            {
				glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &oldStencilClearValue);
				glClearStencil(m_nClearStencil);
			}
			
			// clear
			glClear(m_uClearFlags);
			
			// restore
			if (m_uClearFlags & GL_COLOR_BUFFER_BIT)
            {
				glClearColor(oldClearColor[0], oldClearColor[1], oldClearColor[2], oldClearColor[3]);
            }
			if (m_uClearFlags & GL_DEPTH_BUFFER_BIT)
            {
				glClearDepth(oldDepthClearValue);
            }
			if (m_uClearFlags & GL_STENCIL_BUFFER_BIT)
            {
				glClearStencil(oldStencilClearValue);
            }
		}
		
		//! make sure all children are drawn
        sortAllSubviews();
		
        CAVector<CAView*>::const_iterator itr;
        for (itr=m_obSubviews.begin(); itr!=m_obSubviews.end(); itr++)
        {
            (*itr)->visit();
        }

        end();
	}
}
void RenderingContext::prepareFrame() {
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	camera.updateViewProjectMatrix();
}
/*!****************************************************************************
 @Function		RenderScene
 @Return		bool		true if no error occured
 @Description	Main rendering loop function of the program. The shell will
				call this function every frame.
				eglSwapBuffers() will be performed by PVRShell automatically.
				PVRShell will also manage important OS events.
				Will also manage relevent OS events. The user has access to
				these events through an abstraction layer provided by PVRShell.
******************************************************************************/
bool OGLESIntroducingPFX::RenderScene()
{
	// Clears the color and depth buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Use the loaded effect
	m_pEffect->Activate();

	/*
		Calculates the frame number to animate in a time-based manner.
		Uses the shell function PVRShellGetTime() to get the time in milliseconds.
	*/
	int iTime = PVRShellGetTime();
	int iDeltaTime = iTime - m_iTimePrev;
	m_iTimePrev	= iTime;
	m_fFrame	+= (float)iDeltaTime * DEMO_FRAME_RATE;
	if (m_fFrame > m_Scene.nNumFrame-1)
		m_fFrame = 0;

	// Sets the scene animation to this frame
	m_Scene.SetFrame(m_fFrame);

	{
		PVRTVec3	vFrom, vTo, vUp;
		VERTTYPE	fFOV;
		vUp.x = 0.0f;
		vUp.y = 1.0f;
		vUp.z = 0.0f;

		// We can get the camera position, target and field of view (fov) with GetCameraPos()
		fFOV = m_Scene.GetCameraPos(vFrom, vTo, 0) * 0.4f;

		/*
			We can build the world view matrix from the camera position, target and an up vector.
			For this we use PVRTMat4LookAtRH().
		*/
		m_mView = PVRTMat4::LookAtRH(vFrom, vTo, vUp);

		// Calculates the projection matrix
		bool bRotate = PVRShellGet(prefIsRotated) && PVRShellGet(prefFullScreen);
		m_mProjection = PVRTMat4::PerspectiveFovRH(fFOV, (float)PVRShellGet(prefWidth)/(float)PVRShellGet(prefHeight), CAM_NEAR, CAM_FAR, PVRTMat4::OGL, bRotate);
	}

	/*
		A scene is composed of nodes. There are 3 types of nodes:
		- MeshNodes :
			references a mesh in the pMesh[].
			These nodes are at the beginning of the pNode[] array.
			And there are nNumMeshNode number of them.
			This way the .pod format can instantiate several times the same mesh
			with different attributes.
		- lights
		- cameras
		To draw a scene, you must go through all the MeshNodes and draw the referenced meshes.
	*/
	for (int i=0; i<(int)m_Scene.nNumMeshNode; i++)
	{
		SPODNode* pNode = &m_Scene.pNode[i];

		// Gets pMesh referenced by the pNode
		SPODMesh* pMesh = &m_Scene.pMesh[pNode->nIdx];

		glBindBuffer(GL_ARRAY_BUFFER, m_aiVboID[i]);

		// Gets the node model matrix
		PVRTMat4 mWorld;
		mWorld = m_Scene.GetWorldMatrix(*pNode);

		PVRTMat4 mWorldView;
		mWorldView = m_mView * mWorld;

		for(unsigned int j = 0; j < m_nUniformCnt; ++j)
		{
			switch(m_psUniforms[j].nSemantic)
			{
			case eUsPOSITION:
				{
					glVertexAttribPointer(m_psUniforms[j].nLocation, 3, GL_FLOAT, GL_FALSE, pMesh->sVertex.nStride, pMesh->sVertex.pData);
					glEnableVertexAttribArray(m_psUniforms[j].nLocation);
				}
				break;
			case eUsNORMAL:
				{
					glVertexAttribPointer(m_psUniforms[j].nLocation, 3, GL_FLOAT, GL_FALSE, pMesh->sNormals.nStride, pMesh->sNormals.pData);
					glEnableVertexAttribArray(m_psUniforms[j].nLocation);
				}
				break;
			case eUsUV:
				{
					glVertexAttribPointer(m_psUniforms[j].nLocation, 2, GL_FLOAT, GL_FALSE, pMesh->psUVW[0].nStride, pMesh->psUVW[0].pData);
					glEnableVertexAttribArray(m_psUniforms[j].nLocation);
				}
				break;
			case eUsWORLDVIEWPROJECTION:
				{
					PVRTMat4 mWVP;

					/* Passes the world-view-projection matrix (WVP) to the shader to transform the vertices */
					mWVP = m_mProjection * mWorldView;
					glUniformMatrix4fv(m_psUniforms[j].nLocation, 1, GL_FALSE, mWVP.f);
				}
				break;
			case eUsWORLDVIEWIT:
				{
					PVRTMat4 mWorldViewI, mWorldViewIT;

					/* Passes the inverse transpose of the world-view matrix to the shader to transform the normals */
					mWorldViewI  = mWorldView.inverse();
					mWorldViewIT = mWorldViewI.transpose();

					PVRTMat3 WorldViewIT = PVRTMat3(mWorldViewIT);

					glUniformMatrix3fv(m_psUniforms[j].nLocation, 1, GL_FALSE, WorldViewIT.f);
				}
				break;
			case eUsLIGHTDIREYE:
				{
					// Reads the light direction from the scene.
					PVRTVec4 vLightDirection;
					PVRTVec3 vPos;
					vLightDirection = m_Scene.GetLightDirection(0);

					vLightDirection.x = -vLightDirection.x;
					vLightDirection.y = -vLightDirection.y;
					vLightDirection.z = -vLightDirection.z;

					/*
						Sets the w component to 0, so when passing it to glLight(), it is
						considered as a directional light (as opposed to a spot light).
					*/
					vLightDirection.w = 0;

					// Passes the light direction in eye space to the shader
					PVRTVec4 vLightDirectionEyeSpace;
					vLightDirectionEyeSpace = m_mView * vLightDirection;

					glUniform3f(m_psUniforms[j].nLocation, vLightDirectionEyeSpace.x, vLightDirectionEyeSpace.y, vLightDirectionEyeSpace.z);
				}
				break;
			case eUsTEXTURE:
				{
					// Set the sampler variable to the texture unit
					glUniform1i(m_psUniforms[j].nLocation, m_psUniforms[j].nIdx);
				}
				break;
			}
		}

		/*
			Now that the model-view matrix is set and the materials ready,
			call another function to actually draw the mesh.
		*/
		DrawMesh(pMesh);
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		for(unsigned int j = 0; j < m_nUniformCnt; ++j)
		{
			switch(m_psUniforms[j].nSemantic)
			{
			case eUsPOSITION:
				{
					glDisableVertexAttribArray(m_psUniforms[j].nLocation);
				}
				break;
			case eUsNORMAL:
				{
					glDisableVertexAttribArray(m_psUniforms[j].nLocation);
				}
				break;
			case eUsUV:
				{
					glDisableVertexAttribArray(m_psUniforms[j].nLocation);
				}
				break;
			}
		}
	}

	// Displays the demo name using the tools. For a detailed explanation, see the training course IntroducingPVRTools
	m_Print3D.DisplayDefaultTitle("IntroducingPFX", "", ePVRTPrint3DLogoIMG);
	m_Print3D.Flush();

	return true;
}
Esempio n. 27
0
void test_triangle_smoothed(GLenum mode)
{
	GLint width, height;

	GLfloat vVertices[] = {
			 0.0f,  0.5f, 0.0f,
			-0.5f, -0.5f, 0.0f,
			 0.5f, -0.5f, 0.0f };
	GLfloat vColors[] = {
			1.0f, 0.0f, 0.0f, 1.0f,
			0.0f, 1.0f, 0.0f, 1.0f,
			0.0f, 0.0f, 1.0f, 1.0f};
	EGLSurface surface;

	RD_START("triangle-smoothed", "");

	display = get_display();

	/* get an appropriate EGL frame buffer configuration */
	ECHK(eglChooseConfig(display, config_attribute_list, &config, 1, &num_config));
	DEBUG_MSG("num_config: %d", num_config);

	/* create an EGL rendering context */
	ECHK(context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attribute_list));

	surface = make_window(display, config, 400, 240);

	ECHK(eglQuerySurface(display, surface, EGL_WIDTH, &width));
	ECHK(eglQuerySurface(display, surface, EGL_HEIGHT, &height));

	DEBUG_MSG("Buffer: %dx%d", width, height);

	/* connect the context to the surface */
	ECHK(eglMakeCurrent(display, surface, surface, context));

	program = get_program(vertex_shader_source, fragment_shader_source);

	GCHK(glBindAttribLocation(program, 0, "aPosition"));
	GCHK(glBindAttribLocation(program, 1, "aColor"));

	link_program(program);

	GCHK(glViewport(0, 0, width, height));

	GCHK(glFrontFace(mode));

	/* clear the color buffer */
	GCHK(glClearColor(0.0, 0.0, 0.0, 1.0));
	GCHK(glClear(GL_COLOR_BUFFER_BIT));

	GCHK(glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices));
	GCHK(glEnableVertexAttribArray(0));

	GCHK(glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, vColors));
	GCHK(glEnableVertexAttribArray(1));

	GCHK(glDrawArrays(GL_TRIANGLES, 0, 3));

	ECHK(eglSwapBuffers(display, surface));
	GCHK(glFlush());

	ECHK(eglDestroySurface(display, surface));

	ECHK(eglTerminate(display));

	RD_END();
}
Esempio n. 28
0
int main () {
	/*--------------------------------START OPENGL---------------------------*/
	assert (restart_gl_log ());
	// start GL context and O/S window using the GLFW helper library
	assert (start_gl ());
	glEnable (GL_DEPTH_TEST); // enable depth-testing
    // depth-testing interprets a smaller value as "closer"
	glDepthFunc (GL_LESS);
    glEnable (GL_CULL_FACE); // cull face
	glCullFace (GL_BACK); // cull back face
    // set counter-clock-wise vertex order to mean the front
	glFrontFace (GL_CCW);
    glClearColor (0.2, 0.2, 0.2, 1.0); // grey background to help spot mistakes
	glViewport (0, 0, g_gl_width, g_gl_height);
	
/*------------------------------CREATE GEOMETRY------------------------------*/
	GLfloat* vp = NULL; // array of vertex points
	GLfloat* vn = NULL; // array of vertex normals
	GLfloat* vt = NULL; // array of texture coordinates
	int g_point_count = 0;
	assert (load_obj_file (MESH_FILE, vp, vt, vn, g_point_count));

	GLuint vao;
	glGenVertexArrays (1, &vao);
	glBindVertexArray (vao);

	GLuint points_vbo;
	if (NULL != vp) {
		glGenBuffers (1, &points_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
		glBufferData (GL_ARRAY_BUFFER, 3 * g_point_count * sizeof (GLfloat),
                      vp, GL_STATIC_DRAW);
		glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (0);
	}
	GLuint normals_vbo;
	if (NULL != vn) {
		glGenBuffers (1, &normals_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, normals_vbo);
		glBufferData (GL_ARRAY_BUFFER, 3 * g_point_count * sizeof (GLfloat),
                      vn, GL_STATIC_DRAW);
		glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (1);
	}
	GLuint texcoords_vbo;
	if (NULL != vp) {
		glGenBuffers (1, &texcoords_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo);
		glBufferData (GL_ARRAY_BUFFER, 2 * g_point_count * sizeof (GLfloat),
                      vp, GL_STATIC_DRAW);
		glVertexAttribPointer (2, 2, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (2);
	}
	
/*-------------------------------CREATE SHADERS------------------------------*/
	GLuint shader_programme = create_programme_from_files (VERTEX_SHADER_FILE,
		FRAGMENT_SHADER_FILE);
	int view_mat_location = glGetUniformLocation (shader_programme, "view");
	int proj_mat_location = glGetUniformLocation (shader_programme, "proj");
	
	/* if converting to GLSL 410 do this to replace GLSL texture bindings:
	GLint diffuse_map_loc, specular_map_loc, ambient_map_loc, emission_map_loc;
	diffuse_map_loc = glGetUniformLocation (shader_programme, "diffuse_map");
	specular_map_loc = glGetUniformLocation (shader_programme, "specular_map");
	ambient_map_loc = glGetUniformLocation (shader_programme, "ambient_map");
	emission_map_loc = glGetUniformLocation (shader_programme, "emission_map");
	assert (diffuse_map_loc > -1);
	assert (specular_map_loc > -1);
	assert (ambient_map_loc > -1);
	assert (emission_map_loc > -1);
	glUseProgram (shader_programme);
	glUniform1i (diffuse_map_loc, 0);
	glUniform1i (specular_map_loc, 1);
	glUniform1i (ambient_map_loc, 2);
	glUniform1i (emission_map_loc, 3);
	*/
	
	// load texture
	GLuint tex_diff, tex_spec, tex_amb, tex_emiss;
	glActiveTexture (GL_TEXTURE0);
	assert (load_texture ("boulder_diff.png", &tex_diff));
	glActiveTexture (GL_TEXTURE1);
	assert (load_texture ("boulder_spec.png", &tex_spec));
	glActiveTexture (GL_TEXTURE2);
	assert (load_texture ("ao.png", &tex_amb));
	glActiveTexture (GL_TEXTURE3);
	assert (load_texture ("tileable9b_emiss.png", &tex_emiss));
	
	#define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444
	// input variables
	float near = 0.1f; // clipping plane
	float far = 100.0f; // clipping plane
	float fov = 67.0f * ONE_DEG_IN_RAD; // convert 67 degrees to radians
	float aspect = (float)g_gl_width / (float)g_gl_height; // aspect ratio
	// matrix components
	float range = tan (fov * 0.5f) * near;
	float Sx = (2.0f * near) / (range * aspect + range * aspect);
	float Sy = near / range;
	float Sz = -(far + near) / (far - near);
	float Pz = -(2.0f * far * near) / (far - near);
	GLfloat proj_mat[] = {
		Sx, 0.0f, 0.0f, 0.0f,
		0.0f, Sy, 0.0f, 0.0f,
		0.0f, 0.0f, Sz, -1.0f,
		0.0f, 0.0f, Pz, 0.0f
	};
	
		
	float cam_speed = 1.0f; // 1 unit per second
	float cam_yaw_speed = 10.0f; // 10 degrees per second
    // don't start at zero, or we will be too close
	float cam_pos[] = {0.0f, 0.0f, 5.0f};
	float cam_yaw = 0.0f; // y-rotation in degrees
	mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1],
                                                -cam_pos[2]));
	mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw);
	mat4 view_mat = R * T;
	
	glUseProgram (shader_programme);
	glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
	glUniformMatrix4fv (proj_mat_location, 1, GL_FALSE, proj_mat);
	
	while (!glfwWindowShouldClose (g_window)) {
		static double previous_seconds = glfwGetTime ();
		double current_seconds = glfwGetTime ();
		double elapsed_seconds = current_seconds - previous_seconds;
		previous_seconds = current_seconds;
	
		_update_fps_counter (g_window);
		// wipe the drawing surface clear
		glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport (0, 0, g_gl_width, g_gl_height);
		
		glUseProgram (shader_programme);
		glBindVertexArray (vao);
		// draw points 0-3 from the currently bound VAO with current shader
		glDrawArrays (GL_TRIANGLES, 0, g_point_count);
		// update other events like input handling 
		glfwPollEvents ();
		
		// control keys
		bool cam_moved = false;
		if (glfwGetKey (g_window, GLFW_KEY_A)) {
			cam_pos[0] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_D)) {
			cam_pos[0] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_UP)) {
			cam_pos[1] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_DOWN)) {
			cam_pos[1] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_W)) {
			cam_pos[2] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_S)) {
			cam_pos[2] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_LEFT)) {
			cam_yaw += cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_RIGHT)) {
			cam_yaw -= cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		// update view matrix
		if (cam_moved) {
			mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0],
                -cam_pos[1], -cam_pos[2])); // cam translation
			mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw); // 
			mat4 view_mat = R * T;
			glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
		}
		
		
		if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) {
			glfwSetWindowShouldClose (g_window, 1);
		}
		// put the stuff we've been drawing onto the display
		glfwSwapBuffers (g_window);
	}
	
	// close GL context and any other GLFW resources
	glfwTerminate();
	return 0;
}
  void TextEngineRenderer::Render() {
    GameState &current_state = updater.GetCurrentState();

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    PushMatrix();
    matrix_stack.back() *= glm::scale(glm::mat4(1), glm::vec3(glm::vec2(current_state.zoom * 0.1f), 1.0f));
    matrix_stack.back() *= glm::translate(glm::mat4(1), glm::vec3(-current_state.camera_position, 0));

    const glm::vec2 position = glm::vec2(current_state.player_body->GetPosition().x,
                                         current_state.player_body->GetPosition().y);

    fill = glm::vec4(0.0f, 0.5f, 0.3f, 0.5f);
    for (const auto &area : scene.areas) {
      if (area->invisible) {
        continue;
      }
      if (Shape::kAxisAlignedBoundingBox == area->shape) {
        DrawAxisAlignedBoundingBox(area->aabb);
      } else {
        DrawCircle(area->aabb.center(), area->aabb.radius());
      }
    }
    fill = glm::vec4(1.0f, 0.0f, 0.0f, 0.5f);
    for (const auto &object : scene.objects) {
      if (object->invisible) {
        continue;
      }
      if (Shape::kAxisAlignedBoundingBox == object->shape) {
        DrawAxisAlignedBoundingBox(object->aabb);
      } else {
        DrawCircle(object->aabb.center(), object->aabb.radius());
      }	
    }

    const glm::mat4 normalized_to_reversed = glm::scale(glm::mat4(), glm::vec3(1.0f, -1.0f, 1.0f));
    const glm::mat4 reversed_to_offset = glm::translate(glm::mat4(), glm::vec3(glm::vec2(1.0f), 0.0f));
    const glm::mat4 offset_to_screen = glm::scale(glm::mat4(), glm::vec3(glm::vec2(0.5f), 1.0f));
    const glm::mat4 screen_to_window = glm::scale(glm::mat4(), glm::vec3(width, height, 1.0f));

    const glm::mat4 transform = (screen_to_window * offset_to_screen *
                                 reversed_to_offset * normalized_to_reversed *
                                 model_view * projection * matrix_stack.back());
    const glm::mat4 transform2 = (screen_to_window * offset_to_screen *
                                  reversed_to_offset *
                                  model_view * projection * matrix_stack.back());
    const auto inverse = glm::inverse(transform2);
    const glm::vec4 homogeneous = transform * glm::vec4(position, 0.0f, 1.0f);
    const glm::vec2 transformed = homogeneous.xy() / homogeneous.w;

    fill = glm::vec4(0.5f, 0.5f, 0.6f, 1.0f);
    PushMatrix();
    matrix_stack.back() *= glm::translate(glm::mat4(1), glm::vec3(position, 0));
    matrix_stack.back() *= glm::rotate(glm::mat4(1),
                                       current_state.player_body->GetAngle(),
                                       glm::vec3(0, 0, 1));
    DrawRectangle(glm::vec2(0), glm::vec2(0.25f, 0.5f));
    PopMatrix();
    PopMatrix();
    
    if (edit) {
      MaybeRebuildAttenuationShader();
      if (current_state.selected_item) {
        attenuation3_program.Use();
        attenuation3_program.Uniforms({
          {u8"model_view_inverse", &inverse}
        });
        const auto isaabb3 = Shape::kAxisAlignedBoundingBox == current_state.selected_item->shape;
        glUniform1i(attenuation3_program.GetUniformLocation(u8"selected_isaabb"), isaabb3);
        if (Shape::kAxisAlignedBoundingBox == current_state.selected_item->shape) {
          attenuation3_program.Uniforms({
            {u8"selected_minimum_or_center", current_state.selected_item->aabb.minimum},
            {u8"selected_maximum_or_radius", current_state.selected_item->aabb.maximum},
          });
          CHECK_STATE(!glGetError());
        } else {
          attenuation3_program.Uniforms({
            {u8"selected_minimum_or_center", current_state.selected_item->aabb.center()},
            {u8"selected_maximum_or_radius", glm::vec2(current_state.selected_item->aabb.radius())},
          });
          CHECK_STATE(!glGetError());
        }
        const auto attenuation3_coefficients = glm::vec3(
            current_state.selected_item->base_attenuation,
                current_state.selected_item->linear_attenuation,
                    current_state.selected_item->quadratic_attenuation);
        attenuation3_program.Uniforms({
          {u8"selected_attenuation", attenuation3_coefficients},
        });
        const auto color3 = glm::vec4(0, 0, 0, 0.125);
        attenuation3_program.Uniforms({
          {u8"color", color3}
        });
        attenuation_array.Bind();
        glDrawArrays(attenuation.element_type, 0, attenuation.element_count);
        CHECK_STATE(!glGetError());
        
        attenuation_program.Use();
        attenuation_program.Uniforms({
          {u8"model_view_inverse", &inverse}
        });
        const auto isaabb = Shape::kAxisAlignedBoundingBox == current_state.selected_item->shape;
        glUniform1i(attenuation_program.GetUniformLocation(u8"selected_isaabb"), isaabb);
        if (Shape::kAxisAlignedBoundingBox == current_state.selected_item->shape) {
          attenuation_program.Uniforms({
            {u8"selected_minimum_or_center", current_state.selected_item->aabb.minimum},
            {u8"selected_maximum_or_radius", current_state.selected_item->aabb.maximum},
          });
          CHECK_STATE(!glGetError());
        } else {
          attenuation_program.Uniforms({
            {u8"selected_minimum_or_center", current_state.selected_item->aabb.center()},
            {u8"selected_maximum_or_radius", glm::vec2(current_state.selected_item->aabb.radius())},
          });
          CHECK_STATE(!glGetError());
        }
        const auto attenuation_coefficients = glm::vec3(
            current_state.selected_item->base_attenuation,
                current_state.selected_item->linear_attenuation,
                    current_state.selected_item->quadratic_attenuation);
        attenuation_program.Uniforms({
          {u8"selected_attenuation", attenuation_coefficients},
        });
        const auto color = glm::vec4(0, 0, 0, 0.5);
        attenuation_program.Uniforms({
          {u8"color", color}
        });
        attenuation_array.Bind();
        glDrawArrays(attenuation.element_type, 0, attenuation.element_count);
        CHECK_STATE(!glGetError());
      }
    }

    const auto mouse_position = 2.0f * mouse.get_cursor_position();
    unsigned char mouse_buttons = 0;
    if (mouse.IsButtonDown(GLFW_MOUSE_BUTTON_1)) {
      mouse_buttons |= IMGUI_MBUT_LEFT;
    }
    if (mouse.IsButtonDown(GLFW_MOUSE_BUTTON_2)) {
      mouse_buttons |= IMGUI_MBUT_RIGHT;
    }
    
    if (edit) {
      imguiBeginFrame(mouse_position.x, height - mouse_position.y, mouse_buttons, 0);
      
      for (auto &area : scene.areas) {
        const glm::vec4 homogeneous = transform * glm::vec4(area->aabb.minimum.x, area->aabb.maximum.y, 0.0f, 1.0f);
        const glm::vec2 transformed = homogeneous.xy() / homogeneous.w;
        imguiDrawText(transformed.x, height - transformed.y, IMGUI_ALIGN_LEFT, area->name.c_str(), imguiRGBA(0, 0, 0));
      }
      
      for (auto &object : scene.objects) {
        const glm::vec4 homogeneous = transform * glm::vec4(object->aabb.minimum.x, object->aabb.maximum.y, 0.0f, 1.0f);
        const glm::vec2 transformed = homogeneous.xy() / homogeneous.w;
        imguiDrawText(transformed.x, height - transformed.y, IMGUI_ALIGN_LEFT, object->name.c_str(), imguiRGBA(0, 0, 0));
      }
      
      if (current_state.selected_item) {
        std::ostringstream name, constant, linear, quadratic;
        name << current_state.selected_item->name;
        imguiDrawText(10, height - 50, IMGUI_ALIGN_LEFT, name.str().c_str(), imguiRGBA(0, 0, 0));
        constant << "c: " << current_state.selected_item->base_attenuation;
        imguiDrawText(10, height - 75, IMGUI_ALIGN_LEFT, constant.str().c_str(), imguiRGBA(0, 0, 0));
        linear << "l: " << current_state.selected_item->linear_attenuation;
        imguiDrawText(10, height - 100, IMGUI_ALIGN_LEFT, linear.str().c_str(), imguiRGBA(0, 0, 0));
        quadratic << "q: " << current_state.selected_item->quadratic_attenuation << std::endl;
        imguiDrawText(10, height - 125, IMGUI_ALIGN_LEFT, quadratic.str().c_str(), imguiRGBA(0, 0, 0));
      }
      
      imguiEndFrame();
    }

    imguiRenderGLDraw(width, height);
  }
Esempio n. 30
0
void display(void)
{
	if(dipMode==1)
	{
		glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
	}else{
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	}
	

	curF++;
	// put your OpenGL display commands here
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

	// reset OpenGL transformation matrix
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity(); // reset transformation matrix to identity

	// setup look at transformation so that 
	// eye is at : (0,0,3)
	// look at center is at : (0,0,0)
	// up direction is +y axis
	gluLookAt(0.f,0.f,3.f,0.f,0.f,0.f,0.f,1.f,0.f);
	glRotatef(fRotateAngle,.3f,1.f,.3f);
	//rand() * 2 - 1;

		// Test drawing a solid teapot

/*
	else{
		glLineWidth(2.5);
		//glColor3f(1. , 0. , 0.);
	}
*/

	glColor3f(changecolor + 1., changecolor + .5, changecolor);// set current color to orange
	//glutSolidTeapot(1.f); // call glut utility to draw a solid teapot 
  glBegin(GL_TRIANGLE_FAN);
  
	glVertex2f(-.6 + sin(change - 10) / 20, 1. + cos(change - 10) / 20);
	glVertex2f(-.6 + cos(change - 10) / 20, .6 + sin(change - 10) / 20);
	glVertex2f(-.2 + cos(change - 10) / 20, .6 + cos(change - 10) / 20); // v3
	glVertex2f(.2 + cos(change - 10) / 20, .6 + sin(change - 10) / 20); // v10
	glVertex2f(.6 + sin(change - 10) / 20, .6 + sin(change - 10) / 20);
	glVertex2f(.6 + cos(change - 10) / 20, 1. + sin(change - 10) / 20);

  glEnd();

  glBegin(GL_TRIANGLE_FAN);
/*	if (colorflag) {
		glColor3f(changecolor + 1., changecolor + .5, changecolor);// set current color to orange
	}
	else {
		glColor3f(changecolor + 1., changecolor + .5, changecolor);
	}*/

	glVertex2f(0. + sin(change - 10) / 20, -1. + sin(change - 10) / 20);
	glVertex2f(-.6 + sin(change - 10) / 20, -1. + sin(change - 10) / 20);
	glVertex2f(-.6 + cos(change - 10) / 20, -.6 + cos(change - 10) / 20);
	glVertex2f(-.2 + cos(change - 10) / 20, -.6 + sin(change - 10) / 20);
	glVertex2f(-.2 + cos(change - 10) / 20, .6 + cos(change - 10) / 20); // v3
	glVertex2f(.2 + cos(change - 10) / 20, .6 + sin(change - 10) / 20); // v10
	glVertex2f(.2 + sin(change - 10) / 20, -.6 + cos(change - 10) / 20);
	glVertex2f(.6 + cos(change - 10) / 20, -.6 + sin(change - 10) / 20);
	glVertex2f(.6 + sin(change - 10) / 20, -1. + cos(change - 10) / 20);

  glEnd();

	//glFlush();
	glutSwapBuffers();	// swap front/back framebuffer to avoid flickering 

	curClock=clock();
	float elapsed=(curClock-startClock)/(float)CLOCKS_PER_SEC;
	if(elapsed>1.0f){
		float fps=(float)(curF-prevF)/elapsed;
		printf("fps:%f\n",fps);
		prevF=curF;
		startClock=curClock;
	}
}