Search Results

Search found 711 results on 29 pages for 'pos'.

Page 10/29 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • jQuery - How do I make the menu fadeout when the user clicks anywhere else in the document besides the menu itself?

    - by GirlGoneMad
    Hi, I have a link that functions similar to a drop down menu in that it fades in a list of links below it when clicked. Currently, the list fades back out when the link is clicked again, but I'd like for it to also fade out if the user clicks elsewhere on the page. I'm not sure how to add the $(document).click(function()... that handles this, or if this is even the right approach. Here is my code: $('#show_button').click( function(){ if(!$('#list').is(':visible')){ var pos = $('#show_button').offset(); $('#list').css({'left':pos.left - 11, 'top': pos.top+14}).fadeIn(); } else{ $('#list').fadeOut(); } }); I am trying to add something like this to make the list fade out when the user clicks anywhere else in the page: if($('#list').is(':visible')){ $(document).click(function() { $('#list').fadeOut(); }); } Thanks in advance - I would appreciate any help on this one :)

    Read the article

  • Texture will not apply to my 3d Cube directX

    - by numerical25
    I am trying to apply a texture onto my 3d cube but it is not showing up correctly. I believe that it might some what be working because the cube is all brown which is almost the same complexion as the texture. And I did not originally make the cube brown. These are the steps I've done to add the texture I first declared 2 new varibles ID3D10EffectShaderResourceVariable* pTextureSR; ID3D10ShaderResourceView* textureSRV; I also added a variable and a struct to my shader .fx file Texture2D tex2D; SamplerState linearSampler { Filter = MIN_MAG_MIP_LINEAR; AddressU = Wrap; AddressV = Wrap; }; I then grabbed the image from my local hard drive from within the .cpp file. I believe this was successful, I checked all varibles for errors, everything has a memory address. Plus I pulled resources before and never had a problem. D3DX10CreateShaderResourceViewFromFile(mpD3DDevice,L"crate.jpg",NULL,NULL,&textureSRV,NULL); I grabbed the tex2d varible from my fx file and placed into my resource varible pTextureSR = modelObject.pEffect->GetVariableByName("tex2D")->AsShaderResource(); And added the resource to the varible pTextureSR->SetResource(textureSRV); I also added the extra property to my vertex layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT, 0 , 0, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"COLOR",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 12, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 24, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD",0, DXGI_FORMAT_R32G32_FLOAT, 0 , 36, D3D10_INPUT_PER_VERTEX_DATA, 0} }; as well as my struct struct VertexPos { D3DXVECTOR3 pos; D3DXVECTOR4 color; D3DXVECTOR3 normal; D3DXVECTOR2 texCoord; }; Then I created a new pixel shader that adds the texture to it. Below is the code in its entirety matrix Projection; matrix WorldMatrix; Texture2D tex2D; float3 lightSource; float4 lightColor = {0.5, 0.5, 0.5, 0.5}; // PS_INPUT - input variables to the pixel shader // This struct is created and fill in by the // vertex shader struct PS_INPUT { float4 Pos : SV_POSITION; float4 Color : COLOR0; float4 Normal : NORMAL; float2 Tex : TEXCOORD; }; SamplerState linearSampler { Filter = MIN_MAG_MIP_LINEAR; AddressU = Wrap; AddressV = Wrap; }; //////////////////////////////////////////////// // Vertex Shader - Main Function /////////////////////////////////////////////// PS_INPUT VS(float4 Pos : POSITION, float4 Color : COLOR, float4 Normal : NORMAL, float2 Tex : TEXCOORD) { PS_INPUT psInput; // Pass through both the position and the color psInput.Pos = mul( Pos, Projection ); psInput.Normal = Normal; psInput.Tex = Tex; return psInput; } /////////////////////////////////////////////// // Pixel Shader /////////////////////////////////////////////// float4 PS(PS_INPUT psInput) : SV_Target { float4 finalColor = 0; finalColor = saturate(dot(lightSource, psInput.Normal) * lightColor); return finalColor; } float4 textured( PS_INPUT psInput ) : SV_Target { return tex2D.Sample( linearSampler, psInput.Tex ); } // Define the technique technique10 Render { pass P0 { SetVertexShader( CompileShader( vs_4_0, VS() ) ); SetGeometryShader( NULL ); SetPixelShader( CompileShader( ps_4_0, textured() ) ); } } Below is my CPU code. It maybe a little sloppy. But I am just adding code anywhere cause I am just experimenting and playing around. You should find most of the texture code at the bottom createObject #include "MyGame.h" #include "OneColorCube.h" /* This code sets a projection and shows a turning cube. What has been added is the project, rotation and a rasterizer to change the rasterization of the cube. The issue that was going on was something with the effect file which was causing the vertices not to be rendered correctly.*/ typedef struct { ID3D10Effect* pEffect; ID3D10EffectTechnique* pTechnique; //vertex information ID3D10Buffer* pVertexBuffer; ID3D10Buffer* pIndicesBuffer; ID3D10InputLayout* pVertexLayout; UINT numVertices; UINT numIndices; }ModelObject; ModelObject modelObject; // World Matrix D3DXMATRIX WorldMatrix; // View Matrix D3DXMATRIX ViewMatrix; // Projection Matrix D3DXMATRIX ProjectionMatrix; ID3D10EffectMatrixVariable* pProjectionMatrixVariable = NULL; ID3D10EffectMatrixVariable* pWorldMatrixVarible = NULL; ID3D10EffectVectorVariable* pLightVarible = NULL; ID3D10EffectShaderResourceVariable* pTextureSR; bool MyGame::InitDirect3D() { if(!DX3dApp::InitDirect3D()) { return false; } D3D10_RASTERIZER_DESC rastDesc; rastDesc.FillMode = D3D10_FILL_WIREFRAME; rastDesc.CullMode = D3D10_CULL_FRONT; rastDesc.FrontCounterClockwise = true; rastDesc.DepthBias = false; rastDesc.DepthBiasClamp = 0; rastDesc.SlopeScaledDepthBias = 0; rastDesc.DepthClipEnable = false; rastDesc.ScissorEnable = false; rastDesc.MultisampleEnable = false; rastDesc.AntialiasedLineEnable = false; ID3D10RasterizerState *g_pRasterizerState; mpD3DDevice->CreateRasterizerState(&rastDesc, &g_pRasterizerState); //mpD3DDevice->RSSetState(g_pRasterizerState); // Set up the World Matrix D3DXMatrixIdentity(&WorldMatrix); D3DXMatrixLookAtLH(&ViewMatrix, new D3DXVECTOR3(0.0f, 10.0f, -20.0f), new D3DXVECTOR3(0.0f, 0.0f, 0.0f), new D3DXVECTOR3(0.0f, 1.0f, 0.0f)); // Set up the projection matrix D3DXMatrixPerspectiveFovLH(&ProjectionMatrix, (float)D3DX_PI * 0.5f, (float)mWidth/(float)mHeight, 0.1f, 100.0f); if(!CreateObject()) { return false; } return true; } //These are actions that take place after the clearing of the buffer and before the present void MyGame::GameDraw() { static float rotationAngleY = 15.0f; static float rotationAngleX = 0.0f; static D3DXMATRIX rotationXMatrix; static D3DXMATRIX rotationYMatrix; D3DXMatrixIdentity(&rotationXMatrix); D3DXMatrixIdentity(&rotationYMatrix); // create the rotation matrix using the rotation angle D3DXMatrixRotationY(&rotationYMatrix, rotationAngleY); D3DXMatrixRotationX(&rotationXMatrix, rotationAngleX); rotationAngleY += (float)D3DX_PI * 0.0008f; rotationAngleX += (float)D3DX_PI * 0.0005f; WorldMatrix = rotationYMatrix * rotationXMatrix; // Set the input layout mpD3DDevice->IASetInputLayout(modelObject.pVertexLayout); pWorldMatrixVarible->SetMatrix((float*)&WorldMatrix); // Set vertex buffer UINT stride = sizeof(VertexPos); UINT offset = 0; mpD3DDevice->IASetVertexBuffers(0, 1, &modelObject.pVertexBuffer, &stride, &offset); // Set primitive topology mpD3DDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); //ViewMatrix._43 += 0.005f; // Combine and send the final matrix to the shader D3DXMATRIX finalMatrix = (WorldMatrix * ViewMatrix * ProjectionMatrix); pProjectionMatrixVariable->SetMatrix((float*)&finalMatrix); // make sure modelObject is valid // Render a model object D3D10_TECHNIQUE_DESC techniqueDescription; modelObject.pTechnique->GetDesc(&techniqueDescription); // Loop through the technique passes for(UINT p=0; p < techniqueDescription.Passes; ++p) { modelObject.pTechnique->GetPassByIndex(p)->Apply(0); // draw the cube using all 36 vertices and 12 triangles mpD3DDevice->Draw(36,0); } } //Render actually incapsulates Gamedraw, so you can call data before you actually clear the buffer or after you //present data void MyGame::Render() { DX3dApp::Render(); } bool MyGame::CreateObject() { //Create Layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT, 0 , 0, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"COLOR",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 12, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 24, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"TEXCOORD",0, DXGI_FORMAT_R32G32_FLOAT, 0 , 36, D3D10_INPUT_PER_VERTEX_DATA, 0} }; UINT numElements = (sizeof(layout)/sizeof(layout[0])); modelObject.numVertices = sizeof(vertices)/sizeof(VertexPos); for(int i = 0; i < modelObject.numVertices; i += 3) { D3DXVECTOR3 out; D3DXVECTOR3 v1 = vertices[0 + i].pos; D3DXVECTOR3 v2 = vertices[1 + i].pos; D3DXVECTOR3 v3 = vertices[2 + i].pos; D3DXVECTOR3 u = v2 - v1; D3DXVECTOR3 v = v3 - v1; D3DXVec3Cross(&out, &u, &v); D3DXVec3Normalize(&out, &out); vertices[0 + i].normal = out; vertices[1 + i].normal = out; vertices[2 + i].normal = out; } //Create buffer desc D3D10_BUFFER_DESC bufferDesc; bufferDesc.Usage = D3D10_USAGE_DEFAULT; bufferDesc.ByteWidth = sizeof(VertexPos) * modelObject.numVertices; bufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; D3D10_SUBRESOURCE_DATA initData; initData.pSysMem = vertices; //Create the buffer HRESULT hr = mpD3DDevice->CreateBuffer(&bufferDesc, &initData, &modelObject.pVertexBuffer); if(FAILED(hr)) return false; /* //Create indices DWORD indices[] = { 0,1,3, 1,2,3 }; ModelObject.numIndices = sizeof(indices)/sizeof(DWORD); bufferDesc.ByteWidth = sizeof(DWORD) * ModelObject.numIndices; bufferDesc.BindFlags = D3D10_BIND_INDEX_BUFFER; initData.pSysMem = indices; hr = mpD3DDevice->CreateBuffer(&bufferDesc, &initData, &ModelObject.pIndicesBuffer); if(FAILED(hr)) return false;*/ ///////////////////////////////////////////////////////////////////////////// //Set up fx files LPCWSTR effectFilename = L"effect.fx"; modelObject.pEffect = NULL; hr = D3DX10CreateEffectFromFile(effectFilename, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, mpD3DDevice, NULL, NULL, &modelObject.pEffect, NULL, NULL); if(FAILED(hr)) return false; pProjectionMatrixVariable = modelObject.pEffect->GetVariableByName("Projection")->AsMatrix(); pWorldMatrixVarible = modelObject.pEffect->GetVariableByName("WorldMatrix")->AsMatrix(); pTextureSR = modelObject.pEffect->GetVariableByName("tex2D")->AsShaderResource(); ID3D10ShaderResourceView* textureSRV; D3DX10CreateShaderResourceViewFromFile(mpD3DDevice,L"crate.jpg",NULL,NULL,&textureSRV,NULL); pLightVarible = modelObject.pEffect->GetVariableByName("lightSource")->AsVector(); //Dont sweat the technique. Get it! LPCSTR effectTechniqueName = "Render"; D3DXVECTOR3 vLight(1.0f, 1.0f, 1.0f); pLightVarible->SetFloatVector(vLight); modelObject.pTechnique = modelObject.pEffect->GetTechniqueByName(effectTechniqueName); if(modelObject.pTechnique == NULL) return false; pTextureSR->SetResource(textureSRV); //Create Vertex layout D3D10_PASS_DESC passDesc; modelObject.pTechnique->GetPassByIndex(0)->GetDesc(&passDesc); hr = mpD3DDevice->CreateInputLayout(layout, numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &modelObject.pVertexLayout); if(FAILED(hr)) return false; return true; } And here is my cube coordinates. I actually only added coordinates to one side. And that is the front side. To double check I flipped the cube in all directions just to make sure i didnt accidentally place the text on the incorrect side //Create vectors and put in vertices // Create vertex buffer VertexPos vertices[] = { // BACK SIDES { D3DXVECTOR3(-5.0f, 5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(-5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(1.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(0.0,1.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(-5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.0f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, // 2 FRONT SIDE { D3DXVECTOR3(-5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f), D3DXVECTOR2(2.0,0.0)}, { D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f), D3DXVECTOR2(0.0,2.0)}, { D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f), D3DXVECTOR2(0.0,2.0)}, { D3DXVECTOR3(5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f) , D3DXVECTOR2(2.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.0f,0.0f), D3DXVECTOR2(2.0,2.0)}, // 3 { D3DXVECTOR3(-5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(-5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(-5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, // 4 { D3DXVECTOR3(-5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, 5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, -5.0f), D3DXVECTOR4(1.0f,0.5f,0.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, // 5 { D3DXVECTOR3(5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(0.0,0.0)}, { D3DXVECTOR3(5.0f, -5.0f, 5.0f), D3DXVECTOR4(0.0f,1.0f,0.5f,0.0f), D3DXVECTOR2(0.0,0.0)}, // 6 {D3DXVECTOR3(-5.0f, 5.0f, -5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, {D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, {D3DXVECTOR3(-5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, {D3DXVECTOR3(-5.0f, 5.0f, 5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, {D3DXVECTOR3(-5.0f, -5.0f, -5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, {D3DXVECTOR3(-5.0f, -5.0f, 5.0f), D3DXVECTOR4(0.5f,0.0f,1.0f,0.0f), D3DXVECTOR2(0.0,0.0)}, };

    Read the article

  • Is a text file with names/pixel locations something a graphic artist can/should produce? [on hold]

    - by edA-qa mort-ora-y
    I have an artist working on 2D graphics for a game UI. He has no problem producing a screenshot showing all the bits, but we're having some trouble exporting this all into an easy-to-use format. For example, take the game HUD, which is a bunch of elements laid out around the screen. He exports the individual graphics for each one, but how should he communicate the positioning of each of them? My desire is to have a yaml file (or some other simple markup file) that contains the name of each asset and pixel position of that element. For example: fire_icon: pos: 20, 30 fire_bar: pos: 30, 80 Is producing such files a common task of a graphic artist? Is is reasonable to request them to produce such files as part of their graphic work?

    Read the article

  • Setting up OpenGL camera with off-center perspective

    - by user5484
    Hi, I'm using OpenGL ES (in iOS) and am struggling with setting up a viewport with an off-center distance point. Consider a game where you have a character in the left hand side of the screen, and some controls alpha'd over the left-hand side. The "main" part of the screen is on the right, but you still want to show whats in the view on the left. However when the character moves "forward" you want the character to appear to be going "straight", or "up" on the device, and not heading on an angle to the point that is geographically at the mid-x position in the screen. Here's the jist of how i set my viewport up where it is centered in the middle: // setup the camera // glMatrixMode(GL_PROJECTION); glLoadIdentity(); const GLfloat zNear = 0.1; const GLfloat zFar = 1000.0; const GLfloat fieldOfView = 90.0; // can definitely adjust this to see more/less of the scene GLfloat size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0); CGRect rect; rect.origin = CGPointMake(0.0, 0.0); rect.size = CGSizeMake(backingWidth, backingHeight); glFrustumf(-size, size, -size / (rect.size.width / rect.size.height), size / (rect.size.width / rect.size.height), zNear, zFar); glMatrixMode(GL_MODELVIEW); // rotate the whole scene by the tilt to face down on the dude const float tilt = 0.3f; const float yscale = 0.8f; const float zscale = -4.0f; glTranslatef(0.0, yscale, zscale); const int rotationMinDegree = 0; const int rotationMaxDegree = 180; glRotatef(tilt * (rotationMaxDegree - rotationMinDegree) / 2, 1.0f, 0.0f, 0.0f); glTranslatef(0, -yscale, -zscale); static float b = -25; //0; static float c = 0; // rotate by to face in the direction of the dude float a = RADIANS_TO_DEGREES(-atan2f(-gCamera.orientation.x, -gCamera.orientation.z)); glRotatef(a, 0.0, 1.0, 0.0); // and move to where it is glTranslatef(-gCamera.pos.x, -gCamera.pos.y, -gCamera.pos.z); // draw the rest of the scene ... I've tried a variety of things to make it appear as though "the dude" is off to the right: - do a translate after the frustrum to the x direction - do a rotation after the frustrum about the up/y-axis - move the camera with a biased lean to the left of the dude Nothing i do seems to produce good results, the dude will either look like he's stuck on an angle, or the whole scene will appear tilted. I'm no OpenGL expert, so i'm hoping someone can suggest some ideas or tricks on how to "off-center" these model views in OpenGL. Thanks!

    Read the article

  • C++ Little Wonders: The C++11 auto keyword redux

    - by James Michael Hare
    I’ve decided to create a sub-series of my Little Wonders posts to focus on C++.  Just like their C# counterparts, these posts will focus on those features of the C++ language that can help improve code by making it easier to write and maintain.  The index of the C# Little Wonders can be found here. This has been a busy week with a rollout of some new website features here at my work, so I don’t have a big post for this week.  But I wanted to write something up, and since lately I’ve been renewing my C++ skills in a separate project, it seemed like a good opportunity to start a C++ Little Wonders series.  Most of my development work still tends to focus on C#, but it was great to get back into the saddle and renew my C++ knowledge.  Today I’m going to focus on a new feature in C++11 (formerly known as C++0x, which is a major move forward in the C++ language standard).  While this small keyword can seem so trivial, I feel it is a big step forward in improving readability in C++ programs. The auto keyword If you’ve worked on C++ for a long time, you probably have some passing familiarity with the old auto keyword as one of those rarely used C++ keywords that was almost never used because it was the default. That is, in the code below (before C++11): 1: int foo() 2: { 3: // automatic variables (allocated and deallocated on stack) 4: int x; 5: auto int y; 6:  7: // static variables (retain their value across calls) 8: static int z; 9:  10: return 0; 11: } The variable x is assumed to be auto because that is the default, thus it is unnecessary to specify it explicitly as in the declaration of y below that.  Basically, an auto variable is one that is allocated and de-allocated on the stack automatically.  Contrast this to static variables, that are allocated statically and exist across the lifetime of the program. Because auto was so rarely (if ever) used since it is the norm, they decided to remove it for this purpose and give it new meaning in C++11.  The new meaning of auto: implicit typing Now, if your compiler supports C++ 11 (or at least a good subset of C++11 or 0x) you can take advantage of type inference in C++.  For those of you from the C# world, this means that the auto keyword in C++ now behaves a lot like the var keyword in C#! For example, many of us have had to declare those massive type declarations for an iterator before.  Let’s say we have a std::map of std::string to int which will map names to ages: 1: std::map<std::string, int> myMap; And then let’s say we want to find the age of a given person: 1: // Egad that's a long type... 2: std::map<std::string, int>::const_iterator pos = myMap.find(targetName); Notice that big ugly type definition to declare variable pos?  Sure, we could shorten this by creating a typedef of our specific map type if we wanted, but now with the auto keyword there’s no need: 1: // much shorter! 2: auto pos = myMap.find(targetName); The auto now tells the compiler to determine what type pos should be based on what it’s being assigned to.  This is not dynamic typing, it still determines the type as if it were explicitly declared and once declared that type cannot be changed.  That is, this is invalid: 1: // x is type int 2: auto x = 42; 3:  4: // can't assign string to int 5: x = "Hello"; Once the compiler determines x is type int it is exactly as if we typed int x = 42; instead, so don’t' confuse it with dynamic typing, it’s still very type-safe. An interesting feature of the auto keyword is that you can modify the inferred type: 1: // declare method that returns int* 2: int* GetPointer(); 3:  4: // p1 is int*, auto inferred type is int 5: auto *p1 = GetPointer(); 6:  7: // ps is int*, auto inferred type is int* 8: auto p2 = GetPointer(); Notice in both of these cases, p1 and p2 are determined to be int* but in each case the inferred type was different.  because we declared p1 as auto *p1 and GetPointer() returns int*, it inferred the type int was needed to complete the declaration.  In the second case, however, we declared p2 as auto p2 which means the inferred type was int*.  Ultimately, this make p1 and p2 the same type, but which type is inferred makes a difference, if you are chaining multiple inferred declarations together.  In these cases, the inferred type of each must match the first: 1: // Type inferred is int 2: // p1 is int* 3: // p2 is int 4: // p3 is int& 5: auto *p1 = GetPointer(), p2 = 42, &p3 = p2; Note that this works because the inferred type was int, if the inferred type was int* instead: 1: // syntax error, p1 was inferred to be int* so p2 and p3 don't make sense 2: auto p1 = GetPointer(), p2 = 42, &p3 = p2; You could also use const or static to modify the inferred type: 1: // inferred type is an int, theAnswer is a const int 2: const auto theAnswer = 42; 3:  4: // inferred type is double, Pi is a static double 5: static auto Pi = 3.1415927; Thus in the examples above it inferred the types int and double respectively, which were then modified to const and static. Summary The auto keyword has gotten new life in C++11 to allow you to infer the type of a variable from it’s initialization.  This simple little keyword can be used to cut down large declarations for complex types into a much more readable form, where appropriate.   Technorati Tags: C++, C++11, Little Wonders, auto

    Read the article

  • Camera rotation - First Person Camera using GLM

    - by tempvar
    I've just switched from deprecated opengl functions to using shaders and GLM math library and i'm having a few problems setting up my camera rotations (first person camera). I'll show what i've got setup so far. I'm setting up my ViewMatrix using the glm::lookAt function which takes an eye position, target and up vector // arbitrary pos and target values pos = glm::vec3(0.0f, 0.0f, 10.0f); target = glm::vec3(0.0f, 0.0f, 0.0f); up = glm::vec3(0.0f, 1.0f, 0.0f); m_view = glm::lookAt(pos, target, up); i'm using glm::perspective for my projection and the model matrix is just identity m_projection = glm::perspective(m_fov, m_aspectRatio, m_near, m_far); model = glm::mat4(1.0); I send the MVP matrix to my shader to multiply the vertex position glm::mat4 MVP = camera->getProjection() * camera->getView() * model; // in shader gl_Position = MVP * vec4(vertexPos, 1.0); My camera class has standard rotate and translate functions which call glm::rotate and glm::translate respectively void camera::rotate(float amount, glm::vec3 axis) { m_view = glm::rotate(m_view, amount, axis); } void camera::translate(glm::vec3 dir) { m_view = glm::translate(m_view, dir); } and i usually just use the mouse delta position as the amount for rotation Now normally in my previous opengl applications i'd just setup the yaw and pitch angles and have a sin and cos to change the direction vector using (gluLookAt) but i'd like to be able to do this using GLM and matrices. So at the moment i have my camera set 10 units away from the origin facing that direction. I can see my geometry fine, it renders perfectly. When i use my rotation function... camera->rotate(mouseDeltaX, glm::vec3(0, 1, 0)); What i want is for me to look to the right and left (like i would with manipulating the lookAt vector with gluLookAt) but what's happening is It just rotates the model i'm looking at around the origin, like im just doing a full circle around it. Because i've translated my view matrix, shouldn't i need to translate it to the centre, do the rotation then translate back away for it to be rotating around the origin? Also, i've tried using the rotate function around the x axis to get pitch working, but as soon as i rotate the model about 90 degrees, it starts to roll instead of pitch (gimbal lock?). Thanks for your help guys, and if i've not explained it well, basically i'm trying to get a first person camera working with matrix multiplication and rotating my view matrix is just rotating the model around the origin.

    Read the article

  • Converting 2D Physics to 3D.

    - by static void main
    I'm new to game physics and I am trying to adapt a simple 2D ball simulation for a 3D simulation with the Java3D library. I have this problem: Two things: 1) I noted down the values generated by the engine: X/Y are too high and minX/minY/maxY/maxX values are causing trouble. Sometimes the balls are drawing but not moving Sometimes they are going out of the panel Sometimes they're moving on little area Sometimes they just stick at one place... 2) I'm unable to select/define/set the default correct/suitable values considering the 3D graphics scaling/resolution while they are set with respect to 2D screen coordinates, that is my only problem. Please help. This is the code: public class Ball extends GameObject { private float x, y; // Ball's center (x, y) private float speedX, speedY; // Ball's speed per step in x and y private float radius; // Ball's radius // Collision detected by collision detection and response algorithm? boolean collisionDetected = false; // If collision detected, the next state of the ball. // Otherwise, meaningless. private float nextX, nextY; private float nextSpeedX, nextSpeedY; private static final float BOX_WIDTH = 640; private static final float BOX_HEIGHT = 480; /** * Constructor The velocity is specified in polar coordinates of speed and * moveAngle (for user friendliness), in Graphics coordinates with an * inverted y-axis. */ public Ball(String name1,float x, float y, float radius, float speed, float angleInDegree, Color color) { this.x = x; this.y = y; // Convert velocity from polar to rectangular x and y. this.speedX = speed * (float) Math.cos(Math.toRadians(angleInDegree)); this.speedY = speed * (float) Math.sin(Math.toRadians(angleInDegree)); this.radius = radius; } public void move() { if (collisionDetected) { // Collision detected, use the values computed. x = nextX; y = nextY; speedX = nextSpeedX; speedY = nextSpeedY; } else { // No collision, move one step and no change in speed. x += speedX; y += speedY; } collisionDetected = false; // Clear the flag for the next step } public void collideWith() { // Get the ball's bounds, offset by the radius of the ball float minX = 0.0f + radius; float minY = 0.0f + radius; float maxX = 0.0f + BOX_WIDTH - 1.0f - radius; float maxY = 0.0f + BOX_HEIGHT - 1.0f - radius; double gravAmount = 0.9811111f; double gravDir = (90 / 57.2960285258); // Try moving one full step nextX = x + speedX; nextY = y + speedY; System.out.println("In serializedBall in collision."); // If collision detected. Reflect on the x or/and y axis // and place the ball at the point of impact. if (speedX != 0) { if (nextX > maxX) { // Check maximum-X bound collisionDetected = true; nextSpeedX = -speedX; // Reflect nextSpeedY = speedY; // Same nextX = maxX; nextY = (maxX - x) * speedY / speedX + y; // speedX non-zero } else if (nextX < minX) { // Check minimum-X bound collisionDetected = true; nextSpeedX = -speedX; // Reflect nextSpeedY = speedY; // Same nextX = minX; nextY = (minX - x) * speedY / speedX + y; // speedX non-zero } } // In case the ball runs over both the borders. if (speedY != 0) { if (nextY > maxY) { // Check maximum-Y bound collisionDetected = true; nextSpeedX = speedX; // Same nextSpeedY = -speedY; // Reflect nextY = maxY; nextX = (maxY - y) * speedX / speedY + x; // speedY non-zero } else if (nextY < minY) { // Check minimum-Y bound collisionDetected = true; nextSpeedX = speedX; // Same nextSpeedY = -speedY; // Reflect nextY = minY; nextX = (minY - y) * speedX / speedY + x; // speedY non-zero } } speedX += Math.cos(gravDir) * gravAmount; speedY += Math.sin(gravDir) * gravAmount; } public float getSpeed() { return (float) Math.sqrt(speedX * speedX + speedY * speedY); } public float getMoveAngle() { return (float) Math.toDegrees(Math.atan2(speedY, speedX)); } public float getRadius() { return radius; } public float getX() { return x; } public float getY() { return y; } public void setX(float f) { x = f; } public void setY(float f) { y = f; } } Here's how I'm drawing the balls: public class 3DMovingBodies extends Applet implements Runnable { private static final int BOX_WIDTH = 800; private static final int BOX_HEIGHT = 600; private int currentNumBalls = 1; // number currently active private volatile boolean playing; private long mFrameDelay; private JFrame frame; private int currentFrameRate; private Ball[] ball = new Ball[currentNumBalls]; private Random rand; private Sphere[] sphere = new Sphere[currentNumBalls]; private Transform3D[] trans = new Transform3D[currentNumBalls]; private TransformGroup[] objTrans = new TransformGroup[currentNumBalls]; public 3DMovingBodies() { rand = new Random(); float angleInDegree = rand.nextInt(360); setLayout(new BorderLayout()); GraphicsConfiguration config = SimpleUniverse .getPreferredConfiguration(); Canvas3D c = new Canvas3D(config); add("Center", c); ball[0] = new Ball(0.5f, 0.0f, 0.5f, 0.4f, angleInDegree, Color.yellow); // ball[1] = new Ball(1.0f, 0.0f, 0.25f, 0.8f, angleInDegree, // Color.yellow); // ball[2] = new Ball(0.0f, 1.0f, 0.15f, 0.11f, angleInDegree, // Color.yellow); trans[0] = new Transform3D(); // trans[1] = new Transform3D(); // trans[2] = new Transform3D(); sphere[0] = new Sphere(0.5f); // sphere[1] = new Sphere(0.25f); // sphere[2] = new Sphere(0.15f); // Create a simple scene and attach it to the virtual universe BranchGroup scene = createSceneGraph(); SimpleUniverse u = new SimpleUniverse(c); u.getViewingPlatform().setNominalViewingTransform(); u.addBranchGraph(scene); startSimulation(); } public BranchGroup createSceneGraph() { // Create the root of the branch graph BranchGroup objRoot = new BranchGroup(); for (int i = 0; i < currentNumBalls; i++) { // Create a simple shape leaf node, add it to the scene graph. objTrans[i] = new TransformGroup(); objTrans[i].setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); Transform3D pos1 = new Transform3D(); pos1.setTranslation(randomPos()); objTrans[i].setTransform(pos1); objTrans[i].addChild(sphere[i]); objRoot.addChild(objTrans[i]); } BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0); Color3f light1Color = new Color3f(1.0f, 0.0f, 0.2f); Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f); DirectionalLight light1 = new DirectionalLight(light1Color, light1Direction); light1.setInfluencingBounds(bounds); objRoot.addChild(light1); // Set up the ambient light Color3f ambientColor = new Color3f(1.0f, 1.0f, 1.0f); AmbientLight ambientLightNode = new AmbientLight(ambientColor); ambientLightNode.setInfluencingBounds(bounds); objRoot.addChild(ambientLightNode); return objRoot; } public void startSimulation() { playing = true; Thread t = new Thread(this); t.start(); } public void stop() { playing = false; } public void run() { long previousTime = System.currentTimeMillis(); long currentTime = previousTime; long elapsedTime; long totalElapsedTime = 0; int frameCount = 0; while (true) { currentTime = System.currentTimeMillis(); elapsedTime = (currentTime - previousTime); // elapsed time in // seconds totalElapsedTime += elapsedTime; if (totalElapsedTime > 1000) { currentFrameRate = frameCount; frameCount = 0; totalElapsedTime = 0; } for (int i = 0; i < currentNumBalls; i++) { ball[i].move(); ball[i].collideWith(); drawworld(); } try { Thread.sleep(88); } catch (Exception e) { e.printStackTrace(); } previousTime = currentTime; frameCount++; } } public void drawworld() { for (int i = 0; i < currentNumBalls; i++) { printTG(objTrans[i], "SteerTG"); trans[i].setTranslation(new Vector3f(ball[i].getX(), ball[i].getY(), 0.0f)); objTrans[i].setTransform(trans[i]); } } private Vector3f randomPos() /* * Return a random position vector. The numbers are hardwired to be within * the confines of the box. */ { Vector3f pos = new Vector3f(); pos.x = rand.nextFloat() * 5.0f - 2.5f; // -2.5 to 2.5 pos.y = rand.nextFloat() * 2.0f + 0.5f; // 0.5 to 2.5 pos.z = rand.nextFloat() * 5.0f - 2.5f; // -2.5 to 2.5 return pos; } // end of randomPos() public static void main(String[] args) { System.out.println("Program Started"); 3DMovingBodiesbb = new 3DMovingBodies(); bb.addKeyListener(bb); MainFrame mf = new MainFrame(bb, 600, 400); } }

    Read the article

  • problem with loading in .FBX meshes in DirectX 10

    - by N0xus
    I'm trying to load in meshes into DirectX 10. I've created a bunch of classes that handle it and allow me to call in a mesh with only a single line of code in my main game class. How ever, when I run the program this is what renders: In the debug output window the following errors keep appearing: D3D10: ERROR: ID3D10Device::DrawIndexed: Input Assembler - Vertex Shader linkage error: Signatures between stages are incompatible. The reason is that Semantic 'TEXCOORD' is defined for mismatched hardware registers between the output stage and input stage. [ EXECUTION ERROR #343: DEVICE_SHADER_LINKAGE_REGISTERINDEX ] D3D10: ERROR: ID3D10Device::DrawIndexed: Input Assembler - Vertex Shader linkage error: Signatures between stages are incompatible. The reason is that the input stage requires Semantic/Index (POSITION,0) as input, but it is not provided by the output stage. [ EXECUTION ERROR #342: DEVICE_SHADER_LINKAGE_SEMANTICNAME_NOT_FOUND ] The thing is, I've no idea how to fix this. The code I'm using does work and I've simply brought all of that code into a new project of mine. There are no build errors and this only appears when the game is running The .fx file is as follows: float4x4 matWorld; float4x4 matView; float4x4 matProjection; struct VS_INPUT { float4 Pos:POSITION; float2 TexCoord:TEXCOORD; }; struct PS_INPUT { float4 Pos:SV_POSITION; float2 TexCoord:TEXCOORD; }; Texture2D diffuseTexture; SamplerState diffuseSampler { Filter = MIN_MAG_MIP_POINT; AddressU = WRAP; AddressV = WRAP; }; // // Vertex Shader // PS_INPUT VS( VS_INPUT input ) { PS_INPUT output=(PS_INPUT)0; float4x4 viewProjection=mul(matView,matProjection); float4x4 worldViewProjection=mul(matWorld,viewProjection); output.Pos=mul(input.Pos,worldViewProjection); output.TexCoord=input.TexCoord; return output; } // // Pixel Shader // float4 PS(PS_INPUT input ) : SV_Target { return diffuseTexture.Sample(diffuseSampler,input.TexCoord); //return float4(1.0f,1.0f,1.0f,1.0f); } RasterizerState NoCulling { FILLMODE=SOLID; CULLMODE=NONE; }; technique10 Render { pass P0 { SetVertexShader( CompileShader( vs_4_0, VS() ) ); SetGeometryShader( NULL ); SetPixelShader( CompileShader( ps_4_0, PS() ) ); SetRasterizerState(NoCulling); } } In my game, the .fx file and model are called and set as follows: Loading in shader file //Set the shader flags - BMD DWORD dwShaderFlags = D3D10_SHADER_ENABLE_STRICTNESS; #if defined( DEBUG ) || defined( _DEBUG ) dwShaderFlags |= D3D10_SHADER_DEBUG; #endif ID3D10Blob * pErrorBuffer=NULL; if( FAILED( D3DX10CreateEffectFromFile( TEXT("TransformedTexture.fx" ), NULL, NULL, "fx_4_0", dwShaderFlags, 0, md3dDevice, NULL, NULL, &m_pEffect, &pErrorBuffer, NULL ) ) ) { char * pErrorStr = ( char* )pErrorBuffer->GetBufferPointer(); //If the creation of the Effect fails then a message box will be shown MessageBoxA( NULL, pErrorStr, "Error", MB_OK ); return false; } //Get the technique called Render from the effect, we need this for rendering later on m_pTechnique=m_pEffect->GetTechniqueByName("Render"); //Number of elements in the layout UINT numElements = TexturedLitVertex::layoutSize; //Get the Pass description, we need this to bind the vertex to the pipeline D3D10_PASS_DESC PassDesc; m_pTechnique->GetPassByIndex( 0 )->GetDesc( &PassDesc ); //Create Input layout to describe the incoming buffer to the input assembler if (FAILED(md3dDevice->CreateInputLayout( TexturedLitVertex::layout, numElements,PassDesc.pIAInputSignature, PassDesc.IAInputSignatureSize, &m_pVertexLayout ) ) ) { return false; } model loading: m_pTestRenderable=new CRenderable(); //m_pTestRenderable->create<TexturedVertex>(md3dDevice,8,6,vertices,indices); m_pModelLoader = new CModelLoader(); m_pTestRenderable = m_pModelLoader->loadModelFromFile( md3dDevice,"armoredrecon.fbx" ); m_pGameObjectTest = new CGameObject(); m_pGameObjectTest->setRenderable( m_pTestRenderable ); // Set primitive topology, how are we going to interpet the vertices in the vertex buffer md3dDevice->IASetPrimitiveTopology( D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST ); if ( FAILED( D3DX10CreateShaderResourceViewFromFile( md3dDevice, TEXT( "armoredrecon_diff.png" ), NULL, NULL, &m_pTextureShaderResource, NULL ) ) ) { MessageBox( NULL, TEXT( "Can't load Texture" ), TEXT( "Error" ), MB_OK ); return false; } m_pDiffuseTextureVariable = m_pEffect->GetVariableByName( "diffuseTexture" )->AsShaderResource(); m_pDiffuseTextureVariable->SetResource( m_pTextureShaderResource ); Finally, the draw function code: //All drawing will occur between the clear and present m_pViewMatrixVariable->SetMatrix( ( float* )m_matView ); m_pWorldMatrixVariable->SetMatrix( ( float* )m_pGameObjectTest->getWorld() ); //Get the stride(size) of the a vertex, we need this to tell the pipeline the size of one vertex UINT stride = m_pTestRenderable->getStride(); //The offset from start of the buffer to where our vertices are located UINT offset = m_pTestRenderable->getOffset(); ID3D10Buffer * pVB=m_pTestRenderable->getVB(); //Bind the vertex buffer to input assembler stage - md3dDevice->IASetVertexBuffers( 0, 1, &pVB, &stride, &offset ); md3dDevice->IASetIndexBuffer( m_pTestRenderable->getIB(), DXGI_FORMAT_R32_UINT, 0 ); //Get the Description of the technique, we need this in order to loop through each pass in the technique D3D10_TECHNIQUE_DESC techDesc; m_pTechnique->GetDesc( &techDesc ); //Loop through the passes in the technique for( UINT p = 0; p < techDesc.Passes; ++p ) { //Get a pass at current index and apply it m_pTechnique->GetPassByIndex( p )->Apply( 0 ); //Draw call md3dDevice->DrawIndexed(m_pTestRenderable->getNumOfIndices(),0,0); //m_pD3D10Device->Draw(m_pTestRenderable->getNumOfVerts(),0); } Is there anything I've clearly done wrong or are missing? Spent 2 weeks trying to workout what on earth I've done wrong to no avail. Any insight a fresh pair eyes could give on this would be great.

    Read the article

  • Persisting NLP parsed data

    - by tjb1982
    I've recently started experimenting with NLP using Stanford's CoreNLP, and I'm wondering what are some of the standard ways to store NLP parsed data for something like a text mining application? One way I thought might be interesting is to store the children as an adjacency list and make good use of recursive queries (postgres supports this and I've found it works really well). Something like this: Component ( id, POS, parent_id ) Word ( id, raw, lemma, POS, NER ) CW_Map ( component_id, word_id, position int ) But I assume there are probably many standard ways to do this depending on what kind of analysis is being done that have been adopted by people working in the field over the years. So what are the standard persistence strategies for NLP parsed data and how are they used?

    Read the article

  • Des chercheurs en sécurité découvrent Dexter, un malware qui cible essentiellement les systèmes de point de vente

    Des chercheurs en sécurité découvrent Dexter un malware qui cible essentiellement les systèmes de point de vente Les pirates pour voler les données des cartes de crédit ont trouvé un moyen d'insérer un malware directement dans les systèmes de point de vente (POS). La firme de sécurité Seculert vient d'identifier un programme malveillant spécialement conçu pour attaquer les systèmes de point de vente. Le logiciel malveillant baptisé Dexter, aurait déjà infecté des systèmes POS dans près de 40 pays au cours des deux derniers mois. Les pays anglo-saxons semblent être les cibles favorites du malware, avec 30% d'attaque aux USA, 19% en Grande-Bretagne et 9% au Canada. L...

    Read the article

  • Calculate velocity of a bullet ricocheting on a circle

    - by SteveL
    I made a picture to demostrate what I need,basecaly I have a bullet with velocity and I want it to bounce with the correct angle after it hits a circle Solved(look the accepted answer for explain): Vector.vector.set(bullet.vel); //->v Vector.vector2.setDirection(pos, bullet.pos); //->n normal from center of circle to bullet float dot=Vector.vector.dot(Vector.vector2); //->dot product Vector.vector2.mul(dot).mul(2); Vector.vector.sub(Vector.vector2); Vector.vector.y=-Vector.vector.y; //->for some reason i had to invert the y bullet.vel.set(Vector.vector);

    Read the article

  • Better way to load level content in XNA?

    - by user2002495
    Currently I loaded all my assets in XNA in the main Game class. What I want to achieve later is that I only load specific assets for specific levels (the game will consist of many levels). Here is how I load my main assets into the main class: protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); plane = new Player(Content.Load<Texture2D>(@"Player/playerSprite"), 6, 8); plane.animation = "down"; plane.pos = new Vector2(400, 500); plane.fps = 15; Global.currentPos = plane.pos; lvl1 = new Level1(Content.Load<Texture2D>(@"Levels/bgLvl1"), Content.Load<Texture2D>(@"Levels/bgLvl1-other"), new Vector2(0, 0), new Vector2(0, -600)); CommonBullet.LoadContent(Content); CommonEnemyBullet.LoadContent(Content); } protected override void UnloadContent() { } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); plane.Update(gameTime); lvl1.Update(gameTime); foreach (CommonEnemy ce in cel) { if (ce.CollidesWith(plane)) { ce.hasSpawn = false; } foreach (CommonBullet b in plane.commonBulletList) { if (b.CollidesWith(ce)) { ce.hasSpawn = false; } } ce.Update(gameTime); } LoadCommonEnemy(); base.Update(gameTime); } private void LoadCommonEnemy() { int randY = rand.Next(-600, -10); int randX = rand.Next(0, 750); if (cel.Count < 3) { cel.Add(new CommonEnemy(Content.Load<Texture2D>(@"Enemy/Common/commonEnemySprite"), 7, 2, "left", randX, randY)); } for (int i = 0; i < cel.Count; i++) { if (!cel[i].hasSpawn) { cel.RemoveAt(i); i--; } } } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); spriteBatch.Begin(); lvl1.Draw(spriteBatch); plane.Draw(spriteBatch); foreach (CommonEnemy ce in cel) { ce.Draw(spriteBatch); } spriteBatch.End(); base.Draw(gameTime); } I wish to load my players, enemies, all in Level1 class. However, when I move my player & enemy code into the Level1 class, the gameTime returns null. Here is my Level1 class: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Media; using Microsoft.Xna.Framework.Input; using SpaceShooter_Beta.Animation.PlayerCollection; using SpaceShooter_Beta.Animation.EnemyCollection.Common; namespace SpaceShooter_Beta.Levels { public class Level1 { public Texture2D bgTexture1, bgTexture2; public Vector2 bgPos1, bgPos2; public float speed = 5f; Player plane; public Level1(Texture2D texture1, Texture2D texture2, Vector2 pos1, Vector2 pos2) { this.bgTexture1 = texture1; this.bgTexture2 = texture2; this.bgPos1 = pos1; this.bgPos2 = pos2; } public void LoadContent(ContentManager cm) { plane = new Player(cm.Load<Texture2D>(@"Player/playerSprite"), 6, 8); plane.animation = "down"; plane.pos = new Vector2(400, 500); plane.fps = 15; Global.currentPos = plane.pos; } public void Draw(SpriteBatch sb) { sb.Draw(bgTexture1, bgPos1, Color.White); sb.Draw(bgTexture2, bgPos2, Color.White); plane.Draw(sb); } public void Update(GameTime gt) { bgPos1.Y += speed; bgPos2.Y += speed; if (bgPos1.Y >= 600) { bgPos1.Y = -600; } if (bgPos2.Y >= 600) { bgPos2.Y = -600; } plane.Update(gt); } } } Of course when I did this, I delete all my player's code in the main Game class. All of that works fine (no errors) except that the game cannot start. The debugger says that plane.Update(gt); in Level 1 class has null GameTime, same thing with the Draw method in the Level class. Please help, I appreciate for the time. [EDIT] I know that using switch in the main class can be a solution. But I prefer a cleaner solution than that, since using switch still means I need to load all the assets through the main class, the code will be A LOT later on for each levels

    Read the article

  • Dealing with multiple animation state in one sprite sheet image using html5 canvas

    - by Sora
    I am recently creating a Game using html5 canvas .The player have multiple state it can walk jump kick and push and multiple other states my question is simple but after some deep research i couldn't find the best way to deal with those multiple states this is my jsfiddle : http://jsfiddle.net/Z7a5h/5/ i managed to do one animation but i started my code in a messy way ,can anyone show me a way to deal with multiple state animation for one sprite image or just give a useful link to follow and understand the concept of it please .I appreciate your help if (!this.IsWaiting) { this.IsWaiting = true; this.lastRenderTime = now; this.Pos = 1 + (this.Pos + 1) % 3; } else { if (now - this.lastRenderTime >= this.RenderRate) this.IsWaiting = false; }

    Read the article

  • I didn't mean to become a database developer, but now I am. Should I stop or try to get better?

    - by pretlow majette
    20 years ago I couldn't afford even a cheap POS program when I opened my first surf shop in the Virgin Islands. I bought a copy of Paradox (remember that?) in 1990 and spent months in a back room scratching out a POS application. Over many iterations, including a switch to Access (2000)/SQL Server (2003), I built a POS and backoffice solution that runs four stores with multiple cash registers, a warehouse and office. Until recently, all my stores were connected to the same LAN (in a small shopping center) and performance wasn't an issue. Now that we've opened a location in the States that's changed. Connecting to my local server via the internet has slowed that locations application to a crawl. This is partly due to the slow and crappy dsl service we have in the Virgin Islands, and partly due to my less-than-professional code and sql. With other far-away stores in the works, I need a better solution. I like my application. My staff knows it well, and I'm not inclined to take on the expense of a proper commercial solution. So where does that leave me? I should probably host my sql online to sidestep the slow dsl here. I think I can handle cleaning up my SQL querries to speed that up a bit. What about Access? My version seems so old, but I don't like the newer versions with the 'ribbon'. There are so many options... Should I be learning Visual Studio with an eye on moving completely to the web? Will my VBA skills help me at all there? I don't have the luxury of a year at the keyboard to figure it out anymore. What about dotnetnuke, sharepoint, or lightswitch? They all seem like possibilities, but even understanding their capabilities is daunting. I'm pretty deep into it, but maybe I should bail and hire a consultant or programmer. That sounds expensive tho, and there's no guarantee there either... Any advice would be greatly appreciated. Or, if anybody is interested in buying a small chain of surf shops...

    Read the article

  • Enemies don't shoot. What is wrong? [closed]

    - by Bryan
    I want that every enemy shoots independently bullets. If an enemy’s bullet left the screen, the enemy can shoot a new bullet. Not earlier. But for the moment, the enemies don't shoot. Not a single bullet. I guess their is something wrong with my Enemy class, but I can't find a bug and I get no error message. What is wrong? public class Map { Texture2D myEnemy, myBullet ; Player Player; List<Enemy> enemieslist = new List<Enemy>(); List<Bullet> bulletslist = new List<Bullet>(); float fNextEnemy = 0.0f; float fEnemyFreq = 3.0f; int fMaxEnemy = 3 ; Vector2 Startposition = new Vector2(200, 200); GraphicsDeviceManager graphicsDevice; public Map(GraphicsDeviceManager device) { graphicsDevice = device; } public void Load(ContentManager content) { myEnemy = content.Load<Texture2D>("enemy"); myBullet = content.Load<Texture2D>("bullet"); Player = new Player(graphicsDevice); Player.Load(content); } public void Update(GameTime gameTime) { Player.Update(gameTime); float delta = (float)gameTime.ElapsedGameTime.TotalSeconds; for(int i = enemieslist.Count - 1; i >= 0; i--) { // Update Enemy Enemy enemy = enemieslist[i]; enemy.Update(gameTime, this.graphicsDevice, Player.playershape.Position, delta); // Try to remove an enemy if (enemy.Remove == true) { enemieslist.Remove(enemy); enemy.Remove = false; } } this.fNextEnemy += delta; //New enemy if (fMaxEnemy > 0) { if ((this.fNextEnemy >= fEnemyFreq) && (enemieslist.Count < 3)) { Vector2 enemyDirection = Vector2.Normalize(Player.playershape.Position - Startposition) * 100f; enemieslist.Add(new Enemy(Startposition, enemyDirection, Player.playershape.Position)); fMaxEnemy -= 1; fNextEnemy -= fEnemyFreq; } } } public void Draw(SpriteBatch batch) { Player.Draw(batch); foreach (Enemy enemies in enemieslist) { enemies.Draw(batch, myEnemy); } foreach (Bullet bullets in bulletslist) { bullets.Draw(batch, myBullet); } } } public class Enemy { List<Bullet> bulletslist = new List<Bullet>(); private float nextShot = 0; private float shotFrequency = 2.0f; Vector2 vPos; Vector2 vMove; Vector2 vPlayer; public bool Remove; public bool Shot; public Enemy(Vector2 Pos, Vector2 Move, Vector2 Player) { this.vPos = Pos; this.vMove = Move; this.vPlayer = Player; this.Remove = false; this.Shot = false; } public void Update(GameTime gameTime, GraphicsDeviceManager graphics, Vector2 PlayerPos, float delta) { nextShot += delta; for (int i = bulletslist.Count - 1; i >= 0; i--) { // Update Bullet Bullet bullets = bulletslist[i]; bullets.Update(gameTime, graphics, delta); // Try to remove a bullet... Collision, hit, or outside screen. if (bullets.Remove == true) { bulletslist.Remove(bullets); bullets.Remove = false; } } if (nextShot >= shotFrequency) { this.Shot = true; nextShot -= shotFrequency; } // Does the enemy shot? if ((Shot == true) && (bulletslist.Count < 1)) // New bullet { Vector2 bulletDirection = Vector2.Normalize(PlayerPos - this.vPos) * 200f; bulletslist.Add(new Bullet(this.vPos, bulletDirection, PlayerPos)); Shot = false; } if (!Remove) { this.vMove = Vector2.Normalize(PlayerPos - this.vPos) * 100f; this.vPos += this.vMove * delta; if (this.vPos.X > graphics.PreferredBackBufferWidth + 1) { this.Remove = true; } else if (this.vPos.X < -20) { this.Remove = true; } if (this.vPos.Y > graphics.PreferredBackBufferHeight + 1) { this.Remove = true; } else if (this.vPos.Y < -20) { this.Remove = true; } } } public void Draw(SpriteBatch batch, Texture2D myTexture) { if (!Remove) { batch.Draw(myTexture, this.vPos, Color.White); } } } public class Bullet { Vector2 vPos; Vector2 vMove; Vector2 vPlayer; public bool Remove; public Bullet(Vector2 Pos, Vector2 Move, Vector2 Player) { this.Remove = false; this.vPos = Pos; this.vMove = Move; this.vPlayer = Player; } public void Update(GameTime gameTime, GraphicsDeviceManager graphics, float delta) { if (!Remove) { this.vPos += this.vMove * delta; if (this.vPos.X > graphics.PreferredBackBufferWidth +1) { this.Remove = true; } else if (this.vPos.X < -20) { this.Remove = true; } if (this.vPos.Y > graphics.PreferredBackBufferHeight +1) { this.Remove = true; } else if (this.vPos.Y < -20) { this.Remove = true; } } } public void Draw(SpriteBatch spriteBatch, Texture2D myTexture) { if (!Remove) { spriteBatch.Draw(myTexture, this.vPos, Color.White); } } }

    Read the article

  • Repelling a rigidbody in the direction an object is rotating

    - by ndg
    Working in Unity, I have a game object which I rotate each frame, like so: void Update() { transform.Rotate(new Vector3(0, 1, 0) * speed * Time.deltaTime); } However, I'm running into problems when it comes to applying a force to rigidbodies that collide with this game objects sphere collider. The effect I'm hoping to achieve is that objects which touch the collider are thrown in roughly the same direction as the object is rotating. To do this, I've tried the following: Vector3 force = ((transform.localRotation * Vector3.forward) * 2000) * Time.deltaTime; collision.gameObject.rigidbody.AddForce(force, ForceMode.Impulse); Unfortunately this doesn't always match the rotation of the object. To debug the issue, I wrote a simple OnDrawGizmos script, which (strangely) appears to draw the line correctly oriented to the rotation. void OnDrawGizmos() { Vector3 pos = transform.position + ((transform.localRotation * Vector3.forward) * 2); Debug.DrawLine(transform.position, pos, Color.red); } You can see the result of the OnDrawGizmos function below: What am I doing wrong?

    Read the article

  • Inserting x200s into (ultrabase) docking station mirror screen is always activated leading to non optimal resolution

    - by kiu
    Builtin LCD should be 1440x900 External LCD should be 1920x1080 If X200s is inserted into docking station the option mirror screen is always activated leading to a resolution of 1152x864 which looks terrible on the builtin and external lcd. My manual configuration for docking mode (seperate screens with maximum resolution) should be respected, but "Make Default" button has no consequences. Found a quick fix, but this cant be the offical ubuntu way... /etc/udev/rules.d/99-vga.rules: SUBSYSTEM=="drm", ACTION=="change", RUN+="/usr/local/sbin/vga_changed.sh" /usr/local/sbin/vga_changed.sh: #!/bin/bash dmode="$(cat /sys/class/drm/card0-VGA-1/status)" export DISPLAY=:0.0 if [ "${dmode}" = disconnected ]; then /usr/bin/sudo -u kiu /usr/bin/xrandr --output LVDS1 --mode 1440x900 --pos 0x0 --output VGA1 --off elif [ "${dmode}" = connected ]; then /usr/bin/sudo -u kiu /usr/bin/xrandr --output LVDS1 --mode 1440x900 --pos 0x0 --output VGA1 --auto --mode 1920x1080 --right-of LVDS1 fi

    Read the article

  • JavaScript Optimisation

    - by Jayie
    I am using JavaScript to work out all the combinations of badminton doubles matches from a given list of players. Each player teams up with everyone else. EG. If I have the following players a, b, c & d. Their combinations can be: a & b V c & d a & c V b & d a & d V b & c I am using the code below, which I wrote to do the job, but it's a little inefficient. It loops through the PLAYERS array 4 times finding every single combination (including impossible ones). It then sorts the game out into alphabetical order and stores it in the GAMES array if it doesn't already exist. I can then use the first half of the GAMES array to list all game combinations. The trouble is if I have any more than 8 players it runs really slowly because the combination growth is exponential. Does anyone know a better way or algorithm I could use? The more I think about it the more my brain hurts! var PLAYERS = ["a", "b", "c", "d", "e", "f", "g"]; var GAMES = []; var p1, p2, p3, p4, i1, i2, i3, i4, entry, found, i; var pos = 0; var TEAM1 = []; var TEAM2 = []; // loop through players 4 times to get all combinations for (i1 = 0; i1 < PLAYERS.length; i1++) { p1 = PLAYERS[i1]; for (i2 = 0; i2 < PLAYERS.length; i2++) { p2 = PLAYERS[i2]; for (i3 = 0; i3 < PLAYERS.length; i3++) { p3 = PLAYERS[i3]; for (i4 = 0; i4 < PLAYERS.length; i4++) { p4 = PLAYERS[i4]; if ((p1 != p2 && p1 != p3 && p1 != p4) && (p2 != p1 && p2 != p3 && p2 != p4) && (p3 != p1 && p3 != p2 && p3 != p4) && (p4 != p1 && p4 != p2 && p4 != p3)) { // sort teams into alphabetical order (so we can compare them easily later) TEAM1[0] = p1; TEAM1[1] = p2; TEAM2[0] = p3; TEAM2[1] = p4; TEAM1.sort(); TEAM2.sort(); // work out the game and search the array to see if it already exists entry = TEAM1[0] + " & " + TEAM1[1] + " v " + TEAM2[0] + " & " + TEAM2[1]; found = false; for (i=0; i < GAMES.length; i++) { if (entry == GAMES[i]) found = true; } // if the game is unique then store it if (!found) { GAMES[pos] = entry; document.write((pos+1) + ": " + GAMES[pos] + "<br>"); pos++; } } } } } } Thanks in advance. Jason.

    Read the article

  • Displaying emails in a JTable (Java Swing)

    - by Paul
    Hi I'm new to all this. I have been trying to display fetched emails in a JTable using the JavaMail add-on. However when I ask the program to set the value it never does. I have been working in NetBeans if that is any help? the fetchMail class finds all may on a server. The gui class is used to display all emails in a table as well as creating mail. You will probably think that I have tried it like a bull in a china shop, I am new to Java and trying to give myself a challenge. Any help/advice would be greatly appreciated fetchMail: package mail; import java.util.; import java.io.; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.mail.; import javax.mail.internet.; import javax.mail.search.; import javax.activation.; public class fetchMail { public void fetch(String username, String pass, String search){ MessagesTableModel tableModel = new MessagesTableModel(); String complete; DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); gui gui = new gui(); // SUBSTITUTE YOUR ISP's POP3 SERVER HERE!!! String host = "imap.gmail.com"; // SUBSTITUTE YOUR USERNAME AND PASSWORD TO ACCESS E-MAIL HERE!!! String user = username; String password = pass; // SUBSTITUTE YOUR SUBJECT SUBSTRING TO SEARCH HERE!!! String subjectSubstringToSearch = search; // Get a session. Use a blank Properties object. Session session = Session.getInstance(new Properties()); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.imap.socketFactory.fallback", "false"); try { // Get a Store object Store store = session.getStore("imaps"); store.connect(host, user, password); // Get "INBOX" Folder fldr = store.getFolder("INBOX"); fldr.open(Folder.READ_WRITE); int count = fldr.getMessageCount(); System.out.println(count + " total messages"); // Message numebers start at 1 for(int i = 1; i <= count; i++) { // Get a message by its sequence number Message m = fldr.getMessage(i); // Get some headers Date date = m.getSentDate(); int pos = i - 1; String d = df.format(date); Address [] from = m.getFrom(); String subj = m.getSubject(); String mimeType = m.getContentType(); complete = date + "\t" + from[0] + "\t" + subj + "\t" + mimeType; //tableModel.setMessages(m); gui.setDate(d, pos); // System.out.println(d + " " + i); } // Search for e-mails by some subject substring String pattern = subjectSubstringToSearch; SubjectTerm st = new SubjectTerm(pattern); // Get some message references Message [] found = fldr.search(st); System.out.println(found.length + " messages matched Subject pattern \"" + pattern + "\""); for (int i = 0; i < found.length; i++) { Message m = found[i]; // Get some headers Date date = m.getSentDate(); Address [] from = m.getFrom(); String subj = m.getSubject(); String mimeType = m.getContentType(); //System.out.println(date + "\t" + from[0] + "\t" + // subj + "\t" + mimeType); Object o = m.getContent(); if (o instanceof String) { // System.out.println("**This is a String Message**"); // System.out.println((String)o); } else if (o instanceof Multipart) { // System.out.print("**This is a Multipart Message. "); Multipart mp = (Multipart)o; int count3 = mp.getCount(); // System.out.println("It has " + count3 + // " BodyParts in it**"); for (int j = 0; j < count3; j++) { // Part are numbered starting at 0 BodyPart b = mp.getBodyPart(j); String mimeType2 = b.getContentType(); // System.out.println( "BodyPart " + (j + 1) + // " is of MimeType " + mimeType); Object o2 = b.getContent(); if (o2 instanceof String) { // System.out.println("**This is a String BodyPart**"); // System.out.println((String)o2); } else if (o2 instanceof Multipart) { // System.out.print( // "**This BodyPart is a nested Multipart. "); Multipart mp2 = (Multipart)o2; int count2 = mp2.getCount(); // System.out.println("It has " + count2 + // "further BodyParts in it**"); } else if (o2 instanceof InputStream) { // System.out.println( // "**This is an InputStream BodyPart**"); } } //End of for } else if (o instanceof InputStream) { // System.out.println("**This is an InputStream message**"); InputStream is = (InputStream)o; // Assumes character content (not binary images) int c; while ((c = is.read()) != -1) { // System.out.write(c); } } // Uncomment to set "delete" flag on the message //m.setFlag(Flags.Flag.DELETED,true); } //End of for // "true" actually deletes flagged messages from folder fldr.close(true); store.close(); } catch (MessagingException mex) { // Prints all nested (chained) exceptions as well mex.printStackTrace(); } catch (IOException ioex) { ioex.printStackTrace(); } } } gui: /* * gui.java * * Created on 13-May-2010, 18:29:30 */ package mail; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import javax.mail.Address; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; public class gui extends javax.swing.JFrame { private MessagesTableModel tableModel; // Table listing messages. private JTable table; String date; /** Creates new form gui */ public gui() { initComponents(); } @SuppressWarnings("unchecked") private void initComponents() { recieve = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); inboxTable = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); recieve.setText("Receve"); recieve.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { recieveActionPerformed(evt); } }); jButton1.setText("new"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); inboxTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null}, {null, null, null}, {null, null, null}, {null, null, null} }, new String [] { "Date", "subject", "sender" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane1.setViewportView(inboxTable); inboxTable.getColumnModel().getColumn(0).setResizable(false); inboxTable.getColumnModel().getColumn(1).setResizable(false); inboxTable.getColumnModel().getColumn(2).setResizable(false); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(39, 39, 39) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 558, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(recieve) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(73, 73, 73)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(recieve) .addComponent(jButton1)) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(179, Short.MAX_VALUE)) ); pack(); }// </editor-fold> private void recieveActionPerformed(java.awt.event.ActionEvent evt) { fetchMail fetch = new fetchMail(); fetch.fetch(email goes here, password goes here, search goes here); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { createMail create = new createMail(); centerW center = new centerW(); //create.attVis(); center.center(create); create.setVisible(true); } public void setDate(String Date, int pos){ //pos = pos + 1; String [] s = new String [5]; s[pos] = Date; inboxTable.setValueAt(Date, pos, 0); } public String getDate(){ return date; } /** * @param args the command line arguments */ public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new gui().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JTable inboxTable; private javax.swing.JButton jButton1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton recieve; // End of variables declaration }

    Read the article

  • mysterical error

    - by Görkem Buzcu
    i get "customer_service_simulator.exe stopped" error, but i dont know why? this is my c programming project and i have limited time left before deadline. the code is: #include <stdio.h> #include <stdlib.h> #include<time.h> #define FALSE 0 #define TRUE 1 /*A Node declaration to store a value, pointer to the next node and a priority value*/ struct Node { int priority; //arrival time int val; //type int wait_time; int departure_time; struct Node *next; }; Queue Record that will store the following: size: total number of elements stored in the list front: it shows the front node of the queue (front of the queue) rear: it shows the rare node of the queue (rear of the queue) availability: availabity of the teller struct QueueRecord { struct Node *front; struct Node *rear; int size; int availability; }; typedef struct Node *niyazi; typedef struct QueueRecord *Queue; Queue CreateQueue(int); void MakeEmptyQueue(Queue); void enqueue(Queue, int, int); int QueueSize(Queue); int FrontOfQueue(Queue); int RearOfQueue(Queue); niyazi dequeue(Queue); int IsFullQueue(Queue); int IsEmptyQueue(Queue); void DisplayQueue(Queue); void sorteddequeue(Queue); void sortedenqueue(Queue, int, int); void tellerzfunctionz(Queue *, Queue, int, int); int main() { int system_clock=0; Queue waitqueue; int exit, val, priority, customers, tellers, avg_serv_time, sim_time,counter; char command; waitqueue = CreateQueue(0); srand(time(NULL)); fflush(stdin); printf("Enter number of customers, number of tellers, average service time, simulation time\n:"); scanf("%d%c %d%c %d%c %d",&customers, &command,&tellers,&command,&avg_serv_time,&command,&sim_time); fflush(stdin); Queue tellerarray[tellers]; for(counter=0;counter<tellers;counter++){ tellerarray[counter]=CreateQueue(0); //burada teller sayisi kadar queue yaratiyorum } for(counter=0;counter<customers;counter++){ priority=1+(int)rand()%sim_time; //this will generate the arrival time sortedenqueue(waitqueue,1,priority); //here i put the customers in the waiting queue } tellerzfunctionz(tellerarray,waitqueue,tellers,customers); DisplayQueue(waitqueue); DisplayQueue(tellerarray[0]); DisplayQueue(tellerarray[1]); // waitqueue-> printf("\n\n"); system("PAUSE"); return 0; } /*This function initialises the queue*/ Queue CreateQueue(int maxElements) { Queue q; q = (struct QueueRecord *) malloc(sizeof(struct QueueRecord)); if (q == NULL) printf("Out of memory space\n"); else MakeEmptyQueue(q); return q; } /*This function sets the queue size to 0, and creates a dummy element and sets the front and rear point to this dummy element*/ void MakeEmptyQueue(Queue q) { q->size = 0; q->availability=0; q->front = (struct Node *) malloc(sizeof(struct Node)); if (q->front == NULL) printf("Out of memory space\n"); else{ q->front->next = NULL; q->rear = q->front; } } /*Shows if the queue is empty*/ int IsEmptyQueue(Queue q) { return (q->size == 0); } /*Returns the queue size*/ int QueueSize(Queue q) { return (q->size); } /*Shows the queue is full or not*/ int IsFullQueue(Queue q) { return FALSE; } /*Returns the value stored in the front of the queue*/ int FrontOfQueue(Queue q) { if (!IsEmptyQueue(q)) return q->front->next->val; else { printf("The queue is empty\n"); return -1; } } /*Returns the value stored in the rear of the queue*/ int RearOfQueue(Queue q) { if (!IsEmptyQueue(q)) return q->rear->val; else { printf("The queue is empty\n"); return -1; } } /*Displays the content of the queue*/ void DisplayQueue(Queue q) { struct Node *pos; pos=q->front->next; printf("Queue content:\n"); printf("-->Priority Value\n"); while (pos != NULL) { printf("--> %d\t %d\n", pos->priority, pos->val); pos = pos->next; } } void enqueue(Queue q, int element, int priority){ if(IsFullQueue(q)){ printf("Error queue is full"); } else{ q->rear->next=(struct Node *)malloc(sizeof(struct Node)); q->rear=q->rear->next; q->rear->next=NULL; q->rear->val=element; q->rear->priority=priority; q->size++; } } void sortedenqueue(Queue q, int val, int priority) { struct Node *insert,*temp; insert=(struct Node *)malloc(sizeof(struct Node)); insert->val=val; insert->priority=priority; temp=q->front; if(q->size==0){ enqueue(q, val, priority); } else{ while(temp->next!=NULL && temp->next->priority<insert->priority){ temp=temp->next; } //printf("%d",temp->priority); insert->next=temp->next; temp->next=insert; q->size++; if(insert->next==NULL){ q->rear=insert; } } } niyazi dequeue(Queue q) { niyazi del; niyazi deli; del=(niyazi)malloc(sizeof(struct Node)); deli=(niyazi)malloc(sizeof(struct Node)); if(IsEmptyQueue(q)){ printf("Queue is empty!"); return NULL; } else { del=q->front->next; q->front->next=del->next; deli->val=del->val; deli->priority=del->priority; free(del); q->size--; return deli; } } void sorteddequeue(Queue q) { struct Node *temp; struct Node *min; temp=q->front->next; min=q->front; int i; for(i=1;i<q->size;i++) { if(temp->next->priority<min->next->priority) { min=temp; } temp=temp->next; } temp=min->next; min->next=min->next->next; free(temp); if(min->next==NULL){ q->rear=min; } q->size--; } void tellerzfunctionz(Queue *a, Queue b, int c, int d){ int i; int value=0; int priority; niyazi temp; temp=(niyazi)malloc(sizeof(struct Node)); if(c==1){ for(i=0;i<d;i++){ temp=dequeue(b); sortedenqueue((*(a)),temp->val,temp->priority); } } else{ for(i=0;i<d;i++){ while(b->front->next->val==1){ if((*(a+value))->availability==1){ temp=dequeue(b); sortedenqueue((*(a+value)),temp->val,temp->priority); (*(a+value))->rear->val=2; } else{ value++; } } } } } //end of the program

    Read the article

  • MS cash drawer with epson TM-IV88 Status API

    - by Xience
    Does anyone know how to monitor cash drawer's open/close state using Advanced Printer Driver's Status API for Epson TM-88IV thermal printer. I wish i could use OPOS for ADK .Net, but haven't had luck setting it up on windows 7. Does anyone know how to be a part of epson developer network. I have gone through the information available at www.epson-pos.com but there is no information available on POS/ESC codes. Please help...........

    Read the article

  • Delphi 2009 - Strip non alpha numeric from string

    - by Brad
    I've got the following code, and need to strip all non alpha numeric characters. It's not working in delphi 2009 ` unit Unit2; //Used information from // http://stackoverflow.com/questions/574603/what-is-the-fastest-way-of-stripping-non-alphanumeric-characters-from-a-string-in interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; Type TExplodeArray = Array Of String; TForm2 = class(TForm) Memo1: TMemo; ListBox1: TListBox; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } Function Explode ( Const cSeparator, vString : String ) : TExplodeArray; Function Implode ( Const cSeparator : String; Const cArray : TExplodeArray ) : String; Function StripHTML ( S : String ) : String; function allwords(data:string):integer; end; var Form2: TForm2; allword, allphrase: TExplodeArray; implementation {$R *.dfm} Function TForm2.StripHTML ( S : String ) : String; Var TagBegin, TagEnd, TagLength : Integer; Begin TagBegin := Pos ( '<', S ); // search position of first < While ( TagBegin > 0 ) Do Begin // while there is a < in S TagEnd := Pos ( '>', S ); // find the matching > TagLength := TagEnd - TagBegin + 1; Delete ( S, TagBegin, TagLength ); // delete the tag TagBegin := Pos ( '<', S ); // search for next < End; Result := S; // give the result End; Function TForm2.Implode ( Const cSeparator : String; Const cArray : TExplodeArray ) : String; Var i : Integer; Begin Result := ''; For i := 0 To Length ( cArray ) - 1 Do Begin Result := Result + cSeparator + cArray [i]; End; System.Delete ( Result, 1, Length ( cSeparator ) ); End; Function TForm2.Explode ( Const cSeparator, vString : String ) : TExplodeArray; Var i : Integer; S : String; Begin S := vString; SetLength ( Result, 0 ); i := 0; While Pos ( cSeparator, S ) 0 Do Begin SetLength ( Result, Length ( Result ) + 1 ); Result[i] := Copy ( S, 1, Pos ( cSeparator, S ) - 1 ); Inc ( i ); S := Copy ( S, Pos ( cSeparator, S ) + Length ( cSeparator ), Length ( S ) ); End; SetLength ( Result, Length ( Result ) + 1 ); Result[i] := Copy ( S, 1, Length ( S ) ); End; //Copied from JclStrings function StrKeepChars(const S: AnsiString; const Chars: TSysCharSet): AnsiString; var Source, Dest: PChar; begin SetLength(Result, Length(S)); UniqueString(Result); Source := PChar(S); Dest := PChar(Result); while (Source < nil) and (Source^ < #0) do begin if Source^ in Chars then begin Dest^ := Source^; Inc(Dest); end; Inc(Source); end; SetLength(Result, (Longint(Dest) - Longint(PChar(Result))) div SizeOf(AnsiChar)); end; function ReplaceNewlines(const AValue: string): string; var SrcPtr, DestPtr: PChar; begin SrcPtr := PChar(AValue); SetLength(Result, Length(AValue)); DestPtr := PChar(Result); while SrcPtr < {greater than less than} #0 do begin if (SrcPtr[0] = #13) and (SrcPtr[1] = #10) then begin DestPtr[0] := '\'; DestPtr[1] := 't'; Inc(SrcPtr); Inc(DestPtr); end else DestPtr[0] := SrcPtr[0]; Inc(SrcPtr); Inc(DestPtr); end; SetLength(Result, DestPtr - PChar(Result)); end; function StripNonAlphaNumeric(const AValue: string): string; var SrcPtr, DestPtr: PChar; begin SrcPtr := PChar(AValue); SetLength(Result, Length(AValue)); DestPtr := PChar(Result); while SrcPtr < #0 do begin if SrcPtr[0] in ['a'..'z', 'A'..'Z', '0'..'9'] then begin DestPtr[0] := SrcPtr[0]; Inc(DestPtr); end; Inc(SrcPtr); end; SetLength(Result, DestPtr - PChar(Result)); end; function TForm2.allwords(data:string):integer; var i:integer; begin listbox1.Items.add(data); data:= StripHTML ( data ); listbox1.Items.add(data); ////////////////////////////////////////////////////////////// data := StrKeepChars(data, ['A'..'Z', 'a'..'z', '0'..'9']); // Strips out everything data comes back blank in Delphi 2009 ////////////////////////////////////////////////////////////// listbox1.Items.add(data); data := stringreplace(data,' ',' ', [rfReplaceAll, rfIgnoreCase] ); //Replace two spaces with one. listbox1.Items.add(data); allword:= explode(' ',data); { // Converting the following PHP code to Delphi $text = ereg_replace("[^[:alnum:]]", " ", $text); while(strpos($text,' ')!==false) $text = ereg_replace(" ", " ", $text); $text=$string=strtolower($text); $text=explode(" ",$text); return count($text); } for I := 0 to Length(allword) - 1 do listbox1.Items.Add(allword[i]); end; procedure TForm2.Button1Click(Sender: TObject); begin //[^[:alnum:]] allwords(memo1.Text); end; end. ` How else would I go about doing this? Thanks

    Read the article

  • a non recursive approach to the problem of generating combinations at fault

    - by mark
    Hi, I wanted a non recursive approach to the problem of generating combination of certain set of characters or numbers. So, given a subset k of numbers n, generate all the possible combination n!/k!(n-k)! The recursive method would give a combination, given the previous one combination. A non recursive method would generate a combination of a given value of loop index i. I approached the problem with this code: Tested with n = 4 and k = 3, and it works, but if I change k to a number 3 it does not work. Is it due to the fact that (n-k)! in case of n = 4 and k = 3 is 1. and if k 3 it will be more than 1? Thanks. int facto(int x); int len,fact,rem=0,pos=0; int str[7]; int avail[7]; str[0] = 1; str[1] = 2; str[2] = 3; str[3] = 4; str[4] = 5; str[5] = 6; str[6] = 7; int tot=facto(n) / facto(n-k) / facto(k); for (int i=0;i<tot;i++) { avail[0]=1; avail[1]=2; avail[2]=3; avail[3]=4; avail[4]=5; avail[5]=6; avail[6]=7; rem = facto(i+1)-1; cout<<rem+1<<". "; for(int j=len;j>0;j--) { int div = facto(j); pos = rem / div; rem = rem % div; cout<<avail[pos]<<" "; avail[pos]=avail[j]; } cout<<endl; } int facto(int x) { int fact=1; while(x0) fact*=x--; return fact; }

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >