// the main update method void CCDIKSolver::Update(const float timeDeltaInSeconds) { // if we are using cloned nodes if (mStartNode_Clone != mStartNode) { // make sure that the cloned nodes are all still attached to the root of the chain // they can and will become distant if we dont do this Matrix mat = mStartNode_Clone->GetLocalTM(); mat.SetTranslation(mStartNode->GetLocalTM().GetTranslation()); mStartNode_Clone->SetLocalTM(mat); mStartNode_Clone->RecursiveUpdateWorldTM(NULL); } // some values we need int curIteration = 0; float dist = FLT_MAX; Node* curNode = mEndNode_Clone->GetParent(); // the CCD iteration loop while (curIteration < mMaxIterations && dist > mDistThreshold) { // required bone positions Vector3 rootPos = curNode->GetWorldPos(); Vector3 curEnd = mEndNode_Clone->GetWorldPos(); Vector3 desiredEnd = mGoal; // if we are far enough from the goal dist = (desiredEnd - curEnd).SquareLength(); if (dist > mDistThreshold) { // vector to the current effector pos Vector3 curVector = (curEnd - rootPos).Normalize(); // desired effector position vector Vector3 targetVector = (mGoal - rootPos).Normalize(); // calculate the cosine angle const float cosAngle = targetVector.Dot( curVector ); // if the dot product is 1, we don't need to rotate, since it is 0 degrees if (cosAngle < 0.99999f) { // calculate the rotation axis Vector3 crossResult = curVector.Cross( targetVector ); crossResult.Normalize(); // get the rotation angle in radians const float turnAngle = Math::ACos( cosAngle ); // rotate our matrix Matrix rotMat; rotMat.SetRotationMatrixAxisAngle(crossResult, turnAngle); Matrix tempMat = curNode->GetWorldTM() * rotMat; tempMat.SetTranslation( curNode->GetWorldPos() ); // Get our rotational limit attribute NodeLimitAttribute* attribute = (NodeLimitAttribute*)curNode->GetAttributeByType( NodeLimitAttribute::TYPE_ID ); // no need to do all these calculations if there is no valid NodeLimitAttribute or if the user // doesnt want us to do joint limits, or if there is no parent to constrain against if (attribute && mDoJointLimits && (curNode->GetParent() != NULL)) { // NOTE: 3DS Max seems to need us to invert the angles // TODO: verify this with Maya Vector3 min = -attribute->GetRotationMax(); Vector3 max = -attribute->GetRotationMin(); // Instead of: // Vector3 max = attribute->GetRotationMax(); // Vector3 min = attribute->GetRotationMin(); // convert the matrix into local coordinates of the node tempMat *= curNode->GetParent()->GetWorldTM().Inversed(); // calculate the euler representation of this matrix Vector3 tempEuler = tempMat.CalcEulerAngles(); // apply the constraints (simple cliping) if (tempEuler.x > max.x) tempEuler.x = max.x; if (tempEuler.x < min.x) tempEuler.x = min.x; if (tempEuler.y > max.y) tempEuler.y = max.y; if (tempEuler.y < min.y) tempEuler.y = min.y; if (tempEuler.z > max.z) tempEuler.z = max.z; if (tempEuler.z < min.z) tempEuler.z = min.z; // rebuild the matrix from the modified euler angles tempMat.SetRotationMatrixEuler(tempEuler); // convert back into world co-ordinates tempMat *= curNode->GetParent()->GetWorldTM(); } // add correct scale and translation to the rotation matrix Vector3 scale = curNode->GetWorldScale(); tempMat.Scale(scale.x, scale.y, scale.z); tempMat.SetTranslation( curNode->GetWorldPos() ); // recursively update the world TM (forward kinematics) curNode->RecursiveUpdateWorldTM( &tempMat ); } // go one node up in the hierarchy (towards the front of the chain) curNode = curNode->GetParent(); // if we reach the start of the chain, go to the end again and increment the iteration counter if (curNode == mStartNode_Clone->GetParent()) { curNode = mEndNode_Clone->GetParent(); curIteration++; } } } // check if we found a solution if (curIteration >= mMaxIterations) mHasSolution = false; else mHasSolution = true; // if we are not using cloned nodes // then we dont need to copy the positions from the cloned chain into the real chain if (mStartNode_Clone == mStartNode) return; // copy the positions of all the cloned nodes into the real nodes Node *n1 = mEndNode_Clone; Node *n2 = mEndNode; while (true) { n2->SetWorldTM( n1->GetWorldTM() ); n2->SetLocalTM( n1->GetLocalTM() ); n1 = n1->GetParent(); n2 = n2->GetParent(); if (n1 == mStartNode_Clone->GetParent() || n2 == mStartNode->GetParent()) { if (n1 == mStartNode_Clone->GetParent() && n2 == mStartNode->GetParent()) break; else { LOG("Something is VERY wrong in the CCD controller"); LOG("n1='%s' - n2='%s'", n1->GetName().AsChar(), n2->GetName().AsChar()); break; } } } // make sure that all the children that AREN'T in the cloned chain are updated properly mStartNode->RecursiveUpdateWorldTM(NULL); }
void Player::update(float &lastFrameTicks, float &elapsed, Matrix &projectionMatrix, Matrix &viewMatrix, ShaderProgram &program, GLuint textureID, Entity& ent, int player, int& score) { // Update modelMatrix Matrix modelMatrix; static Bullet bullet(x/2); static bool pressed = false; const Uint8 *keys = SDL_GetKeyboardState(NULL); if (player == 1) { if (keys[SDL_SCANCODE_A]) { if (x > -1.85) { x -= elapsed*2; } } if(keys[SDL_SCANCODE_D]) { if (x < 1.85) { x += elapsed*2; } } } else { if (keys[SDL_SCANCODE_LEFT]) { if (x > -1.85) { x -= elapsed*2; } } if(keys[SDL_SCANCODE_RIGHT]) { if (x < 1.85) { x += elapsed*2; } } } // shootBullet(); // for (Bullet b : bullets) { // b.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program); // b.render(program, textureID); // } if (player == 1) { if (keys[SDL_SCANCODE_SPACE]) { pressed = true; } } else { if (keys[SDL_SCANCODE_UP]) { pressed = true; } } if (pressed) { if (bullet.displayBullet(1.6)) { pressed = false; bullet = *new Bullet(x/2); } bullet.update(lastFrameTicks, elapsed, projectionMatrix, viewMatrix, program); bullet.render(program, textureID); } if ((ent.y - 0.0786241/2 <= bullet.y + 0.0905/2) && (ent.y + 0.0786241/2 >= bullet.y - 0.0905/2) && ((bullet.x - 0.0103/2) <= ((ent.x + 0.356564/2))) && ((bullet.x + 0.0103/2) >= ((ent.x - 0.0356564/2)))){ std::cout << "Target Hit" << std::endl; score += 100; ent.display = false; } modelMatrix.identity(); modelMatrix.Scale(0.5, 2, 0); modelMatrix.Translate(x, -0.4, 0); program.setModelMatrix(modelMatrix); }
int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL); SDL_GLContext context = SDL_GL_CreateContext(displayWindow); SDL_GL_MakeCurrent(displayWindow, context); #ifdef _WINDOWS glewInit(); #endif glViewport(0, 0, 640, 360); ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl"); Matrix projectionMatrix; Matrix modelMatrix; Matrix viewMatrix; Matrix panelOneMatrix; Matrix panelTwoMatrix; projectionMatrix.setOrthoProjection(-3.55f, 3.55f, -2.0f, 2.0f, -1.0f, 1.0f); GLuint textureID = LoadTexture("ball.png"); GLuint panelTexID = LoadTexture("red_panel.png"); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Ball *ball = new Ball(0.0f, 0.0f, 3.0f, 3.0f, 0.2f); Panel *panelOne = new Panel(-3.55f, ball); Panel *panelTwo = new Panel(3.55f, ball); float lastFrameTicks = 0.0f; float angle = 0.0f; SDL_Event event; bool done = false; while (!done) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) { done = true; } } float ticks = (float)SDL_GetTicks() / 1000.0f; float elapsed = ticks - lastFrameTicks; lastFrameTicks = ticks; program.setModelMatrix(modelMatrix); program.setProjectionMatrix(projectionMatrix); program.setViewMatrix(viewMatrix); glUseProgram(program.programID); glClearColor(0.2f, 0.2f, 0.2, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE); // BALL float vertices[] = { -0.5f, -0.5f, 0.5f, 0.5f, -0.5f, 0.5f, 0.5f, 0.5f, -0.5f, -0.5f, 0.5f, -0.5f }; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices); glEnableVertexAttribArray(program.positionAttribute); float texCoords[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 }; glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords); glEnableVertexAttribArray(program.texCoordAttribute); glBindTexture(GL_TEXTURE_2D, textureID); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); program.setModelMatrix(panelOneMatrix); // PANEL ONE float panelVTwo[] = { -0.1f, -0.75f, 0.1f, 0.75f, -0.1f, 0.75f, 0.1f, 0.75f, -0.1f, -0.75f, 0.1f, -0.75f }; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, panelVTwo); glEnableVertexAttribArray(program.positionAttribute); float texPanelOne[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 }; glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texPanelOne); glEnableVertexAttribArray(program.texCoordAttribute); panelOneMatrix.Translate(panelOne->starty, panelOne->pos, 0.0f); glBindTexture(GL_TEXTURE_2D, panelTexID); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); program.setModelMatrix(panelTwoMatrix); // PANEL TWO float panelVOne[] = { -0.1f, -0.75f, 0.1f, 0.75f, -0.1f, 0.75f, 0.1f, 0.75f, -0.1f, -0.75f, 0.1f, -0.75f }; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, panelVOne); glEnableVertexAttribArray(program.positionAttribute); float texPanelTwo[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 }; glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texPanelTwo); glEnableVertexAttribArray(program.texCoordAttribute); glBindTexture(GL_TEXTURE_2D, panelTexID); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); modelMatrix.identity(); panelOneMatrix.identity(); panelTwoMatrix.identity(); panelOne->update(); panelTwo->update(); panelOne->pos += panelOne->vel*elapsed; panelTwo->pos += panelTwo->vel*elapsed; ball->update(); ball->xPos += ball->xVel*elapsed; ball->yPos += ball->yVel*elapsed; angle += elapsed; modelMatrix.Translate(ball->xPos, ball->yPos, 0.0f); modelMatrix.Scale(0.6f, 0.6f, 1.0f); modelMatrix.Rotate(angle); panelOneMatrix.Translate(panelOne->starty, panelOne->pos, 0.0f); panelOneMatrix.Scale(0.5f, 0.5f, 1.0f); panelTwoMatrix.Translate(panelTwo->starty, panelTwo->pos, 0.0f); panelTwoMatrix.Scale(0.5f, 0.5f, 1.0f); SDL_GL_SwapWindow(displayWindow); } SDL_Quit(); return 0; }
void Weapon::DrawHUD( Screen3D& Screen, MeshManager& MM, FontManager& FM, Camera& Viewer ) { HitPlayer = false; Screen.Clear(true); // Set the matrices to the origin D3DXMATRIX matWorld; D3DXMatrixIdentity( &matWorld ); Screen.SetTransform( matWorld ); //Set render states ScreenPtr->D3DDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); ScreenPtr->D3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); ScreenPtr->D3DDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); ScreenPtr->D3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); ScreenPtr->D3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); ScreenPtr->D3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE ); ScreenPtr->D3DDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); ScreenPtr->D3DDevice->SetTextureStageState( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE ); ScreenPtr->D3DDevice->SetTextureStageState( 1, D3DTSS_COLORARG2, D3DTA_CURRENT ); ScreenPtr->D3DDevice->SetTextureStageState( 1, D3DTSS_ALPHAOP, D3DTOP_DISABLE ); //Draw the weapon model WeaponFont = FM.GetFont("Lucida Console", 16); Screen.D3DDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); Matrix ViewMatrix = Viewer.GetLookAtMatrix( -10 ); Matrix WorldMatrix; Matrix DisplacementMat; Matrix DisplacementMat2; Matrix ScaleMatrix; Screen.SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); Screen.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); Screen.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); Screen.SetRenderState(D3DRS_ALPHATESTENABLE, FALSE ); Screen.SetRenderState(D3DRS_ZENABLE, FALSE ); RECT muzzleDim = { Screen.GetWidth()/2, Screen.GetHeight()/2-Screen.GetHeight()/5,Screen.GetWidth()/2+(Screen.GetHeight()/5)*2, Screen.GetHeight()/2+Screen.GetHeight()/5}; int fade = (int)(MuzzleFlashFade*255.0f); Screen.DrawSpriteRect( muzzleDim, MuzzleFlash, true, D3DCOLOR_RGBA( fade, fade, fade, fade ) ); Screen.SetRenderState(D3DRS_ZENABLE, TRUE ); Screen.SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW); //Screen.SetTextureMode( TMSphereMap); //Screen.SetTexture(GlossMap, 1); Matrix RMat; RMat.Rotate( Viewer.Yaw, Viewer.Pitch, Viewer.Roll); ScreenPtr->D3DDevice->MultiplyTransform( D3DTS_TEXTURE1, &RMat.Mat ); //draw if(!RightHanded) { //First, apply a -1 scale to the transform //matrix so that the gun draws on the opposite side //(since it's left handed). Also, change the //culling order so it doesn't draw inside out. Screen.SetRenderState( D3DRS_CULLMODE, D3DCULL_CW); DisplacementMat.Translate( 0.10f, 3.1f, -4.3f); ScaleMatrix.Scale( -1, 1, 1 ); D3DXMatrixMultiply(&DisplacementMat.Mat, &DisplacementMat.Mat, &ScaleMatrix.Mat); D3DXMatrixMultiply(&ViewMatrix.Mat, &ViewMatrix.Mat, &DisplacementMat.Mat); D3DXMatrixInverse(&WorldMatrix.Mat, NULL, &ViewMatrix.Mat); Screen.SetTransform(WorldMatrix); //Draw the mesh now and return the culling state //DisplayMesh.Draw( Screen ); Screen.SetRenderState(D3DRS_LIGHTING, FALSE ); MeshA.Draw( Screen, WorldMatrix ); Screen.SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW); D3DMATRIX OldState; Screen.D3DDevice->GetTransform( D3DTS_VIEW, &OldState); Matrix I; Screen.SetViewTransform(I); Smoke.MoveSpawn( -1.0f, -1.2f, 9.0f); Smoke.Draw( Screen, Viewer ); if(DualWeapons) { Smoke.MoveSpawn( 1.0f, -1.1f, 8.0f); Smoke.Draw( Screen, Viewer ); } Screen.D3DDevice->SetTransform( D3DTS_VIEW, &OldState); } else { DisplacementMat.Translate( -0.10f, 3.1f, -4.3f); D3DXMatrixMultiply(&ViewMatrix.Mat, &ViewMatrix.Mat, &DisplacementMat.Mat); D3DXMatrixInverse(&WorldMatrix.Mat, NULL, &ViewMatrix.Mat); Screen.SetTransform(WorldMatrix); //Draw the weapon Screen.D3DDevice->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_NONE ); MeshA.Draw( Screen, WorldMatrix ); Screen.D3DDevice->SetSamplerState( 0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR ); Matrix I; Screen.SetViewTransform(I); Smoke.MoveSpawn( 1.0f, -1.1f, 8.0f); Smoke.Draw( Screen, Viewer ); if(DualWeapons) { Smoke.MoveSpawn( -1.0f, -1.1f, 8.0f); Smoke.Draw( Screen, Viewer ); } } //Show the ammo information by the weapon Screen.D3DDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); ScreenPtr->D3DDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); ScreenPtr->D3DDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); ScreenPtr->D3DDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE); Screen.SetRenderState(D3DRS_ZENABLE, FALSE ); if(ShowAmmoAmount) { TextureHandle hAmmoBox = Screen.GetTextureHandle( "..\\base\\art\\UI\\icons\\ammobox.bmp", "..\\base\\art\\UI\\icons\\ammobox_a.bmp"); Screen.DrawSprite( Screen.GetWidth() - 145.0f, (Real)Screen.GetHeight() - 40.0f, Screen.TM.GetTexture( hAmmoBox )); WeaponFont->Draw(Screen, Screen.GetWidth() - 105.0f, (Real)Screen.GetHeight() - 32.0f, false, D3DCOLOR_RGBA(255, 255, 255, 255), "%d", ClipAmmo); WeaponFont->Draw(Screen, Screen.GetWidth() - 60.0f, (Real)Screen.GetHeight() - 32.0f, false, D3DCOLOR_RGBA(255, 0, 0, 255), "%d", Ammo); } Screen.TM.SetTextureMode( TMNormal, 0, true); //draw the aimer if(ShowAmmoAmount) { Texture* AimerPtr = Screen.TM.GetTexture( Aimer ); Screen.SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); Screen.SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); Screen.SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); Screen.SetRenderState(D3DRS_ALPHATESTENABLE, FALSE ); RECT Dimensions; Dimensions.left = Screen.GetWidth() /2 - (AimerPtr->GetWidth()/2); Dimensions.top = Screen.GetHeight()/2 - (AimerPtr->GetHeight()/2); Dimensions.right = Screen.GetWidth() /2 + AimerPtr->GetWidth()/2-1; Dimensions.bottom = Screen.GetHeight()/2 + AimerPtr->GetHeight()/2-1; if(AimerPtr) Screen.DrawSprite(Screen.GetWidth()/2 - (AimerPtr->GetWidth()/2), Screen.GetHeight()/2 - (AimerPtr->GetHeight()/2), AimerPtr); } ScreenPtr->D3DDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); ScreenPtr->D3DDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); ScreenPtr->D3DDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); Screen.SetRenderState(D3DRS_ZENABLE, TRUE ); Screen.SetRenderState( D3DRS_FOGENABLE, TRUE ); }
void RotationManipulator::ProcessMouseRay(const Vect &cameraDir, float scale, const Vect &rayOrig, const Vect &rayDir) { traceIn(RotationManipulator::ProcessMouseRay); activeAxis = -1; curCameraDir = cameraDir; Matrix mat; mat.SetIdentity(); mat.Translate(GetWorldPos()); mat.Scale(scale, scale, scale); bManipulating = false; DWORD i,j; for(i=0; i<3; i++) { for(j=0; j<30; j++) { DWORD jp1 = (j == 29) ? 0 : j+1; Vect norm = axisNorms[i][j]; if(norm.Dot(cameraDir) > 0.01f) continue; Vect v1 = axisLines[i][j]; Vect v2 = axisLines[i][jp1]; v1.TransformPoint(mat); v2.TransformPoint(mat); Vect lineVec = (v2-v1); float lineLen = lineVec.Len(); Vect lineDir = lineVec*(1.0f/lineLen); float fT1, fT2; if(ClosestLinePoints(rayOrig, rayDir, v1, lineDir, fT1, fT2)) { if((fT2 < 0.0f) || (fT2 > lineLen)) continue; Vect closestPoint1 = rayOrig+(rayDir*fT1); Vect closestPoint2 = v1+(lineDir*fT2); if(closestPoint1.Dist(closestPoint2) < (0.4f*scale)) { Vect axis(0.0f, 0.0f, 0.0f); axis.ptr[i] = 1.0f; activeAxis = i; clickDir = cameraDir.Cross(axis.Cross(norm)).Cross(cameraDir).Norm(); clickOrig = closestPoint1; bManipulating = true; return; } } } } mat.SetIdentity(); mat.Translate(GetWorldPos()); mat.Rotate(Quat().SetLookDirection(cameraDir)); mat.Scale(scale*1.25f, scale*1.25f, scale*1.25f); for(j=0; j<30; j++) { DWORD jp1 = (j == 29) ? 0 : j+1; Vect norm = axisNorms[2][j]; Vect v1 = axisLines[2][j]; Vect v2 = axisLines[2][jp1]; v1.TransformPoint(mat); v2.TransformPoint(mat); norm.TransformVector(mat); Vect lineVec = (v2-v1); float lineLen = lineVec.Len(); Vect lineDir = lineVec*(1.0f/lineLen); float fT1, fT2; if(ClosestLinePoints(rayOrig, rayDir, v1, lineDir, fT1, fT2)) { if((fT2 < 0.0f) || (fT2 > lineLen)) continue; Vect closestPoint1 = rayOrig+(rayDir*fT1); Vect closestPoint2 = v1+(lineDir*fT2); if(closestPoint1.Dist(closestPoint2) < (0.6f*scale)) { activeAxis = 4; clickDir = cameraDir.Cross(norm); clickOrig = closestPoint1; curCameraDir = cameraDir; bManipulating = true; return; } } } traceOut; }
void scaling(float x_value, float y_value, float z_value){ model.Scale(x_value, y_value, z_value); }
//╩Ф╩╜м╪оЯ bool CGdiPlusImage::DrawImage(CDC * pDC, INT nXPos, INT nYPos) { //╪стьеп╤о ASSERT(m_pImage!=NULL); if (m_pImage==NULL) return false; //╢╢╫╗фад╩ ASSERT(pDC!=NULL); Graphics graphics(pDC->GetSafeHdc()); GraphicsContainer Containter = graphics.BeginContainer(); graphics.SetSmoothingMode(SmoothingModeHighQuality); //╩Ях║йТпт INT nImageWidth=m_pImage->GetWidth(); INT nImageHeight=m_pImage->GetHeight(); //╧╧тЛн╩жц RectF rcDrawRect; rcDrawRect.X=0;//(REAL)nXPos; rcDrawRect.Y=0;//(REAL)nYPos; rcDrawRect.Width=(REAL)nImageWidth; rcDrawRect.Height=(REAL)nImageHeight; Matrix matrix; CPoint pt((nXPos+nImageWidth/2), (nYPos+nImageHeight/2)); PointF ptBase((float)pt.x,(float)pt.y); //╬ьуС╠Д╩╩р╙в╒рБкЁпРё╛охф╫рфтзкУ╥е╨СпЩв╙ matrix.Translate((REAL)nXPos,(REAL)nYPos,MatrixOrderAppend); //кУ╥е if ( m_szZoom.cx != 1.0f || m_szZoom.cy != 1.0f ) { ptBase.X += m_szZoom.cx; ptBase.Y += m_szZoom.cy; matrix.Translate(-ptBase.X,-ptBase.Y,MatrixOrderAppend); matrix.Scale(m_szZoom.cx,m_szZoom.cy,MatrixOrderAppend); matrix.Translate(ptBase.X,ptBase.Y,MatrixOrderAppend); } //пЩв╙ if (m_nRotateAngle) { matrix.RotateAt((REAL)m_nRotateAngle,ptBase,MatrixOrderAppend); } graphics.SetTransform(&matrix); //м╦цВ╬ьуС ColorMatrix Matrix= { 1.0f,0.0f,0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f,0.0f,0.0f, 0.0f,0.0f,1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f,m_cbAlphaDepth/255.0f,0.0f, 0.0f,0.0f,0.0f,0.0f,1.0f }; //иХжцйТпт ImageAttributes Attributes; Attributes.SetColorMatrix(&Matrix,ColorMatrixFlagsDefault,ColorAdjustTypeBitmap); //╩Ф╩╜м╪оЯ graphics.DrawImage(m_pImage,rcDrawRect,0,0,(REAL)nImageWidth,(REAL)nImageHeight,UnitPixel,&Attributes); graphics.ResetTransform(); graphics.EndContainer(Containter); return true; }
// // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: { int wmId = LOWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } } break; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code that uses hdc here... { Graphics graphics(hdc); Color color; color.SetFromCOLORREF(params.m_ccBackground.rgbResult); graphics.Clear(color); HFONT fnIndirect = CreateFontIndirect(params.m_cf.lpLogFont); Font font(hdc, fnIndirect); if (params.m_bAntialiasing) graphics.SetSmoothingMode(SmoothingModeHighQuality); Matrix matrix; RectF rect; graphics.MeasureString(params.m_text.c_str(), params.m_text.length(), &font, params.m_pStart, &rect); matrix.Translate(params.m_pStart.X + rect.Width / 2, params.m_pStart.Y + rect.Height / 2); matrix.Rotate(params.m_fRotAngle); matrix.Scale(params.m_fScale, params.m_fScale, MatrixOrderAppend); graphics.MultiplyTransform(&matrix); StringFormat strformat; GraphicsPath path; FontFamily fnFamily; font.GetFamily(&fnFamily); path.AddString(params.m_text.c_str(), params.m_text.length(), &fnFamily, font.GetStyle(), font.GetSize(), PointF(-rect.Width / 2, -rect.Height / 2), strformat.GenericTypographic()); color.SetFromCOLORREF(params.m_ccCircuit.rgbResult); Pen pen(color, 3); pen.SetLineJoin(LineJoinRound); graphics.DrawPath(&pen, &path); color.SetFromCOLORREF(params.m_ccFill.rgbResult); SolidBrush brush(color); graphics.FillPath(&brush, &path); Region region(&path); hRgn = region.GetHRGN(&graphics); graphics.ResetTransform(); RECT rc; GetWindowRect(hWnd, &rc); POINT pt; pt.x = rc.left; pt.y = rc.top; ScreenToClient(hWnd, &pt); matrix.Translate((REAL)-pt.x, (REAL)-pt.y, MatrixOrderAppend); region.Transform(&matrix); HRGN hRgnFr = region.GetHRGN(&graphics); OffsetRect(&rc, -rc.left, -rc.top); /*HRGN hRgnWnd = CreateRectRgn(rc.left, rc.top, rc.right, rc.bottom); CombineRgn(hRgn, hRgn, hRgnWnd, RGN_XOR); CombineRgn(hRgnFr, hRgnFr, hRgnWnd, RGN_XOR);*/ SetWindowRgn(hWnd, params.m_bNonRectRg ? hRgnFr : NULL, TRUE); } EndPaint(hWnd, &ps); } break; case WM_LBUTTONDOWN: { int xPos = GET_X_LPARAM(lParam); int yPos = GET_Y_LPARAM(lParam); if (PtInRegion(hRgn, xPos, yPos)) { DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG_TEXT_PARAMS), hWnd, TextParams); InvalidateRect(hWnd, NULL, TRUE); } } break; case WM_ERASEBKGND: return TRUE; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
CGContextRef gfxQuartzNativeDrawing::BeginNativeDrawing() { NS_ASSERTION(!mQuartzSurface, "BeginNativeDrawing called when drawing already in progress"); if (!mContext->IsCairo()) { DrawTarget *dt = mContext->GetDrawTarget(); if (mContext->GetDrawTarget()->IsDualDrawTarget()) { IntSize backingSize(NSToIntFloor(mNativeRect.width * mBackingScale), NSToIntFloor(mNativeRect.height * mBackingScale)); if (backingSize.IsEmpty()) return nullptr; mDrawTarget = Factory::CreateDrawTarget(BACKEND_COREGRAPHICS, backingSize, FORMAT_B8G8R8A8); Matrix transform; transform.Scale(mBackingScale, mBackingScale); transform.Translate(-mNativeRect.x, -mNativeRect.y); mDrawTarget->SetTransform(transform); dt = mDrawTarget; } mCGContext = mBorrowedContext.Init(dt); MOZ_ASSERT(mCGContext); return mCGContext; } gfxPoint deviceOffset; nsRefPtr<gfxASurface> surf = mContext->CurrentSurface(&deviceOffset.x, &deviceOffset.y); if (!surf || surf->CairoStatus()) return nullptr; // if this is a native Quartz surface, we don't have to redirect // rendering to our own CGContextRef; in most cases, we are able to // use the CGContextRef from the surface directly. we can extend // this to support offscreen drawing fairly easily in the future. if (surf->GetType() == gfxSurfaceTypeQuartz && (surf->GetContentType() == GFX_CONTENT_COLOR || (surf->GetContentType() == GFX_CONTENT_COLOR_ALPHA))) { mQuartzSurface = static_cast<gfxQuartzSurface*>(surf.get()); mSurfaceContext = mContext; // grab the CGContextRef mCGContext = cairo_quartz_get_cg_context_with_clip(mSurfaceContext->GetCairo()); if (!mCGContext) return nullptr; gfxMatrix m = mContext->CurrentMatrix(); CGContextTranslateCTM(mCGContext, deviceOffset.x, deviceOffset.y); // I -think- that this context will always have an identity // transform (since we don't maintain a transform on it in // cairo-land, and instead push/pop as needed) gfxFloat x0 = m.x0; gfxFloat y0 = m.y0; // We round x0/y0 if we don't have a scale, because otherwise things get // rendered badly // XXX how should we be rounding x0/y0? if (!m.HasNonTranslationOrFlip()) { x0 = floor(x0 + 0.5); y0 = floor(y0 + 0.5); } CGContextConcatCTM(mCGContext, CGAffineTransformMake(m.xx, m.yx, m.xy, m.yy, x0, y0)); // bug 382049 - need to explicity set the composite operation to sourceOver CGContextSetCompositeOperation(mCGContext, kPrivateCGCompositeSourceOver); } else { nsIntSize backingSize(NSToIntFloor(mNativeRect.width * mBackingScale), NSToIntFloor(mNativeRect.height * mBackingScale)); mQuartzSurface = new gfxQuartzSurface(backingSize, gfxImageFormatARGB32); if (mQuartzSurface->CairoStatus()) return nullptr; mSurfaceContext = new gfxContext(mQuartzSurface); // grab the CGContextRef mCGContext = cairo_quartz_get_cg_context_with_clip(mSurfaceContext->GetCairo()); CGContextScaleCTM(mCGContext, mBackingScale, mBackingScale); CGContextTranslateCTM(mCGContext, -mNativeRect.X(), -mNativeRect.Y()); } return mCGContext; }
int main(int argc, char *argv[]) { SDL_Init(SDL_INIT_VIDEO); displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL); SDL_GLContext context = SDL_GL_CreateContext(displayWindow); SDL_GL_MakeCurrent(displayWindow, context); #ifdef _WINDOWS glewInit(); #endif //setup glViewport(0, 0, 640, 360); ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl",RESOURCE_FOLDER"fragment_textured.glsl"); //textures GLuint medalTexture = LoadTexture("flat_medal1.png"); Matrix medalProjectionMatrix; Matrix medalModelMatrix; Matrix medalViewMatrix; medalProjectionMatrix.setOrthoProjection(-3.55,3.55,-2.0f,2.0f,-1.0f, 1.0f); GLuint smileyTexture = LoadTexture("happy.gif"); Matrix smileyProjectionMatrix; Matrix smileyModelMatrix; Matrix smileyViewMatrix; smileyProjectionMatrix.setOrthoProjection(-3.55,3.55,-2.0f,2.0f,-1.0f, 1.0f); GLuint diceTexture = LoadTexture("dieWhite_border1.png"); Matrix diceProjectionMatrix; Matrix diceModelMatrix; Matrix diceViewMatrix; diceProjectionMatrix.setOrthoProjection(-3.55,3.55,-2.0f,2.0f,-1.0f, 1.0f); glUseProgram(program.programID); //x, y, z locations float medalX = 0.0f; float medalY = 0.0f; float medalZ = 0.0f; float smileyX = -0.8f; float smileyY = -0.8f; float smileyZ = 0.0f; float lastFrameTicks = 0.0f; SDL_Event event; bool done = false; while (!done) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) { done = true; } } glClear(GL_COLOR_BUFFER_BIT); //get the time float ticks = (float)SDL_GetTicks()/1000.0f; float elapsed = ticks - lastFrameTicks; lastFrameTicks = ticks; //generate the medal program.setModelMatrix(medalModelMatrix); program.setProjectionMatrix(medalProjectionMatrix); program.setViewMatrix(medalViewMatrix); glBindTexture(GL_TEXTURE_2D, medalTexture); float vertices[] = {-0.2, -0.2, 0.2, -0.2, 0.2, 0.2, -0.2, -0.2, 0.2, 0.2, -0.2, 0.2}; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices); glEnableVertexAttribArray(program.positionAttribute); float texCoord[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0}; glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoord); glEnableVertexAttribArray(program.texCoordAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); float angleRotation = angleRotation + elapsed * (0.1*3.14159621/180); medalModelMatrix.Rotate(angleRotation); //generate the happy face texture program.setModelMatrix(smileyModelMatrix); program.setProjectionMatrix(smileyProjectionMatrix); program.setViewMatrix(smileyViewMatrix); glBindTexture(GL_TEXTURE_2D, smileyTexture); //start the texture in the center of the screen and then translate it down by 0.5 float smileyVertex[] = {-0.2, -0.2, 0.2, -0.2, 0.2, 0.2, -0.2, -0.2, 0.2, 0.2, -0.2, 0.2}; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, smileyVertex); glEnableVertexAttribArray(program.positionAttribute); float smileyTexCoord[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0}; glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, smileyTexCoord); glEnableVertexAttribArray(program.texCoordAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); smileyProjectionMatrix.identity(); smileyProjectionMatrix.Translate(0, -0.5, 0.0); float smileyXTranslate = elapsed*1; smileyX = smileyX + smileyXTranslate; if (smileyX > 1.0) { smileyX = -smileyX; } smileyProjectionMatrix.Translate(smileyX,0, 0); //generate the dice program.setModelMatrix(diceModelMatrix); program.setProjectionMatrix(diceProjectionMatrix); program.setViewMatrix(diceViewMatrix); glBindTexture(GL_TEXTURE_2D, diceTexture); //start the texture in the center of the screen and then translate it up by 1.0 float diceVertices[] = {-0.2, -0.2, 0.2, -0.2, 0.2, 0.2, -0.2, -0.2, 0.2, 0.2, -0.2, 0.2}; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, diceVertices); glEnableVertexAttribArray(program.positionAttribute); float dicetexCoord[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0}; glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, dicetexCoord); glEnableVertexAttribArray(program.texCoordAttribute); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); float diceScale = 1+sin(ticks); std::cout << diceScale << std::endl; diceModelMatrix.identity(); diceModelMatrix.Translate(0.0, 1.0, 0.0); diceModelMatrix.Scale(diceScale, diceScale, 0.0); SDL_GL_SwapWindow(displayWindow); } SDL_Quit(); return 0; }
bool CGdiPlusImage::DrawImage(CDC* pDC) { //´´½¨ÆÁÄ» ASSERT(pDC!=NULL); if ( !pDC ) return false; Bitmap bmp(m_rcDest.Width(), m_rcDest.Height()); Graphics* pGraphics = Graphics::FromImage(&bmp); if ( !pGraphics ) return false; GraphicsContainer Containter = pGraphics->BeginContainer(); pGraphics->SetSmoothingMode(SmoothingModeHighQuality); SolidBrush bgbrush(Color(238, 243, 250)); pGraphics->FillRectangle(&bgbrush, 0, 0, m_rcDest.Width(), m_rcDest.Height()); if ( m_pImage ) { //»ñÈ¡ÊôÐÔ INT nImageWidth = m_pImage->GetWidth(); INT nImageHeight = m_pImage->GetHeight(); float fMin = 1.0F; float fZoomRate = 1.0F; bool bZoomOut = false; int nXSrc = 0; int nYSrc = 0; if ( nImageWidth >= m_rcDest.Width() || nImageHeight >= m_rcDest.Height() ) { float fXRate = 1.0F * m_rcDest.Width() / nImageWidth; float fYRate = 1.0F * m_rcDest.Height() / nImageHeight; fMin = min(fXRate, fYRate); fZoomRate = max(nImageWidth * 1.0F / m_rcDest.Width(), nImageHeight * 1.0F / m_rcDest.Height()); bZoomOut = true; } int nDestWidth = fMin * nImageWidth; int nDestHeight = fMin * nImageHeight; //¹¹ÔìλÖà RectF rcDrawRect; rcDrawRect.X = m_rcDest.left + (m_rcDest.Width() - nDestWidth ) / 2; rcDrawRect.Y = m_rcDest.top + (m_rcDest.Height() - nDestHeight ) / 2; rcDrawRect.Width = nDestWidth; rcDrawRect.Height = nDestHeight; Matrix matrix; CPoint pt(m_rcDest.Width() / 2, m_rcDest.Height() / 2); PointF ptBase((float)pt.x, (float)pt.y); //¾ØÕó±ä»»Òª×¢Òâ˳Ðò£¬ÏÈƽÒÆÔÚËõ·ÅºóÐýת matrix.Translate((REAL)m_rcDest.left,(REAL)m_rcDest.top,MatrixOrderAppend); //Ëõ·Å if ( m_szZoom.cx != 1.0f || m_szZoom.cy != 1.0f ) { ptBase.X += m_szZoom.cx; ptBase.Y += m_szZoom.cy; matrix.Translate(-ptBase.X,-ptBase.Y,MatrixOrderAppend); matrix.Scale(m_szZoom.cx,m_szZoom.cy,MatrixOrderAppend); matrix.Translate(ptBase.X,ptBase.Y,MatrixOrderAppend); } //Ðýת if (m_nRotateAngle) { matrix.RotateAt((REAL)m_nRotateAngle,ptBase,MatrixOrderAppend); } pGraphics->SetTransform(&matrix); //͸Ã÷¾ØÕó ColorMatrix Matrix= { 1.0f,0.0f,0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f,0.0f,0.0f, 0.0f,0.0f,1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f,m_cbAlphaDepth/255.0f,0.0f, 0.0f,0.0f,0.0f,0.0f,1.0f }; //ÉèÖÃÊôÐÔ ImageAttributes Attributes; Attributes.SetColorMatrix(&Matrix,ColorMatrixFlagsDefault,ColorAdjustTypeBitmap); //»æ»Í¼Ïñ pGraphics->DrawImage(m_pImage, rcDrawRect, nXSrc, nYSrc, (REAL)nImageWidth - nXSrc * 2, (REAL)nImageHeight - nYSrc * 2, UnitPixel,&Attributes); pGraphics->ResetTransform(); pGraphics->EndContainer(Containter); } // if ( m_pImage ) // ´ÓÄڴ濽±´ÖÁÉ豸 Graphics graphicsreal(pDC->GetSafeHdc()); graphicsreal.DrawImage(&bmp, 0, 0, m_rcDest.Width(), m_rcDest.Height()); delete pGraphics; pGraphics = NULL; return true; }
//»æ»Í¼Ïñ bool CGdiPlusImage::DrawImage(CDC * pDC, INT nXPos, INT nYPos) { //¼ÓÔØÅÐ¶Ï //ASSERT(m_pImage!=NULL); if (m_pImage==NULL) return false; //´´½¨ÆÁÄ» ASSERT(pDC!=NULL); Graphics graphics(pDC->GetSafeHdc()); GraphicsContainer Containter = graphics.BeginContainer(); graphics.SetSmoothingMode(SmoothingModeHighQuality); //»ñÈ¡ÊôÐÔ INT nImageWidth=m_pImage->GetWidth(); INT nImageHeight=m_pImage->GetHeight(); //¹¹ÔìλÖà RectF rcDrawRect; rcDrawRect.X=0;//(REAL)nXPos; rcDrawRect.Y=0;//(REAL)nYPos; rcDrawRect.Width=(REAL)nImageWidth; rcDrawRect.Height=(REAL)nImageHeight; Matrix matrix; CPoint pt((nXPos+nImageWidth/2), (nYPos+nImageHeight/2)); PointF ptBase((float)pt.x,(float)pt.y); //¾ØÕó±ä»»Òª×¢Òâ˳Ðò£¬ÏÈƽÒÆÔÚËõ·ÅºóÐýת matrix.Translate((REAL)nXPos,(REAL)nYPos,MatrixOrderAppend); //Ëõ·Å if ( m_szZoom.cx != 1.0f || m_szZoom.cy != 1.0f ) { ptBase.X += m_szZoom.cx; ptBase.Y += m_szZoom.cy; matrix.Translate(-ptBase.X,-ptBase.Y,MatrixOrderAppend); matrix.Scale(m_szZoom.cx,m_szZoom.cy,MatrixOrderAppend); matrix.Translate(ptBase.X,ptBase.Y,MatrixOrderAppend); } //Ðýת if (m_nRotateAngle) { matrix.RotateAt((REAL)m_nRotateAngle,ptBase,MatrixOrderAppend); } graphics.SetTransform(&matrix); //͸Ã÷¾ØÕó ColorMatrix Matrix= { 1.0f,0.0f,0.0f,0.0f,0.0f, 0.0f,1.0f,0.0f,0.0f,0.0f, 0.0f,0.0f,1.0f,0.0f,0.0f, 0.0f,0.0f,0.0f,m_cbAlphaDepth/255.0f,0.0f, 0.0f,0.0f,0.0f,0.0f,1.0f }; //ÉèÖÃÊôÐÔ ImageAttributes Attributes; Attributes.SetColorMatrix(&Matrix,ColorMatrixFlagsDefault,ColorAdjustTypeBitmap); //»æ»Í¼Ïñ graphics.DrawImage(m_pImage,rcDrawRect,0,0,(REAL)nImageWidth,(REAL)nImageHeight,UnitPixel,&Attributes); graphics.ResetTransform(); graphics.EndContainer(Containter); return true; }
int main(int argc, char *argv[]) { // Initialize SDL SDL_Init(SDL_INIT_VIDEO); displayWindow = SDL_CreateWindow("Homework 1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL); SDL_GLContext context = SDL_GL_CreateContext(displayWindow); SDL_GL_MakeCurrent(displayWindow, context); #ifdef _WINDOWS glewInit(); #endif // Define shader program ShaderProgram program(RESOURCE_FOLDER "vertex_textured.glsl", RESOURCE_FOLDER "fragment_textured.glsl"); glViewport(0, 0, 800, 600); // Load textures GLuint emoji = LoadTexture("emoji.png"); GLuint alien = LoadTexture("p1_front.png"); GLuint medal = LoadTexture("flat_medal6.png"); // Enable blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glUseProgram(program.programID); // Initialize local variables float lastFrameTicks = 0.0f; float angle = 0.0f; float X,Y,moveX, moveY = 0.0; SDL_Event event; bool done = false; while (!done) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) { done = true; } } // Define matrixes program.setProjectionMatrix(projectionMatrix); program.setModelMatrix(modelMatrix); program.setViewMatrix(viewMatrix); // Calculate elapsed time float ticks = (float)SDL_GetTicks()/1000.0f; float elapsed = ticks - lastFrameTicks; lastFrameTicks = ticks; // Calculate angle based on elapsed time angle += elapsed; if (X < .35 && Y < .35) { X += elapsed/2; Y += elapsed/2; } else if (X < -.35 && Y < -.35) { X -= elapsed/2; Y -= elapsed/2; } // Initialize keyboard state const Uint8 *keys = SDL_GetKeyboardState(NULL); // Clear and set color glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // Draw alien texture // glActiveTexture(GL_TEXTURE1); modelMatrix.identity(); modelMatrix.Scale(.2, .2, 1.0); program.setModelMatrix(modelMatrix); glBindTexture(GL_TEXTURE_2D, alien); float vertices1[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5}; float texCoords1[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0}; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices1); glEnableVertexAttribArray(program.positionAttribute); glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords1); glEnableVertexAttribArray(program.texCoordAttribute); glEnable(GL_TEXTURE_2D); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); // Draw medal texture // glActiveTexture(GL_TEXTURE2); modelMatrix.identity(); modelMatrix.Scale(.05, .05, 1.0); modelMatrix.Translate(0, -.95, 0); program.setModelMatrix(modelMatrix); glBindTexture(GL_TEXTURE_2D, medal); float vertices2[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5}; float texCoords2[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0}; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices2); glEnableVertexAttribArray(program.positionAttribute); glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords2); glEnableVertexAttribArray(program.texCoordAttribute); glEnable(GL_TEXTURE_2D); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); // Draw emoji texture // glActiveTexture(GL_TEXTURE0); modelMatrix.identity(); modelMatrix.Scale(X*2, Y*2, 1.0); modelMatrix.Rotate((angle*100.0f) * M_PI/180); if(keys[SDL_SCANCODE_SPACE]) { modelMatrix.identity(); modelMatrix.Scale(X*2, Y*2, 1.0); } modelMatrix.Translate(X*1.5, Y*1.5, 0); program.setModelMatrix(modelMatrix); glBindTexture(GL_TEXTURE_2D, emoji); float vertices[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5}; float texCoords[] = {0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0}; glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices); glEnableVertexAttribArray(program.positionAttribute); glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords); glEnableVertexAttribArray(program.texCoordAttribute); glEnable(GL_TEXTURE_2D); glDrawArrays(GL_TRIANGLES, 0, 6); glDisableVertexAttribArray(program.positionAttribute); glDisableVertexAttribArray(program.texCoordAttribute); SDL_GL_SwapWindow(displayWindow); } SDL_Quit(); return 0; }
void scaleObj(float x, float y, float z){ modelMatrix.Scale(x, y, z); }