示例#1
0
void SetupRC() {
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	shader = gltLoadShaderPairWithAttributes("pass_thru_shader.vp", "pass_thru_shader.fp", 2, GLT_ATTRIBUTE_VERTEX, "vVertex", GLT_ATTRIBUTE_NORMAL, "vNormal");
    fprintf(stdout, "GLT_ATTRIBUTE_VERTEX : %d\nGLT_ATTRIBUTE_COLOR : %d \n", GLT_ATTRIBUTE_VERTEX, GLT_ATTRIBUTE_COLOR);

	MVPMatrixLocation = glGetUniformLocation(shader,"MVPMatrix");
	normalMatrixLocation = glGetUniformLocation(shader,"normalMatrix");

	MVMatrixLocation = glGetUniformLocation(shader,"MVMatrix");
	shaderPositionLocation = glGetUniformLocation(shader, "light1.position");
	shaderColorLocation = glGetUniformLocation(shader, "light1.color");
	shaderAngleLocation = glGetUniformLocation(shader, "light1.angle");

	shaderAttenuation0Location = glGetUniformLocation(shader, "light1.attenuation0");
	shaderAttenuation1Location = glGetUniformLocation(shader, "light1.attenuation1");
	shaderAttenuation2Location = glGetUniformLocation(shader, "light1.attenuation2");

	shaderAmbientColorLocation = glGetUniformLocation(shader, "material.ambientColor");
	shaderDiffuseColorLocation = glGetUniformLocation(shader, "material.diffuseColor");
	shaderSpecularColorLocation = glGetUniformLocation(shader, "material.specularColor");
	shaderSpecularExponentLocation = glGetUniformLocation(shader, "material.specularExponent");

	glEnable(GL_DEPTH_TEST);
	LoadVertices();
	LoadFaces();
}
示例#2
0
void Init(HWND hWnd)
{
    g_hWnd = hWnd;										// Assign the window handle to a global window handle
    GetClientRect(g_hWnd, &g_rRect);					// Assign the windows rectangle to a global RECT
    InitializeOpenGL(g_rRect.right, g_rRect.bottom);	// Init OpenGL with the global rect

    // Position our camera
    g_Camera.PositionCamera(0, 30, 120,	0, 0, 0,	0, 1, 0);

    // This loads the vertices for the terrain
    LoadVertices();

    // Calculate the bounding box of our scene.  This will give us a width of
    // the cube that is needed to surround the whole world.  We want to pass in
    // the vertices and the vertex count into this function to find the farthest point
    // from the center of the world.  That will then be our width.  Depending on the
    // world this doesn't always surround it perfectly. In the next tutorial we will fix that.
    g_Octree.GetSceneDimensions(g_pVertices, g_NumberOfVerts);

    // Here we pass in the information to create the root node.  This will then
    // recursively subdivide the root node into the rest of the node.
    g_Octree.CreateNode(g_pVertices, g_NumberOfVerts, g_Octree.GetCenter(), g_Octree.GetWidth());

    // Here, we turn on a light and enable lighting.  We don't need to
    // set anything else for lighting because we will just take the defaults.
    // We also want color, so we turn that on too.  We don't load any normals from
    // our .raw file so we will calculate some simple face normals to get a decent
    // perspective of the terrain.

    glEnable(GL_LIGHT0);								// Turn on a light with defaults set
    glEnable(GL_LIGHTING);								// Turn on lighting
    glEnable(GL_COLOR_MATERIAL);						// Allow color
}
示例#3
0
vec2 Terrain::LoadVertices(
	const QuadTree<TerrainNode>::Iterator& node, 
	const Image& hmap
	)
{
	//Setup vertex data
	vec2 res = vec2(1.0f, 0.0f);
	int verticesCount = (lodResolution + 1) * (lodResolution + 1);
	vector<vec3> vertices(verticesCount), colors(verticesCount);
	float deltaX = 1.0f / node.LayerSize() / lodResolution;
	float deltaY = 1.0f / node.LayerSize() / lodResolution;
	float x = node.OffsetFloat().x;
	for (int i = 0; i <= lodResolution; i++, x += deltaX)
	{
		float y = node.OffsetFloat().y;
		for (int j = 0; j <= lodResolution; j++, y += deltaY)
		{
			float h = hmap[vec2(x, y)].x;
			res = UniteSegments(res, vec2(h));

			vertices[i*lodResolution + i + j] = vec3(x, h, y);
			colors[i*lodResolution + i + j] = vec3(0.2f, 0.2f + h, 0.4f - h);
		}
	}

	// VAO allocation
	glGenVertexArrays(1, &node->vaoID);
	// VAO setup
	glBindVertexArray(node->vaoID);
	// VBOs allocation
	glGenBuffers(2, node->vboID);
	// VBOs setup
	// vertices buffer
	glBindBuffer(GL_ARRAY_BUFFER, node->vboID[0]);
	glBufferData(GL_ARRAY_BUFFER, vertices.size() * 3 * sizeof(GLfloat), vertices.data(), GL_STATIC_DRAW);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
	glEnableVertexAttribArray(0);
	// colors buffer
	glBindBuffer(GL_ARRAY_BUFFER, node->vboID[1]);
	glBufferData(GL_ARRAY_BUFFER, colors.size() * 3 * sizeof(GLfloat), colors.data(), GL_STATIC_DRAW);
	glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), 0);
	glEnableVertexAttribArray(1);
	// indices buffer
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, GetIndicesBufferID());

	OPENGL_CHECK_FOR_ERRORS();
	// release vertex data
	vertices.clear();
	colors.clear();

	if (node.Level() < maxLOD)
	{
        for (int i : {0, 1, 2, 3})
            res = UniteSegments(res, LoadVertices(node.Add(i), hmap));
	}
	node->heights = res;

	return res;
}
示例#4
0
void MeshEntry::LoadMesh(FbxMesh * mesh,


                         QVector<quint32> &master_indices,
                         QVector<float> &master_vertices,
                         QVector<float> &master_normals,
                         QVector<float> &master_uvs,
                         QVector<float> &master_tangents,


                         bool load_normals,
                         bool load_uvs,
                         bool load_tangents,



                         qint32 & current_control_point_offset,
                         qint32 & current_polygon_offset)
{




    /**
     *Load vertices and indices of the mesh entry
     */
    LoadIndices(mesh, master_indices, current_polygon_offset, current_control_point_offset);
    LoadVertices(mesh, master_vertices, current_control_point_offset);




    /**
    *Load the entry's layers
    */
    if (load_normals)
        LoadNormals(mesh, master_normals);


    if (load_uvs)
        LoadUVs(mesh, master_uvs);


    if (load_tangents)
        LoadTangents(mesh, master_tangents);



    /**
     *Compute the transform and bounding box and load them
     */
    LoadTransform(mesh);
    LoadBoundingBox(mesh);



}
bool SceneLoader::ProcessMesh(ID3D11Device *ind3dDevice, aiMesh &inMesh , DrawableObject &inObject, std::vector<Vertex> &inVertexList, std::vector<UINT> &inIndexList, unsigned int inMaterialIndex)
{

	int inPrevIndexListSize = inIndexList.size();
	int inPrevVertexListSize = inVertexList.size();

	LoadVertices(inMesh, inVertexList, mSceneBoundingSphere);
	LoadIndices(inMesh, inIndexList);

	inObject.AddPart(inPrevVertexListSize, inPrevIndexListSize, inIndexList.size() - inPrevIndexListSize, inMaterialIndex);

	return true;
}
示例#6
0
	void Model::CreateRectangle(Vector2 dimensions, const char* vertexPath, const char* fragmentPath)
	{
		width = dimensions.x;
		height = dimensions.y;

		int halfWidth = width / 2;
		int halfHeight = height / 2;

		Vector3 positions[] =
		{
			Vector3(halfWidth, -halfHeight, 0.0f),
			Vector3(halfWidth, halfHeight, 0.0f),
			Vector3(-halfWidth, halfHeight, 0.0f),
			Vector3(-halfWidth, -halfHeight, 0.0f)
		};

		Vector2 vTexCoords[] =
		{
			Vector2(1.0, 0.0),
			Vector2(1.0, 1.0),
			Vector2(0.0, 1.0),
			Vector2(0.0, 0.0)
		};

		GLubyte vIndices[] =
		{
			0, 1, 2,
			2, 3, 0
		};

		if (!LoadShader(vertexPath, fragmentPath))
		{
			// Log error here
			return;
		}

		glBindAttribLocation(shader.GetProgram(), 0, "vPosition");

		shader.Link();

		// Figure out how to deal with modelviewprojection matrices
		mvpMatrixHandle = glGetUniformLocation(shader.GetProgram(), "MVPMatrix");

		LoadVertices(positions, vTexCoords, arraysize(positions));
		LoadIndices(vIndices, arraysize(vIndices));
		Initialize();
	}
// For reading the triangle-mesh-data chunk
static bool ReadTrimesh(OpenedFile& OFile, int32 ParentChunkEnd)
{
	int32 Location = 0;
	OFile.GetPosition(Location);
	
	assert(ModelPtr);
	
	while(Location < ParentChunkEnd)
	{
		ChunkHeaderData ChunkHeader;
		if (!ReadChunkHeader(OFile,ChunkHeader)) return false;
		
		switch(ChunkHeader.ID)
		{
		case VERTICES:
			if (!LoadChunk(OFile,ChunkHeader)) return false;
			LoadVertices();
			break;
			
		case TXTR_COORDS:
			if (!LoadChunk(OFile,ChunkHeader)) return false;
			LoadTextureCoordinates();
			break;
			
		case FACE_DATA:
			if (!ReadContainer(OFile,ChunkHeader,ReadFaceData)) return false;
			break;
			
		default:
			if (!SkipChunk(OFile,ChunkHeader)) return false;
		}
		
		// Where are we now?
		OFile.GetPosition(Location);
	}
	
	if (Location > ParentChunkEnd)
	{
		if (DBOut)
			fprintf(DBOut,"ERROR: Overran parent chunk: %ld > %ld\n",Location,ParentChunkEnd);
		return false;
	}
	return true;
}
示例#8
0
bool Terrain::LoadFromFile(const string& filename)
{
	//Unload previous terrain, if exists
	Unload();

	WriteToLog("Loading heightmap from TGA file...\n");
	Image img;
	if (!img.Load(filename))
	{
		WriteToLog("ERROR: Failed to load heightmap.\n");
		return false;
	}

	//Load neccessary data to GPU
	WriteToLog("Generating indices...\n");
	GenerateIndices();
	WriteToLog("Loading all vertex data to VAO...\n");
	LoadVertices(heightmap.Heap(), img);
	WriteToLog("OK: Terrain was loaded\n");
	return true;
}
示例#9
0
Obj* obj_load(char *filename)
{
    // open and read obj file
    int i;
    Obj *newobject;

    if((stream = fopen( filename, "r+t" )) != NULL )
    {
        // load objects, faces, and vertices How many objects in this file ?
        obj_CountObjects();
        for (i=numobjects - objectsInFile;i<numobjects;i++)
        {
            // need error check here and other mallocs
            newobject = (Obj *)malloc(sizeof(Obj));
            gameobject[i] = newobject;
            // Load in the faces
            LoadFaces(i - (numobjects - objectsInFile));
            // Load the vertices
            LoadVertices(i - (numobjects - objectsInFile));
        }
        fclose( stream );
    }
    return newobject;
}
示例#10
0
////////////////////BSP::Load///////////////
////////////////////////////////////////////
bool BSP::Load(char * filename, int curveTesselation)
{
	FILE * file;

	file=fopen(filename, "rb");
	if(!file)
	{
		errorLog.OutputError("Unable to open %s", filename);
		return false;
	}

	//read in header
	fread(&header, sizeof(BSP_HEADER), 1, file);

	//check header data is correct
	if(	header.string[0]!='I' || header.string[1]!='B' ||
		header.string[2]!='S' || header.string[3]!='P' ||
		header.version  !=0x2E )
	{
		errorLog.OutputError("%s is not a version 0x2E .bsp map file", filename);
		return false;
	}


	//Load in vertices
	if(!LoadVertices(file))
		return false;


	//Load in mesh indices
	//Calculate number of indices
	int numMeshIndices=header.directoryEntries[bspMeshIndices].length/sizeof(int);

	//Create space
	meshIndices=new int[numMeshIndices];
	if(!meshIndices)
	{
		errorLog.OutputError("Unable to allocate memory for %d mesh indices", numMeshIndices);
		return false;
	}

	//read in the mesh indices
	fseek(file, header.directoryEntries[bspMeshIndices].offset, SEEK_SET);
	fread(meshIndices, header.directoryEntries[bspMeshIndices].length, 1, file);

	

	//Load in faces
	if(!LoadFaces(file, curveTesselation))
		return false;

	
	//Load textures
	if(!LoadTextures(file))
		return false;

		
	//Load Lightmaps
	if(!LoadLightmaps(file))
		return false;


	//Load BSP Data
	if(!LoadBSPData(file))
		return false;


	//Load in entity string
	entityString=new char[header.directoryEntries[bspEntities].length];
	if(!entityString)
	{
		errorLog.OutputError(	"Unable to allocate memory for %d length entity string",
								header.directoryEntries[bspEntities].length);
		return false;
	}

	//Go to entity string in file
	fseek(file, header.directoryEntries[bspEntities].offset, SEEK_SET);
	fread(entityString, 1, header.directoryEntries[bspEntities].length, file);

	//Output the entity string
	//errorLog.OutputSuccess("Entity String: %s", entityString);


	fclose(file);

	errorLog.OutputSuccess("%s Loaded successfully", filename);

	return true;
}
示例#11
0
HRESULT InitDevice()
{
	HRESULT hr = S_OK;

	RECT rc;
	GetClientRect(g_hWnd, &rc);
	UINT width = rc.right - rc.left;
	UINT height = rc.bottom - rc.top;

	UINT createDeviceFlags = 0;
#ifdef _DEBUG
	createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

	D3D_DRIVER_TYPE driverTypes[] =
	{
		D3D_DRIVER_TYPE_HARDWARE,
		D3D_DRIVER_TYPE_WARP,
		D3D_DRIVER_TYPE_REFERENCE,
	};
	UINT numDriverTypes = ARRAYSIZE(driverTypes);

	D3D_FEATURE_LEVEL featureLevels[] =
	{
		D3D_FEATURE_LEVEL_11_0,
		D3D_FEATURE_LEVEL_10_1,
		D3D_FEATURE_LEVEL_10_0,
	};
	UINT numFeatureLevels = ARRAYSIZE(featureLevels);

	DXGI_SWAP_CHAIN_DESC sd;
	ZeroMemory(&sd, sizeof(sd));
	sd.BufferCount = 1;
	sd.BufferDesc.Width = width;
	sd.BufferDesc.Height = height;
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	sd.BufferDesc.RefreshRate.Numerator = 60;
	sd.BufferDesc.RefreshRate.Denominator = 1;
	sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.OutputWindow = g_hWnd;
	sd.SampleDesc.Count = 1;
	sd.SampleDesc.Quality = 0;
	sd.Windowed = TRUE;
	sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;

	for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
	{
		g_driverType = driverTypes[driverTypeIndex];
		hr = D3D11CreateDeviceAndSwapChain(NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels,
			D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext);
		if (SUCCEEDED(hr))
			break;
	}
	if (FAILED(hr))
		return hr;

	// Create a render target view
	ID3D11Texture2D* pBackBuffer = NULL;
	hr = g_pSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
	if (FAILED(hr))
		return hr;

	hr = g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_pRenderTargetView);
	pBackBuffer->Release();
	if (FAILED(hr))
		return hr;

	// Create depth stencil texture
	D3D11_TEXTURE2D_DESC descDepth;
	ZeroMemory(&descDepth, sizeof(descDepth));
	descDepth.Width = width;
	descDepth.Height = height;
	descDepth.MipLevels = 1;
	descDepth.ArraySize = 1;
	descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	descDepth.SampleDesc.Count = 1;
	descDepth.SampleDesc.Quality = 0;
	descDepth.Usage = D3D11_USAGE_DEFAULT;
	descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	descDepth.CPUAccessFlags = 0;
	descDepth.MiscFlags = 0;
	hr = g_pd3dDevice->CreateTexture2D(&descDepth, NULL, &g_pDepthStencil);
	if (FAILED(hr))
		return hr;

	// Create the depth stencil view
	D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
	ZeroMemory(&descDSV, sizeof(descDSV));
	descDSV.Format = descDepth.Format;
	descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	descDSV.Texture2D.MipSlice = 0;
	hr = g_pd3dDevice->CreateDepthStencilView(g_pDepthStencil, &descDSV, &g_pDepthStencilView);
	if (FAILED(hr))
		return hr;

	g_pImmediateContext->OMSetRenderTargets(1, &g_pRenderTargetView, g_pDepthStencilView);

	// Setup the viewport
	D3D11_VIEWPORT vp;
	vp.Width = (FLOAT)width;
	vp.Height = (FLOAT)height;
	vp.MinDepth = 0.0f;
	vp.MaxDepth = 1.0f;
	vp.TopLeftX = 0;
	vp.TopLeftY = 0;
	g_pImmediateContext->RSSetViewports(1, &vp);

	// Compile the vertex shader
	ID3DBlob* pVSBlob = NULL;
	hr = CompileShaderFromFile(L"Tutorial05.fx", "VS", "vs_4_0", &pVSBlob);
	if (FAILED(hr))
	{
		MessageBox(NULL,
			L"The FX file cannot be compiled.  Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
		return hr;
	}

	// Create the vertex shader
	hr = g_pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, &g_pVertexShader);
	if (FAILED(hr))
	{
		pVSBlob->Release();
		return hr;
	}

	// Define the input layout
	D3D11_INPUT_ELEMENT_DESC layout[] =
	{
		{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TEXCOORD", 0,  DXGI_FORMAT_R32G32_FLOAT, 0, 28, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "NORMAL", 0,  DXGI_FORMAT_R32G32B32_FLOAT, 0, 36, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "TANGENT", 0,  DXGI_FORMAT_R32G32B32_FLOAT, 0, 48, D3D11_INPUT_PER_VERTEX_DATA, 0 },
		{ "BINORMAL", 0,  DXGI_FORMAT_R32G32B32_FLOAT, 0, 60, D3D11_INPUT_PER_VERTEX_DATA, 0 },
	};
	UINT numElements = ARRAYSIZE(layout);

	// Create the input layout
	hr = g_pd3dDevice->CreateInputLayout(layout, numElements, pVSBlob->GetBufferPointer(),
		pVSBlob->GetBufferSize(), &g_pVertexLayout);
	pVSBlob->Release();
	if (FAILED(hr))
		return hr;

	// Set the input layout
	g_pImmediateContext->IASetInputLayout(g_pVertexLayout);

	// Compile the pixel shader
	ID3DBlob* pPSBlob = NULL;
	hr = CompileShaderFromFile(L"Tutorial05.fx", "PS", "ps_4_0", &pPSBlob);
	if (FAILED(hr))
	{
		MessageBox(NULL,
			L"The FX file cannot be compiled.  Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
		return hr;
	}

	// Create the pixel shader
	hr = g_pd3dDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, &g_pPixelShader);
	pPSBlob->Release();
	if (FAILED(hr))
		return hr;

	// -------------------------------------------------------------
	// JPE: Shaders para WireFrame
	// -------------------------------------------------------------
	// Compile the vertex shader
	ID3DBlob* pVSBlobWF = NULL;
	hr = CompileShaderFromFile(L"Tutorial05.fx", "VS_WF", "vs_4_0", &pVSBlobWF);
	if (FAILED(hr))
	{
		MessageBox(NULL,
			L"The FX file cannot be compiled.  Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
		return hr;
	}

	// Create the vertex shader
	hr = g_pd3dDevice->CreateVertexShader(pVSBlobWF->GetBufferPointer(), pVSBlobWF->GetBufferSize(), NULL, &g_pVertexShaderWF);
	pVSBlobWF->Release();
	if (FAILED(hr))
		return hr;

	// Compile the pixel shader
	ID3DBlob* pPSBlobWF = NULL;
	hr = CompileShaderFromFile(L"Tutorial05.fx", "PS_WF", "ps_4_0", &pPSBlobWF);
	if (FAILED(hr))
	{
		MessageBox(NULL,
			L"The FX file cannot be compiled.  Please run this executable from the directory that contains the FX file.", L"Error", MB_OK);
		return hr;
	}

	// Create the pixel shader
	hr = g_pd3dDevice->CreatePixelShader(pPSBlobWF->GetBufferPointer(), pPSBlobWF->GetBufferSize(), NULL, &g_pPixelShaderWF);
	pPSBlobWF->Release();
	if (FAILED(hr))
		return hr;

	// -------------------------------------------------------------

	// JPE: Create vertex buffer and index buffer
	SimpleVertex* vertices;
	WORD* indices;
	if (modelo == ModeloMono)
	{
		LoadFileOFF(&vertices, &indices, &cantVertices, &cantIndices);
	}
	else
	{
		LoadVertices(&vertices, &indices, &cantVertices, &cantIndices);
	}
	CalcularNormales(vertices, indices, cantVertices, cantIndices);

	
	// Crea Buffer para Vertices
    D3D11_BUFFER_DESC bd;
	ZeroMemory( &bd, sizeof(bd) );
    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof( SimpleVertex ) * cantVertices;
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bd.CPUAccessFlags = 0;
    D3D11_SUBRESOURCE_DATA InitData;
	ZeroMemory( &InitData, sizeof(InitData) );
    InitData.pSysMem = vertices;
    hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pVertexBuffer );
    if( FAILED( hr ) )
        return hr;

    // Set vertex buffer
    UINT stride = sizeof( SimpleVertex );
    UINT offset = 0;
    g_pImmediateContext->IASetVertexBuffers( 0, 1, &g_pVertexBuffer, &stride, &offset );

	// Crea Buffer para Indexes
	bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof( WORD ) * cantIndices;        // 36 vertices needed for 12 triangles in a triangle list
    bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
	bd.CPUAccessFlags = 0;
    InitData.pSysMem = indices;
    hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &g_pIndexBuffer );
    if( FAILED( hr ) )
        return hr;

    // Set index buffer
    g_pImmediateContext->IASetIndexBuffer( g_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0 );

    // Set primitive topology
    g_pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );

	// Create the constant buffer
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof(ConstantBuffer);
	bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	bd.CPUAccessFlags = 0;
    hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pConstantBuffer );
    if( FAILED( hr ) )
        return hr;

	// JPE: Create the constant buffer for PixelShader
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof(ConstantBufferPS);
	bd.BindFlags = D3D11_BIND_SHADER_RESOURCE;
	bd.CPUAccessFlags = 0;
	hr = g_pd3dDevice->CreateBuffer(&bd, NULL, &g_pConstantBufferPS);
	if (FAILED(hr))
		return hr;

    // Initialize the world matrix
	g_World1 = XMMatrixIdentity();
	g_World2 = XMMatrixIdentity();

	SetViewMatrix();

    // Initialize the projection matrix
	g_Projection = XMMatrixPerspectiveFovLH( XM_PIDIV2, width / (FLOAT)height, 0.01f, 100.0f );

	// JPE: Texturas
	loadTextures(g_pd3dDevice);

	// JPE: Raster state
	///*
	D3D11_RASTERIZER_DESC rasterDesc;

	// Setup the raster description which will determine how and what polygons will be drawn.
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_SOLID;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	hr = g_pd3dDevice->CreateRasterizerState(&rasterDesc, &m_rasterState);
	if (FAILED(hr))
	{
		return hr;
	}

	// Now set the rasterizer state.
	g_pImmediateContext->RSSetState(m_rasterState);
	//*/

	// JPE: Raster state para WireFrame
	// Setup the raster description which will determine how and what polygons will be drawn.
	rasterDesc.AntialiasedLineEnable = false;
	rasterDesc.CullMode = D3D11_CULL_BACK;
	rasterDesc.DepthBias = 0;
	rasterDesc.DepthBiasClamp = 0.0f;
	rasterDesc.DepthClipEnable = true;
	rasterDesc.FillMode = D3D11_FILL_WIREFRAME;
	rasterDesc.FrontCounterClockwise = false;
	rasterDesc.MultisampleEnable = false;
	rasterDesc.ScissorEnable = false;
	rasterDesc.SlopeScaledDepthBias = 0.0f;

	// Create the rasterizer state from the description we just filled out.
	hr = g_pd3dDevice->CreateRasterizerState(&rasterDesc, &m_rasterStateWF);
	if (FAILED(hr))
	{
		return hr;
	}


	// JPE: Parametros default
	if (modelo == ModeloMono)
	{
		bump = false;
		useTexture = false;
		rotate = false;
	}

    return S_OK;
}
示例#12
0
文件: map.c 项目: fielder/fenton
int
Map_Load (const char *name)
{
	int direxists;

	map_error = NULL;
	memset (&loadmap, 0, sizeof(loadmap));

	if (Data_IsDir(name, &direxists) && direxists)
	{
		loaddir = name;
		Get = GetFromDir;
	}
	else
	{
		/* no directory with the map name; try a pak */

		const char *ext = ".pak";
		char path[2048];

		if (strlen(name) > (sizeof(path) - strlen(ext) - 1))
			return Error("map name too long");
		strcpy (path, name);
		strcat (path, ext);
		if ((loadpak = Pak_Open(path)) == NULL)
			return Error("unable to open \"%s\"", path);

		Get = GetFromPak;
	}

	if (!LoadPlanes())
		goto failed;
	if (!LoadVertices())
		goto failed;
	if (!LoadEdges())
		goto failed;
	if (!LoadEdgeLoops())
		goto failed;
	if (!LoadSurfaces())
		goto failed;
	if (!LoadPortals())
		goto failed;
	if (!LoadNodes())
		goto failed;
	if (!LoadLeafs())
		goto failed;
	if (!LoadTextures())
		goto failed;

	/* success; get rid of current map & switch over */

	Map_Unload ();
	map = loadmap;
	memset (&loadmap, 0, sizeof(loadmap));

	Get = NULL;
	loadpak = Pak_Close (loadpak);
	loaddir = NULL;

	return 1;

failed:
	/* failure; keep the currently-loaded map running */

	FreeMap (&loadmap);

	Get = NULL;
	loadpak = Pak_Close (loadpak);
	loaddir = NULL;

	return 0;
}