Ejemplo n.º 1
0
/**
 * Menu interaction (enter/space/click to continue)
 */
void MenuTalker::logic() {

	if (!visible || npc==NULL) return;

	tablist.logic();

	advanceButton->enabled = false;
	closeButton->enabled = false;

	// determine active button
	if ((unsigned)dialog_node < npc->dialog.size() && !npc->dialog[dialog_node].empty() && event_cursor < npc->dialog[dialog_node].size()-1) {
		if (npc->dialog[dialog_node][event_cursor+1].type != "") {
			advanceButton->enabled = true;
			tablist.remove(closeButton);
			tablist.add(advanceButton);
		}
		else {
			closeButton->enabled = true;
			tablist.remove(advanceButton);
			tablist.add(closeButton);
		}
	}
	else {
		closeButton->enabled = true;
		tablist.remove(advanceButton);
		tablist.add(closeButton);
	}

	bool more;
	if (advanceButton->checkClick() || closeButton->checkClick()) {
		// button was clicked
		npc->processEvent(dialog_node, event_cursor);
		event_cursor++;
		more = npc->processDialog(dialog_node, event_cursor);
	}
	else if	(inpt->pressing[ACCEPT] && !inpt->lock[ACCEPT]) {
		inpt->lock[ACCEPT] = true;
		// pressed next/more
		npc->processEvent(dialog_node, event_cursor);
		event_cursor++;
		more = npc->processDialog(dialog_node, event_cursor);
	}
	else {
		textbox->logic();
		return;
	}

	if (more) {
		createBuffer();
	}
	else {
		// show the NPC Action Menu
		menu->npc->setNPC(npc);

		if (!menu->npc->selection())
			menu->npc->visible = true;
		else
			menu->npc->setNPC(NULL);

		// end dialog
		setNPC(NULL);
	}
}
Ejemplo n.º 2
0
// convert button to character output
 void decodeLetter (char input) {
	if (input == '1')
	{
		display[dLocx++] = '1';
	}
	else if (input == 'U')
	{
		screenY--;
	}
	else if (input == 'D')
	{
		screenY++;
	}
	else if (input == 'L')
	{
		screenX--;
	}
	else if (input == 'R')
	{
		screenX++;
	}
	else if (input == 'T')
	{
		if(dLocx != 0)
		{
			dLocx--;
			display[dLocx] = '\0';
		}
	}
	else if (input == 'S')
	{
			// output display buffer to OLED display
			int i;			
			createBuffer();
      UARTSend (buffer, dLocx+9);
		
			RIT128x96x4Clear();
			RIT128x96x4StringDraw("----------------------", 0, 50, 15);
			RIT128x96x4StringDraw(display, 0, 0, 15);
			RIT128x96x4StringDraw(display2, 0, 60, 15);
		
      for(i=0; i<dLocx + 1; i++)
				display[i]='\0';
      dLocx=0;
      return;
	}
	else if(input == 'P')
	{
		showError();		// Error
	}
	
	if (dLocx != 0)
	{
		if (input == '2')
		{
			if (flag == 1)
			{
				if (display[dLocx - 1] == 'A')
					display[dLocx - 1] = 'B';
				else if (display[dLocx - 1] == 'B')
					display[dLocx - 1] = 'C';
				else if (display[dLocx - 1] == 'C')
					display[dLocx - 1] = '2';
				else if (display[dLocx - 1] == '2')
					display[dLocx - 1] = 'A';
				else
					display[dLocx++] = 'A';
				
			}
			else
			{
				display[dLocx++] = 'A';
			}
		}
		else if (input == '3')
		{
			if (flag == 1)
			{
				if (display[dLocx - 1] == 'D')
					display[dLocx - 1] = 'E';
				else if (display[dLocx - 1] == 'E')
					display[dLocx - 1] = 'F';
				else if (display[dLocx - 1] == 'F')
					display[dLocx - 1] = '3';
				else if (display[dLocx - 1] == '3')
					display[dLocx - 1] = 'D';
				else
					display[dLocx++] = 'D';
			}
			else
			{
				display[dLocx++] = 'D';
			}
		}
		else if (input == '4')
		{
			if (flag == 1)
			{   
				if (display[dLocx - 1] == 'G')
					display[dLocx - 1] = 'H';
				else if (display[dLocx - 1] == 'H')
					display[dLocx - 1] = 'I';
				else if (display[dLocx - 1] == 'I')
					display[dLocx - 1] = '4';
				else if (display[dLocx - 1] == '4')
					display[dLocx - 1] = 'G';
				else
					display[dLocx++] = 'G';
			}
			else
			{
				display[dLocx++] = 'G';
			}
		}
		else if (input == '5')
		{       
			if (flag == 1)
			{
				if (display[dLocx - 1] == 'J')
					display[dLocx - 1] = 'K';
				else if (display[dLocx - 1] == 'K')
					display[dLocx - 1] = 'L';
				else if (display[dLocx - 1] == 'L')
					display[dLocx - 1] = '5';
				else if (display[dLocx - 1] == '5')
					display[dLocx - 1] = 'J';
				else
					display[dLocx++] = 'J';
			}
			else
			{
				display[dLocx++] = 'J';
			}
		}
		else if (input == '6')
		{
			if (flag == 1)  
			{   
				if (display[dLocx - 1] == 'M')
					display[dLocx - 1] = 'N';
				else if (display[dLocx - 1] == 'N')
					display[dLocx - 1] = 'O';
				else if (display[dLocx - 1] == 'O')
					display[dLocx - 1] = '6';
				else if (display[dLocx - 1] == '6')
					display[dLocx - 1] = 'M';
				else
					display[dLocx++] = 'M';
			}
			else
			{
				display[dLocx++] = 'M';
			}
		}
		else if (input == '7')
		{
			if (flag == 1)
			{
				if (display[dLocx - 1] == 'P')
					display[dLocx - 1] = 'Q';
				else if (display[dLocx - 1] == 'Q')
					display[dLocx - 1] = 'R';
				else if (display[dLocx - 1] == 'R')
					display[dLocx - 1] = 'S';
				else if (display[dLocx - 1] == 'S')
					display[dLocx - 1] = '7';
				else if (display[dLocx - 1] == '7')
					display[dLocx - 1] = 'P';
				else
					display[dLocx++] = 'P';
			}
			else
			{
				display[dLocx++] = 'P';
			}
		}
		else if (input == '8')
		{
			if (flag == 1)
			{
				if (display[dLocx - 1] == 'T')
					display[dLocx - 1] = 'U';
				else if (display[dLocx - 1] == 'U')
					display[dLocx - 1] = 'V';
				else if (display[dLocx - 1] == 'V')
					display[dLocx - 1] = '8';
				else if (display[dLocx - 1] == '8')
					display[dLocx - 1] = 'T';
				else
					display[dLocx++] = 'T';
			}
			else
			{
				display[dLocx++] = 'T';
			}
		}
		else if (input == '9')
		{
			if (flag == 1)
			{
				if (display[dLocx - 1] == 'W')
					display[dLocx - 1] = 'X';
				else if (display[dLocx - 1] == 'X')
					display[dLocx - 1] = 'Y';
				else if (display[dLocx - 1] == 'Y')
					display[dLocx - 1] = 'Z';
				else if (display[dLocx - 1] == 'Z')
					display[dLocx - 1] = '9';
				else if (display[dLocx - 1] == '9')
					display[dLocx - 1] = 'W';
				else
					display[dLocx++] = 'W';
			}
			else
			{
				display[dLocx++] = 'W';
			}
		}
		else if (input == '0')
		{
			if (flag == 1)
			{   
				if (display[dLocx - 1] == ' ')
					display[dLocx - 1] = '0';
				else if (display[dLocx - 1] == '0')
					display[dLocx - 1] = ' ';
				else
					display[dLocx++] = ' ';
			}
			else
			{
				display[dLocx++] = ' ';
			}
		}
	}
	else
	{
		if (input == '2')
		{
			display[dLocx++] = 'A';
		}
		else if (input == '3')
		{
			display[dLocx++] = 'D';
		}
		else if (input == '4')
		{
			display[dLocx++] = 'G';
		}
		else if (input == '5')
		{
			display[dLocx++] = 'J';
		}
		else if (input == '6')
		{
			display[dLocx++] = 'M';
		}
		else if (input == '7')
		{
			display[dLocx++] = 'P';
		}
		else if (input == '8')
		{
			display[dLocx++] = 'T';
		}
		else if (input == '9')
		{
			display[dLocx++] = 'W';
		}
		else if (input == '0')
		{
			display[dLocx++] = ' ';
		}
	}
	display[dLocx] = '\0';
 }       
Ejemplo n.º 3
0
void ATetrahedronMesh::create(unsigned np, unsigned nt)
{
	createBuffer(np, nt * 4);
	setNumPoints(np);
	setNumIndices(nt * 4);
}
 void GLESHardwareIndexBuffer::notifyOnContextReset()
 {
     createBuffer();
     mShadowUpdated = true;
     _updateFromShadow();
 }
Ejemplo n.º 5
0
    void SessionPrivate::processLine(const QByteArray& line)
    {
        Q_Q(Session);
        QString process = readString(line);
        QString prefix, command;
        QStringList params;

        // From RFC 1459:
        //  <message>  ::= [':' <prefix> <SPACE> ] <command> <params> <crlf>
        //  <prefix>   ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]
        //  <command>  ::= <letter> { <letter> } | <number> <number> <number>
        //  <SPACE>    ::= ' ' { ' ' }
        //  <params>   ::= <SPACE> [ ':' <trailing> | <middle> <params> ]
        //  <middle>   ::= <Any *non-empty* sequence of octets not including SPACE
        //                 or NUL or CR or LF, the first of which may not be ':'>
        //  <trailing> ::= <Any, possibly *empty*, sequence of octets not including
        //                   NUL or CR or LF>

        // parse <prefix>
        if (process.startsWith(QLatin1Char(':')))
        {
            prefix = process.mid(1, process.indexOf(QLatin1Char(' ')) - 1);
            process.remove(0, prefix.length() + 2);

            if (options & Session::StripNicks)
            {
                int index = prefix.indexOf(QRegExp(QLatin1String("[@!]")));
                if (index != -1)
                    prefix.truncate(index);
            }
        }

        // parse <command>
        command = process.mid(0, process.indexOf(QLatin1Char(' ')));
        process.remove(0, command.length() + 1);
        bool isNumeric = false;
        uint code = command.toInt(&isNumeric);

        // parse middle/params
        while (!process.isEmpty())
        {
            if (process.startsWith(QLatin1Char(':')))
            {
                process.remove(0, 1);
                params << process;
                process.clear();
            }
            else
            {
                QString param = process.mid(0, process.indexOf(QLatin1Char(' ')));
                process.remove(0, param.length() + 1);
                params << param;
            }
        }

        // handle PING/PONG
        if (command == QLatin1String("PING"))
        {
            QString arg = params.value(0);
            q->raw(QString(QLatin1String("PONG %1")).arg(arg));
            return;
        }

        // and dump
        if (isNumeric)
        {
            switch (code)
            {
                case Irc::Rfc::RPL_WELCOME:
                {
                    Buffer* buffer = createBuffer(host);
                    buffer->d_func()->setReceiver(prefix);
                    break;
                }

                case Irc::Rfc::RPL_TOPIC:
                {
                    QString topic = params.value(1);
                    QString target = resolveTarget(QString(), topic);
                    Buffer* buffer = createBuffer(target);
                    buffer->d_func()->topic = topic;
                    break;
                }

                case Irc::Rfc::RPL_NAMREPLY:
                {
                    QStringList list = params;
                    list.removeAll(QLatin1String("="));
                    list.removeAll(QLatin1String("@"));
                    list.removeAll(QLatin1String("*"));

                    QString target = resolveTarget(QString(), list.value(1));
                    Buffer* buffer = createBuffer(target);
                    QStringList names = list.value(2).split(QLatin1String(" "), QString::SkipEmptyParts);
                    foreach (const QString& name, names)
                        buffer->d_func()->addName(name);
                    break;
                }

                case Irc::Rfc::RPL_MOTDSTART:
                    motd.clear();
                    break;

                case Irc::Rfc::RPL_MOTD:
                    motd.append(params.value(1) + QLatin1Char('\n'));
                    break;

                case Irc::Rfc::RPL_ENDOFMOTD:
                    if (defaultBuffer)
                        emit defaultBuffer->motdReceived(motd);
                    motd.clear();
                    break;

                default:
                    break;
            }

            if (code == Rfc::RPL_TOPICSET && options & Session::StripNicks)
            {
                QString user = params.value(2);
                int index = user.indexOf(QRegExp(QLatin1String("[@!]")));
                if (index != -1)
                {
                    user.truncate(index);
                    params.replace(2, user);
                }
            }

            if (defaultBuffer)
                emit defaultBuffer->numericMessageReceived(prefix, code, params);

            // join auto-join channels after MOTD
            if (code == Rfc::RPL_ENDOFMOTD || code == Rfc::ERR_NOMOTD)
            {
                foreach (const QString& channel, channels)
                    q->join(channel);
            }
        }
Ejemplo n.º 6
0
// Main function 
// *********************************************************************
int main(int argc, char **argv)
{
    // set and log Global and Local work size dimensions
    szLocalWorkSize = 16;
    szGlobalWorkSize = (iNumElements + szLocalWorkSize - 1) / szLocalWorkSize * szLocalWorkSize;  // rounded up to the nearest multiple of the LocalWorkSize

    // Allocate and initialize host arrays 
    std::vector<float> radius;
    std::vector<float4> position;
    std::vector<float4> emission;
    std::vector<float4> color;
    std::vector<cl_short> reflType;
    std::vector<float4> output;
    cl_int numSpheres = parallelize(spheres, radius, position, emission, color, reflType);

    output.resize(szGlobalWorkSize);

    // Create the OpenCL context on a GPU device
    cl_int err = 0;
    cxGPUContext = clCreateContextFromType(0, CL_DEVICE_TYPE_GPU, NULL, NULL, &err);
    CL_VERIFY(err);

    // Get the list of GPU devices associated with context
    clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, 0, NULL, &szParmDataBytes);
    cdDevices = (cl_device_id*)malloc(szParmDataBytes);
    clGetContextInfo(cxGPUContext, CL_CONTEXT_DEVICES, szParmDataBytes, cdDevices, NULL);

    cqCommandQue = clCreateCommandQueue(cxGPUContext, cdDevices[0], 0, 0);

    // Allocate the OpenCL buffer memory objects for source and result on the device GMEM
    cl_mem radiusBuf = createBuffer(cxGPUContext, radius);
    cl_mem positionBuf = createBuffer(cxGPUContext, position);
    cl_mem emissionBuf = createBuffer(cxGPUContext, emission);
    cl_mem colorBuf = createBuffer(cxGPUContext, color);
    cl_mem reflTypeBuf = createBuffer(cxGPUContext, reflType);
    cl_mem outputBuf = clCreateBuffer(cxGPUContext, CL_MEM_WRITE_ONLY, sizeof(output[0]) * output.size(), NULL, 0);
    
    std::string source = readFile(cSourceFile);
    const char *cSource = source.c_str();

    // Create the program
    cpProgram = clCreateProgramWithSource(cxGPUContext, 1, &cSource, 0, 0);

    // Build the program
    err = clBuildProgram(cpProgram, 0, NULL, NULL, NULL, NULL);
    CL_VERIFY(err);

    // Create the kernel
    ckKernel = clCreateKernel(cpProgram, "radiance", &err);
    CL_VERIFY(err);

    // Set the Argument values
    CL_VERIFY(clSetKernelArg(ckKernel, 0, sizeof(cl_mem), (void*)&radiusBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 1, sizeof(cl_mem), (void*)&positionBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 2, sizeof(cl_mem), (void*)&emissionBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 3, sizeof(cl_mem), (void*)&colorBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 4, sizeof(cl_mem), (void*)&reflTypeBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 5, sizeof(cl_int), (void*)&numSpheres));
    CL_VERIFY(clSetKernelArg(ckKernel, 6, sizeof(cl_mem), (void*)&outputBuf));
    CL_VERIFY(clSetKernelArg(ckKernel, 7, sizeof(cl_int), (void*)&width));
    CL_VERIFY(clSetKernelArg(ckKernel, 8, sizeof(cl_int), (void*)&height));

    // --------------------------------------------------------
    // Start Core sequence... copy input data to GPU, compute, copy results back

    // Launch kernel
    CL_VERIFY(clEnqueueNDRangeKernel(cqCommandQue, ckKernel, 1, NULL, &szGlobalWorkSize, &szLocalWorkSize, 0, NULL, NULL));

    // Synchronous/blocking read of results, and check accumulated errors
    CL_VERIFY(clEnqueueReadBuffer(cqCommandQue, outputBuf, CL_TRUE, 0, sizeof(output[0]) * output.size(), &output.front(), 0, NULL, NULL));

    writePPM(output);
    writeRaw(output);

    // Cleanup and leave
    Cleanup (EXIT_SUCCESS);
}
Ejemplo n.º 7
0
HRESULT Buffer::initialize(ID3D11Device *p_Device, ID3D11DeviceContext *p_DeviceContext,
	Description &p_Description)
{
	HRESULT result = S_OK;
	D3D11_BUFFER_DESC bufferDescription;

	m_Device = p_Device;
	m_DeviceContext = p_DeviceContext;
	m_Type = p_Description.type;

	bufferDescription.StructureByteStride = 0;
	bufferDescription.MiscFlags = 0;

	switch (m_Type)
	{
	case Type::VERTEX_BUFFER:
	{
								bufferDescription.BindFlags = D3D11_BIND_VERTEX_BUFFER;
								if (p_Description.usage == Usage::STREAM_OUT_TARGET)
								{
									bufferDescription.BindFlags |= D3D11_BIND_STREAM_OUTPUT;
								}
								break;
	}
	case Type::INDEX_BUFFER:
	{
							   bufferDescription.BindFlags = D3D11_BIND_INDEX_BUFFER;
							   break;
	}
	case Type::CONSTANT_BUFFER_VS:
	case Type::CONSTANT_BUFFER_GS:
	case Type::CONSTANT_BUFFER_PS:
	case Type::BUFFER_TYPE_COUNT:
	case Type::CONSTANT_BUFFER_ALL:
	{
									  bufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
									  break;
	}
	case  Type::STAGING_BUFFER:
	{
								  bufferDescription.BindFlags = 0;
								  break;
	}

	case Type::STRUCTURED_BUFFER:
	{
									bufferDescription.MiscFlags = D3D11_RESOURCE_MISC_BUFFER_STRUCTURED;
									bufferDescription.StructureByteStride = p_Description.sizeOfElement;
									bufferDescription.BindFlags = 0;
									break;
	}

	default:
	{
			   return S_FALSE;
			   break;
	}
	}

	if (p_Description.bindSRV)	bufferDescription.BindFlags |= D3D11_BIND_SHADER_RESOURCE;
	if (p_Description.bindUAV)	bufferDescription.BindFlags |= D3D11_BIND_UNORDERED_ACCESS;

	m_Usage = p_Description.usage;
	m_SizeOfElement = p_Description.sizeOfElement;
	m_NumOfElements = p_Description.numOfElements;
	bufferDescription.CPUAccessFlags = 0;
	switch (m_Usage)
	{
	case Usage::DEFAULT:
	{
						   bufferDescription.Usage = D3D11_USAGE_DEFAULT;
						   break;
	}
	case Usage::STREAM_OUT_TARGET:
	{
									 bufferDescription.Usage = D3D11_USAGE_DEFAULT;
									 break;
	}
	case Usage::CPU_WRITE:
	{
							 bufferDescription.Usage = D3D11_USAGE_DYNAMIC;
							 bufferDescription.CPUAccessFlags |= D3D11_CPU_ACCESS_WRITE;
							 break;
	}
	case Usage::CPU_WRITE_DISCARD:
	{
									 bufferDescription.Usage = D3D11_USAGE_DYNAMIC;
									 bufferDescription.CPUAccessFlags |= D3D11_CPU_ACCESS_WRITE;
									 break;
	}
	case Usage::CPU_READ:
	{
							if (m_Type != Type::STAGING_BUFFER)
							{
								throw BufferException("Cannot set CPU read to other than staging buffer", __LINE__, __FILE__);
							}
							bufferDescription.Usage = D3D11_USAGE_STAGING;
							bufferDescription.CPUAccessFlags |= D3D11_CPU_ACCESS_READ;
							break;
	}
	case Usage::USAGE_COUNT:
	{
							   bufferDescription.Usage = D3D11_USAGE_DEFAULT;
							   break;
	}
	case Usage::USAGE_IMMUTABLE:
	{
								   bufferDescription.Usage = D3D11_USAGE_IMMUTABLE;
								   break;
	}
	default:
	{
			   break;
	}
	}

	bufferDescription.ByteWidth = p_Description.numOfElements * p_Description.sizeOfElement;

	bufferDescription.ByteWidth = ((bufferDescription.ByteWidth + 15) / 16) * 16;

	if (p_Description.initData)
	{
		D3D11_SUBRESOURCE_DATA data;
		data.pSysMem = p_Description.initData;
		data.SysMemPitch = 0;
		data.SysMemSlicePitch = 0;
		result = createBuffer(&bufferDescription, &data, &m_Buffer);
	}
	else
	{
		result = createBuffer(&bufferDescription, nullptr, &m_Buffer);
	}

	return result;
}
Ejemplo n.º 8
0
vkts::IImageDataSP Example::gatherImageData() const
{
	VkResult result;

	auto fence = vkts::fenceCreate(device->getDevice(), 0);

	if (!fence.get())
	{
		vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not create fence.");

		return vkts::IImageDataSP();
	}

	//

	auto imageData = vkts::imageDataCreate(VKTS_IMAGE_NAME, VKTS_IMAGE_LENGTH, VKTS_IMAGE_LENGTH, 1, 1.0f, 0.0f, 0.0f, 1.0f, VK_IMAGE_TYPE_2D, VK_FORMAT_R8G8B8A8_UNORM);

	// Check, if we can use a linear tiled image for staging.
	if (physicalDevice->isImageTilingAvailable(VK_IMAGE_TILING_LINEAR, imageData->getFormat(), imageData->getImageType(), 0, imageData->getExtent3D(), imageData->getMipLevels(), 1, VK_SAMPLE_COUNT_1_BIT, imageData->getSize()))
	{
		vkts::IImageSP stageImage;
		vkts::IDeviceMemorySP stageDeviceMemory;

		if (!createTexture(stageImage, stageDeviceMemory, VK_IMAGE_TILING_LINEAR, VK_IMAGE_USAGE_TRANSFER_DST_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 0))
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not create stage image and device memory.");

			return vkts::IImageDataSP();
		}

		//

		cmdBuffer->reset();


		result = cmdBuffer->beginCommandBuffer(0, VK_NULL_HANDLE, 0, VK_NULL_HANDLE, VK_FALSE, 0, 0);

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not begin command buffer.");

			return vkts::IImageDataSP();
		}

		VkImageSubresourceRange imageSubresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };

		// Prepare stage image for final layout etc.
		stageImage->cmdPipelineBarrier(cmdBuffer->getCommandBuffer(), VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, imageSubresourceRange);

		VkImageCopy imageCopy;

		imageCopy.srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
		imageCopy.srcOffset = {0, 0, 0};
		imageCopy.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
		imageCopy.dstOffset = {0, 0, 0};
		imageCopy.extent = { VKTS_IMAGE_LENGTH, VKTS_IMAGE_LENGTH, 1u };

		// Copy form device to host visible image / memory. This command also sets the needed barriers.
		image->copyImage(cmdBuffer->getCommandBuffer(), stageImage, imageCopy);

		stageImage->cmdPipelineBarrier(cmdBuffer->getCommandBuffer(), VK_ACCESS_HOST_READ_BIT, VK_IMAGE_LAYOUT_GENERAL, imageSubresourceRange);

		result = cmdBuffer->endCommandBuffer();

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not end command buffer.");

			return VK_FALSE;
		}


		VkSubmitInfo submitInfo{};

		submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;

		submitInfo.waitSemaphoreCount = 0;
		submitInfo.pWaitSemaphores = nullptr;
		submitInfo.commandBufferCount = 1;
		submitInfo.pCommandBuffers = cmdBuffer->getCommandBuffers();
		submitInfo.signalSemaphoreCount = 0;
		submitInfo.pSignalSemaphores = nullptr;

		result = queue->submit(1, &submitInfo, fence->getFence());

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not submit queue.");

			return vkts::IImageDataSP();
		}

		//

		result = fence->waitForFence(UINT64_MAX);

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not wait for fence.");

			return vkts::IImageDataSP();
		}

		//
		// Copy pixel data from device memory into image data memory.
		//

		VkImageSubresource imageSubresource;

		imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
		imageSubresource.mipLevel = 0;
		imageSubresource.arrayLayer = 0;

		VkSubresourceLayout subresourceLayout;

		stageImage->getImageSubresourceLayout(subresourceLayout, imageSubresource);

		//

		result = stageDeviceMemory->mapMemory(0, VK_WHOLE_SIZE, 0);

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not map memory.");

			return vkts::IImageDataSP();
		}

		imageData->upload(stageDeviceMemory->getMemory(), 0, 0, subresourceLayout);

		if (!(stageDeviceMemory->getMemoryPropertyFlags() & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
		{
			result = stageDeviceMemory->invalidateMappedMemoryRanges(0, VK_WHOLE_SIZE);

			if (result != VK_SUCCESS)
			{
				vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not invalidate memory.");

				return VK_FALSE;
			}
		}

		stageDeviceMemory->unmapMemory();

		// Stage image and device memory are automatically destroyed.
	}
	else
	{
		// As an alternative, use the buffer.

		vkts::IBufferSP stageBuffer;
		vkts::IDeviceMemorySP stageDeviceMemory;

		VkBufferCreateInfo bufferCreateInfo{};

        bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
        bufferCreateInfo.size = imageData->getSize();
        bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
        bufferCreateInfo.flags = 0;
        bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
        bufferCreateInfo.queueFamilyIndexCount = 0;
        bufferCreateInfo.pQueueFamilyIndices = nullptr;

        if (!createBuffer(stageBuffer, stageDeviceMemory, bufferCreateInfo, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
        {
    		vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not create buffer.");

			return vkts::IImageDataSP();
        }


		//

		cmdBuffer->reset();


		result = cmdBuffer->beginCommandBuffer(0, VK_NULL_HANDLE, 0, VK_NULL_HANDLE, VK_FALSE, 0, 0);

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not begin command buffer.");

			return vkts::IImageDataSP();
		}

		VkBufferImageCopy bufferImageCopy;

		bufferImageCopy.bufferOffset = 0;
		bufferImageCopy.bufferRowLength = VKTS_IMAGE_LENGTH;
		bufferImageCopy.bufferImageHeight = VKTS_IMAGE_LENGTH;
		bufferImageCopy.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1};
		bufferImageCopy.imageOffset = {0, 0, 0};
		bufferImageCopy.imageExtent = {VKTS_IMAGE_LENGTH, VKTS_IMAGE_LENGTH, 1};

		image->copyImageToBuffer(cmdBuffer->getCommandBuffer(), stageBuffer, bufferImageCopy);


		result = cmdBuffer->endCommandBuffer();

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not end command buffer.");

			return VK_FALSE;
		}


		VkSubmitInfo submitInfo{};

		submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;

		submitInfo.waitSemaphoreCount = 0;
		submitInfo.pWaitSemaphores = nullptr;
		submitInfo.commandBufferCount = 1;
		submitInfo.pCommandBuffers = cmdBuffer->getCommandBuffers();
		submitInfo.signalSemaphoreCount = 0;
		submitInfo.pSignalSemaphores = nullptr;

		result = queue->submit(1, &submitInfo, fence->getFence());

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not submit queue.");

			return vkts::IImageDataSP();
		}

		//

		result = fence->waitForFence(UINT64_MAX);

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not wait for fence.");

			return vkts::IImageDataSP();
		}

		//
		// Copy pixel data from device memory into image data memory.
		//

		VkSubresourceLayout subresourceLayout;

		subresourceLayout.offset = 0;
		subresourceLayout.size = stageBuffer->getSize();
		subresourceLayout.rowPitch = VKTS_IMAGE_LENGTH * 4 * sizeof(uint8_t);
		subresourceLayout.arrayPitch = VKTS_IMAGE_LENGTH * VKTS_IMAGE_LENGTH * 4 * sizeof(uint8_t);
		subresourceLayout.depthPitch = VKTS_IMAGE_LENGTH * VKTS_IMAGE_LENGTH * 4 * sizeof(uint8_t);

		result = stageDeviceMemory->mapMemory(0, VK_WHOLE_SIZE, 0);

		if (result != VK_SUCCESS)
		{
			vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not map memory.");

			return vkts::IImageDataSP();
		}

		imageData->upload(stageDeviceMemory->getMemory(), 0, 0, subresourceLayout);

		if (!(stageDeviceMemory->getMemoryPropertyFlags() & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
		{
			result = stageDeviceMemory->invalidateMappedMemoryRanges(0, VK_WHOLE_SIZE);

			if (result != VK_SUCCESS)
			{
				vkts::logPrint(VKTS_LOG_ERROR, __FILE__, __LINE__, "Could not invalidate memory.");

				return VK_FALSE;
			}
		}

		stageDeviceMemory->unmapMemory();

		// Stage image and device memory are automatically destroyed.
	}

	// Fence is automatically destroyed.

	return imageData;
}
Ejemplo n.º 9
0
	return Lav_ERROR_NONE;
}

LavError createBuffer(LavHandle sim, LavHandle& h) {
	ERRCHECK(Lav_createBufferNode(sim, &h));
	LavHandle b;
	ERRCHECK(Lav_createBuffer(sim, &b));
	ERRCHECK(Lav_bufferLoadFromArray(b, 44100, 4, BUFFER_SIZE/4, buffer));
	ERRCHECK(Lav_nodeSetBufferProperty(h, Lav_BUFFER_BUFFER, b));
	return Lav_ERROR_NONE;
}

std::tuple<std::string, int, std::function<std::vector<LavHandle>(LavHandle, int)>> to_profile[] = {
ENTRY("sine", 1000, Lav_createSineNode(sim, &h)),
ENTRY("Blit", 1000, Lav_createBlitNode(sim, &h)),
ENTRY("4-channel buffer", 100, createBuffer(sim, h)),
ENTRY("crossfading delay line", 1000, Lav_createCrossfadingDelayNode(sim, 0.1, 1, &h)),
ENTRY("biquad", 1000, Lav_createBiquadNode(sim, 1, &h)),
ENTRY("One-pole filter", 1000, Lav_createOnePoleFilterNode(sim, 1, &h)),
ENTRY("2-channel 2-input crossfader", 500, createCrossfader(sim, h)),
ENTRY("amplitude panner", 1000, Lav_createAmplitudePannerNode(sim, &h)),
ENTRY("HRTF panner", 30, Lav_createHrtfNode(sim, "default", &h)),
ENTRY("hard limiter", 1000, Lav_createHardLimiterNode(sim, 2, &h)),
ENTRY("channel splitter", 1000, Lav_createChannelSplitterNode(sim, 10, &h)),
ENTRY("channel merger", 1000, Lav_createChannelMergerNode(sim, 10, &h)),
ENTRY("noise", 100, Lav_createNoiseNode(sim, &h)),
ENTRY("ringmod", 1000, Lav_createRingmodNode(sim, &h)),
ENTRY("16x16 FDN", 1, Lav_createFeedbackDelayNetworkNode(sim, 1.0f, 16, &h)),
ENTRY("32x32 FDN", 1, Lav_createFeedbackDelayNetworkNode(sim, 1.0f, 32, &h)),
};
int to_profile_size=sizeof(to_profile)/sizeof(to_profile[0]);
Ejemplo n.º 10
0
Buffer& DataSource::getBuffer()
{
	if( ! mBuffer )
		createBuffer();
	return mBuffer;
}
Ejemplo n.º 11
0
bool AudioBufferManager::init_process_mode(AudioBufferParam_t& aParam)
{
	mLenOfSample = aParam.mLenOfSample;
	mInChannelNum = aParam.mInChannelNum;
	mOutChannelNum = aParam.mOutChannelNum;
	mProcessBufferNum = mInChannelNum > mOutChannelNum ? mInChannelNum : mOutChannelNum;

	mInDefBufferSize = aParam.mFrameShiftSize;
	mFrameShiftSize = aParam.mFrameShiftSize;
	mInitDelay = aParam.mInitDelaySize;

	mInDefBufferLen = mLenOfSample * mInDefBufferSize;
	mProcessBufferLen = mLenOfSample * mFrameShiftSize;
	mFrameShiftLen = mLenOfSample * mFrameShiftSize;

	if (0 == mLenOfSample || 0 == mFrameShiftSize)
	{
		AUDIO_PROCESSING_PRINTF("init param is invalid!");
		return false;
	}

	if(NULL != mpBufferCondition)
	{
		for (CAUDIO_U8_t channelIndex = 0; channelIndex < mInChannelNum; channelIndex++)
		{
			deleteBuffer(mpBufferCondition[channelIndex].mpInDeficiencyBuffer);
		}

		for (CAUDIO_U8_t channelIndex = 0; channelIndex < mOutChannelNum; channelIndex++)
		{
			deleteBuffer(mpBufferCondition[channelIndex].mpPostProcessBuffer);
		}

		for (CAUDIO_U8_t channelIndex = 0; channelIndex < mProcessBufferNum; channelIndex++)
		{
			deleteBuffer(mpBufferCondition[channelIndex].mpProcessBuffer);
		}

		delete[] mpBufferCondition;
		mpBufferCondition = NULL;
	}

	mpBufferCondition = new BufferCondition_t[mProcessBufferNum];
	memset(mpBufferCondition, 0, mProcessBufferNum*sizeof(BufferCondition_t));
	if (NULL == mpBufferCondition)
	{
		AUDIO_PROCESSING_PRINTF("alloc mpBufferCondition failed!");
		return false;
	}

	for (CAUDIO_U8_t channelIndex = 0; channelIndex < mInChannelNum; channelIndex++)
	{
		if (!createBuffer(mpBufferCondition[channelIndex].mpInDeficiencyBuffer, mInDefBufferLen))
		{
			AUDIO_PROCESSING_PRINTF("create in deficiency buffer failed!");
			return false;
		}
		mpBufferCondition[channelIndex].mInDefBufferWritePtr = 0;
		//mpBufferCondition[channelIndex].mInDefBufferWritePtr = mLenOfSample*mFrameShiftSize / 2;
	}

	for (CAUDIO_U8_t channelIndex = 0; channelIndex < mProcessBufferNum; channelIndex++)
	{
		if (!createBuffer(mpBufferCondition[channelIndex].mpProcessBuffer, mProcessBufferLen))
		{
			AUDIO_PROCESSING_PRINTF("create out deficiency buffer failed!");
			return false;
		}
	}

	for (CAUDIO_U8_t channelIndex = 0; channelIndex < mOutChannelNum; channelIndex++)
	{
		// introduce mInitDelay at the beginning of output
		mpBufferCondition[channelIndex].mPostProBufWrtPtr = mInitDelay * mLenOfSample;
		mPostProcessBufferLen = aParam.mPostProcessBufferLen;
		if (!createBuffer(mpBufferCondition[channelIndex].mpPostProcessBuffer, mPostProcessBufferLen))
		{
			AUDIO_PROCESSING_PRINTF("create out post process buffer failed!");
			return false;
		}
	}

	if(NULL != mppProcessBufferPtrs)
	{
		delete[] mppProcessBufferPtrs;
		mppProcessBufferPtrs = NULL;
	}
	mppProcessBufferPtrs = (void**) new CAUDIO_U8_t[mProcessBufferNum * sizeof(void*)];
	if (NULL == mppProcessBufferPtrs)
	{
		AUDIO_PROCESSING_PRINTF("mppProcessBufferPtrs alloc failed!");
		return false;
	}

	for (CAUDIO_U8_t channelIndex = 0; channelIndex < mProcessBufferNum; channelIndex++)
	{
		mppProcessBufferPtrs[channelIndex] = mpBufferCondition[channelIndex].mpProcessBuffer;
	}

	return true;
}
Ejemplo n.º 12
0
bool AudioBufferManager::init_buffer_mode(AudioBufferParam_t& aParam)
{
	mLenOfSample = aParam.mLenOfSample;
	mInChannelNum = aParam.mInChannelNum;
	mOutChannelNum = aParam.mOutChannelNum;
	if(mInChannelNum != mOutChannelNum)
	{
		AUDIO_PROCESSING_PRINTF("in channel num and out channel num should be the same in buffer mode");
		return false;
	}

	mProcessBufferNum = mInChannelNum;

	mInDefBufferSize = aParam.mFrameShiftSize;
	mFrameShiftSize = aParam.mFrameShiftSize;
	mInitDelay = aParam.mInitDelaySize;

	mInDefBufferLen = mLenOfSample * mInDefBufferSize;
	//mProcessBufferLen = mLenOfSample * mFrameShiftSize;
	mFrameShiftLen = mLenOfSample * mFrameShiftSize;

	if (0 == mLenOfSample || 0 == mFrameShiftSize)
	{
		AUDIO_PROCESSING_PRINTF("init param is invalid!");
		return false;
	}

	if(NULL != mpBufferCondition)
	{
		for (CAUDIO_U8_t channelIndex = 0; channelIndex < mInChannelNum; channelIndex++)
		{
			deleteBuffer(mpBufferCondition[channelIndex].mpInDeficiencyBuffer);
		}

		for (CAUDIO_U8_t channelIndex = 0; channelIndex < mOutChannelNum; channelIndex++)
		{
			deleteBuffer(mpBufferCondition[channelIndex].mpPostProcessBuffer);
		}

		delete[] mpBufferCondition;
		mpBufferCondition = NULL;
	}

	mpBufferCondition = new BufferCondition_t[mProcessBufferNum];
	memset(mpBufferCondition, 0, mProcessBufferNum*sizeof(BufferCondition_t));
	if (NULL == mpBufferCondition)
	{
		AUDIO_PROCESSING_PRINTF("alloc mpBufferCondition failed!");
		return false;
	}

	for (CAUDIO_U8_t channelIndex = 0; channelIndex < mInChannelNum; channelIndex++)
	{
		if (!createBuffer(mpBufferCondition[channelIndex].mpInDeficiencyBuffer, mInDefBufferLen))
		{
			AUDIO_PROCESSING_PRINTF("create in deficiency buffer failed!");
			return false;
		}
		mpBufferCondition[channelIndex].mInDefBufferWritePtr = mInitDelay * mLenOfSample;
		//mpBufferCondition[channelIndex].mInDefBufferWritePtr = mLenOfSample*mFrameShiftSize / 2;
	}

	for (CAUDIO_U8_t channelIndex = 0; channelIndex < mOutChannelNum; channelIndex++)
	{
		// introduce mInitDelay at the beginning of output
		mpBufferCondition[channelIndex].mPostProBufWrtPtr = mInitDelay * mLenOfSample;
		//mPostProcessBufferLen = aParam.mPostProcessBufferLen;
		mPostProcessBufferLen = mFrameShiftLen;  // this len is different from process mode
		if (!createBuffer(mpBufferCondition[channelIndex].mpPostProcessBuffer, mPostProcessBufferLen))
		{
			AUDIO_PROCESSING_PRINTF("create out post process buffer failed!");
			return false;
		}
	}

	return true;
}
Ejemplo n.º 13
0
int main(void) {
    VkInstance instance;
    {
        const char debug_ext[] = "VK_EXT_debug_report";
        const char* extensions[] = {debug_ext,};

        const char validation_layer[] = "VK_LAYER_LUNARG_standard_validation";
        const char* layers[] = {validation_layer,};

        VkInstanceCreateInfo create_info = {
            .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .pApplicationInfo = NULL,
            .enabledLayerCount = NELEMS(layers),
            .ppEnabledLayerNames = layers,
            .enabledExtensionCount = NELEMS(extensions),
            .ppEnabledExtensionNames = extensions,
        };
        assert(vkCreateInstance(&create_info, NULL, &instance) == VK_SUCCESS);
    }

    VkDebugReportCallbackEXT debug_callback;
    {
        VkDebugReportCallbackCreateInfoEXT create_info = {
            .sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT,
            .pNext = NULL,
            .flags = (VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT |
                      VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT),
            .pfnCallback = &debugReportCallback,
            .pUserData = NULL,
        };

        PFN_vkCreateDebugReportCallbackEXT createDebugReportCallback =
            (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
        assert(createDebugReportCallback);
        assert(createDebugReportCallback(instance, &create_info, NULL, &debug_callback) == VK_SUCCESS);
    }

    VkPhysicalDevice phy_device;
    {
        uint32_t num_devices;
        assert(vkEnumeratePhysicalDevices(instance, &num_devices, NULL) == VK_SUCCESS);
        assert(num_devices >= 1);
        VkPhysicalDevice * phy_devices = malloc(sizeof(*phy_devices) * num_devices);
        assert(vkEnumeratePhysicalDevices(instance, &num_devices, phy_devices) == VK_SUCCESS);
        phy_device = phy_devices[0];
        free(phy_devices);
    }

    VkPhysicalDeviceMemoryProperties memory_properties;
    vkGetPhysicalDeviceMemoryProperties(phy_device, &memory_properties);

    VkDevice device;
    {
        float queue_priorities[] = {1.0};
        const char validation_layer[] = "VK_LAYER_LUNARG_standard_validation";
        const char* layers[] = {validation_layer,};

        uint32_t nqueues;
        matchingQueues(phy_device, VK_QUEUE_GRAPHICS_BIT, &nqueues, NULL);
        assert(nqueues > 0);
        uint32_t * queue_family_idxs = malloc(sizeof(*queue_family_idxs) * nqueues);
        matchingQueues(phy_device, VK_QUEUE_GRAPHICS_BIT, &nqueues, queue_family_idxs);

        VkDeviceQueueCreateInfo queue_info = {
            .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .queueFamilyIndex = queue_family_idxs[0],
            .queueCount = 1,
            .pQueuePriorities = queue_priorities,
        };
        free(queue_family_idxs);

        VkPhysicalDeviceFeatures features = {
            .geometryShader = VK_TRUE,
            .fillModeNonSolid = VK_TRUE,
        };

        VkDeviceCreateInfo create_info = {
            .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .queueCreateInfoCount = 1,
            .pQueueCreateInfos = &queue_info,
            .enabledLayerCount = NELEMS(layers),
            .ppEnabledLayerNames = layers,
            .enabledExtensionCount = 0,
            .ppEnabledExtensionNames = NULL,
            .pEnabledFeatures = &features,
        };

        assert(vkCreateDevice(phy_device, &create_info, NULL, &device) == VK_SUCCESS);
    }

    VkQueue queue;
    vkGetDeviceQueue(device, 0, 0, &queue);

    VkCommandPool cmd_pool;
    {
        VkCommandPoolCreateInfo create_info = {
            .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
            .pNext = NULL,
            .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
            .queueFamilyIndex = 0,
        };
        assert(vkCreateCommandPool(device, &create_info, NULL, &cmd_pool) == VK_SUCCESS);
    }

    VkRenderPass render_pass;
    {
        VkAttachmentDescription attachments[] = {{
                .flags = 0,
                .format = VK_FORMAT_R8G8B8A8_UNORM,
                .samples = VK_SAMPLE_COUNT_8_BIT,
                .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
                .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
                .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
                .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
                .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
                .finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
            }, {
                .flags = 0,
                .format = VK_FORMAT_D16_UNORM,
                .samples = VK_SAMPLE_COUNT_8_BIT,
                .loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
                .storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
                .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
                .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
                .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
                .finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
            }, {
                .flags = 0,
                .format = VK_FORMAT_R8G8B8A8_UNORM,
                .samples = VK_SAMPLE_COUNT_1_BIT,
                .loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
                .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
                .stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
                .stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
                .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
                .finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
            }};
        VkAttachmentReference attachment_refs[NELEMS(attachments)] = {{
                .attachment = 0,
                .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
            }, {
                .attachment = 1,
                .layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL,
            }, {
                .attachment = 2,
                .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
            }};
        VkSubpassDescription subpasses[1] = {{
                .flags = 0,
                .pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
                .inputAttachmentCount = 0,
                .pInputAttachments = NULL,
                .colorAttachmentCount = 1,
                .pColorAttachments = &attachment_refs[0],
                .pResolveAttachments = &attachment_refs[2],
                .pDepthStencilAttachment = &attachment_refs[1],
                .preserveAttachmentCount = 0,
                .pPreserveAttachments = NULL,
            }};
        VkSubpassDependency dependencies[] = {{
                .srcSubpass = 0,
                .dstSubpass = VK_SUBPASS_EXTERNAL,
                .srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
                .dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT,
                .srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
                .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
                .dependencyFlags = 0,
            }};
        VkRenderPassCreateInfo create_info = {
            .sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .attachmentCount = NELEMS(attachments),
            .pAttachments = attachments,
            .subpassCount = NELEMS(subpasses),
            .pSubpasses = subpasses,
            .dependencyCount = NELEMS(dependencies),
            .pDependencies = dependencies,
        };
        assert(vkCreateRenderPass(device, &create_info, NULL, &render_pass) == VK_SUCCESS);
    }

    VkImage images[3];
    VkDeviceMemory image_memories[NELEMS(images)];
    VkImageView views[NELEMS(images)];
    createFrameImage(memory_properties, device, render_size,
                     VK_FORMAT_R8G8B8A8_UNORM, VK_SAMPLE_COUNT_8_BIT,
                     VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_ASPECT_COLOR_BIT,
                     &images[0], &image_memories[0], &views[0]);
    createFrameImage(memory_properties, device, render_size,
                     VK_FORMAT_D16_UNORM, VK_SAMPLE_COUNT_8_BIT,
                     VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_IMAGE_ASPECT_DEPTH_BIT,
                     &images[1], &image_memories[1], &views[1]);
    createFrameImage(memory_properties, device, render_size,
                     VK_FORMAT_R8G8B8A8_UNORM, VK_SAMPLE_COUNT_1_BIT,
                     VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
                     VK_IMAGE_ASPECT_COLOR_BIT,
                     &images[2], &image_memories[2], &views[2]);

    VkBuffer verts_buffer;
    VkDeviceMemory verts_memory;
    createBuffer(memory_properties, device, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, sizeof(verts), verts, &verts_buffer, &verts_memory);

    VkBuffer index_buffer;
    VkDeviceMemory index_memory;
    createBuffer(memory_properties, device, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, sizeof(indices), indices, &index_buffer, &index_memory);

    VkBuffer image_buffer;
    VkDeviceMemory image_buffer_memory;
    createBuffer(memory_properties, device, VK_BUFFER_USAGE_TRANSFER_DST_BIT, render_size.height * render_size.width * 4, NULL, &image_buffer, &image_buffer_memory);

    VkFramebuffer framebuffer;
    createFramebuffer(device, render_size, 3, views, render_pass, &framebuffer);

    VkShaderModule shaders[5];
    {
        char* filenames[NELEMS(shaders)] = {"cube.vert.spv", "cube.geom.spv", "cube.frag.spv", "wireframe.geom.spv", "color.frag.spv"};
        for (size_t i = 0; i < NELEMS(shaders); i++){
            size_t code_size;
            uint32_t * code;
            assert((code_size = loadModule(filenames[i], &code)) != 0);

            VkShaderModuleCreateInfo create_info = {
                .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO,
                .pNext = NULL,
                .flags = 0,
                .codeSize = code_size,
                .pCode = code,
            };
            assert(vkCreateShaderModule(device, &create_info, NULL, &shaders[i]) == VK_SUCCESS);
            free(code);
        }
    }

    VkPipelineLayout pipeline_layout;
    {
        VkPushConstantRange push_range = {
            .stageFlags = VK_SHADER_STAGE_VERTEX_BIT,
            .offset = 0,
            .size = 4,
        };
        VkPipelineLayoutCreateInfo create_info = {
            .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .setLayoutCount = 0,
            .pSetLayouts = NULL,
            .pushConstantRangeCount = 1,
            .pPushConstantRanges = &push_range,
        };
        assert(vkCreatePipelineLayout(device, &create_info, NULL, &pipeline_layout) == VK_SUCCESS);
    }

    VkPipeline pipelines[2];
    {
        VkPipelineShaderStageCreateInfo stages[3] = {{
                .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                .pNext = NULL,
                .flags = 0,
                .stage = VK_SHADER_STAGE_VERTEX_BIT,
                .module = shaders[0],
                .pName = "main",
                .pSpecializationInfo = NULL,
            },{
                .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                .pNext = NULL,
                .flags = 0,
                .stage = VK_SHADER_STAGE_GEOMETRY_BIT,
                .module = shaders[1],
                .pName = "main",
                .pSpecializationInfo = NULL,
            },{
                .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,
                .pNext = NULL,
                .flags = 0,
                .stage = VK_SHADER_STAGE_FRAGMENT_BIT,
                .module = shaders[2],
                .pName = "main",
                .pSpecializationInfo = NULL,
            }};
        VkVertexInputBindingDescription vtx_binding = {
            .binding = 0,
            .stride = sizeof(struct Vertex),
            .inputRate = VK_VERTEX_INPUT_RATE_VERTEX,
        };
        VkVertexInputAttributeDescription vtx_attr = {
            .location = 0,
            .binding = 0,
            .format = VK_FORMAT_R32G32B32_SFLOAT,
            .offset = offsetof(struct Vertex, pos),
        };
        VkPipelineVertexInputStateCreateInfo vtx_state = {
            .sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .vertexBindingDescriptionCount = 1,
            .pVertexBindingDescriptions = &vtx_binding,
            .vertexAttributeDescriptionCount = 1,
            .pVertexAttributeDescriptions = &vtx_attr,
        };
        VkPipelineInputAssemblyStateCreateInfo ia_state = {
            .sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP,
            .primitiveRestartEnable = VK_TRUE,
        };
        VkViewport viewport = {
            .x = 0,
            .y = 0,
            .width = render_size.width,
            .height = render_size.height,
            .minDepth = 0.0,
            .maxDepth = 1.0,
        };
        VkRect2D scissor= {
            .offset = {.x = 0, .y = 0,},
            .extent = render_size,
        };
        VkPipelineViewportStateCreateInfo viewport_state = {
            .sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .viewportCount = 1,
            .pViewports = &viewport,
            .scissorCount = 1,
            .pScissors = &scissor,
        };
        VkPipelineRasterizationStateCreateInfo rasterization_state = {
            .sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .depthClampEnable = VK_FALSE,
            .rasterizerDiscardEnable = VK_FALSE,
            .polygonMode = VK_POLYGON_MODE_FILL,
            .cullMode = VK_CULL_MODE_NONE,
            .frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE,
            .depthBiasEnable = VK_FALSE,
            .lineWidth = 1.0,
        };
        VkPipelineMultisampleStateCreateInfo multisample_state = {
            .sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .rasterizationSamples = VK_SAMPLE_COUNT_8_BIT,
            .sampleShadingEnable = VK_FALSE,
            .minSampleShading = 0.0,
            .pSampleMask = NULL,
            .alphaToCoverageEnable = VK_FALSE,
            .alphaToOneEnable = VK_FALSE,
        };
        VkPipelineDepthStencilStateCreateInfo depth_stencil_state = {
            .sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .depthTestEnable = VK_TRUE,
            .depthWriteEnable = VK_TRUE,
            .depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL,
            .depthBoundsTestEnable = VK_FALSE,
            .stencilTestEnable = VK_FALSE,
            .front = {},
            .back = {},
            .minDepthBounds = 0.0,
            .maxDepthBounds = 1.0,
        };
        VkPipelineColorBlendAttachmentState color_blend_attachment = {
            .blendEnable = VK_FALSE,
            .colorWriteMask = ( VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT
                                | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT),
        };
        VkPipelineColorBlendStateCreateInfo color_blend_state = {
            .sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .logicOpEnable = VK_FALSE, //.logicOp = 0,
            .attachmentCount = 1,
            .pAttachments = &color_blend_attachment,
            .blendConstants = {},
        };

        VkGraphicsPipelineCreateInfo create_info = {
            .sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO,
            .pNext = NULL,
            .flags = 0,
            .stageCount = NELEMS(stages),
            .pStages = stages,
            .pVertexInputState = &vtx_state,
            .pInputAssemblyState = &ia_state,
            .pTessellationState = NULL,
            .pViewportState = &viewport_state,
            .pRasterizationState = &rasterization_state,
            .pMultisampleState = &multisample_state,
            .pDepthStencilState = &depth_stencil_state,
            .pColorBlendState = &color_blend_state,
            .pDynamicState = NULL,
            .layout = pipeline_layout,
            .renderPass = render_pass,
            .subpass = 0,
            .basePipelineHandle = VK_NULL_HANDLE,
            .basePipelineIndex = 0,
        };
        assert(vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &create_info, NULL, &pipelines[0]) == VK_SUCCESS);
        stages[1].module = shaders[3];
        stages[2].module = shaders[4];
        rasterization_state.polygonMode = VK_POLYGON_MODE_LINE;
        assert(vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &create_info, NULL, &pipelines[1]) == VK_SUCCESS);
    }

    VkCommandBuffer draw_buffers[2];
    {
        VkCommandBufferAllocateInfo allocate_info = {
            .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
            .pNext = NULL,
            .commandPool = cmd_pool,
            .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
            .commandBufferCount = NELEMS(draw_buffers),
        };
        assert(vkAllocateCommandBuffers(device, &allocate_info, draw_buffers) == VK_SUCCESS);
    }

    {
        VkCommandBufferBeginInfo begin_info = {
            .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
            .pNext = NULL,
            .flags = 0,
            .pInheritanceInfo = NULL,
        };

        VkClearValue clear_values[] = {{
                .color.float32 = {0.0, 0.0, 0.0, 1.0},
            }, {
                .depthStencil = {.depth = 1.0},
            }};
        VkRenderPassBeginInfo renderpass_begin_info = {
            .sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO,
            .pNext = NULL,
            .renderPass = render_pass,
            .framebuffer = framebuffer,
            .renderArea = {
                .offset = {.x = 0, .y = 0},
                .extent = render_size,
            },
            .clearValueCount = NELEMS(clear_values),
            .pClearValues = clear_values,
        };
        for (size_t i = 0; i < NELEMS(draw_buffers); i++){
            assert(vkBeginCommandBuffer(draw_buffers[i], &begin_info) == VK_SUCCESS);
            uint32_t persp = i == 0;
            vkCmdPushConstants(draw_buffers[i], pipeline_layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(persp), &persp);
            vkCmdBeginRenderPass(draw_buffers[i], &renderpass_begin_info, VK_SUBPASS_CONTENTS_INLINE);
            VkDeviceSize offset = 0;
            vkCmdBindVertexBuffers(draw_buffers[i], 0, 1, &verts_buffer, &offset);
            vkCmdBindIndexBuffer(draw_buffers[i], index_buffer, 0, VK_INDEX_TYPE_UINT32);
            for (size_t j = 0; j < NELEMS(pipelines); j++) {
                vkCmdBindPipeline(draw_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines[j]);
                vkCmdDrawIndexed(draw_buffers[i], 20, 27, 0, 0, 0);
            }
            vkCmdEndRenderPass(draw_buffers[i]);
        }

        VkBufferImageCopy copy = {
            .bufferOffset = 0,
            .bufferRowLength = 0, // Tightly packed
            .bufferImageHeight = 0, // Tightly packed
            .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
            .imageOffset = {0, 0, 0},
            .imageExtent = {.width = render_size.width,
                            .height = render_size.height,
                            .depth = 1},
        };
        VkBufferMemoryBarrier transfer_barrier = {
            .sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
            .pNext = 0,
            .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT,
            .dstAccessMask = VK_ACCESS_HOST_READ_BIT,
            .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
            .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
            .buffer = image_buffer,
            .offset = 0,
            .size = VK_WHOLE_SIZE,
        };
        for (size_t i = 0; i < NELEMS(draw_buffers); i++){
            vkCmdCopyImageToBuffer(draw_buffers[i], images[2], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, image_buffer, 1, &copy);

            vkCmdPipelineBarrier(draw_buffers[i], VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 0, NULL, 1, &transfer_barrier, 0, NULL);
            assert(vkEndCommandBuffer(draw_buffers[i]) == VK_SUCCESS);
        }
    }

    VkFence fence;
    {
        VkFenceCreateInfo create_info = {
            .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
            .pNext = 0,
            .flags = 0,
        };
        assert(vkCreateFence(device, &create_info, NULL, &fence) == VK_SUCCESS);
    }

    {
        char * filenames[] = {"cube_persp.tif", "cube_ortho.tif"};
        char * image_data;
        assert(vkMapMemory(device, image_buffer_memory, 0, VK_WHOLE_SIZE, 0, (void **) &image_data) == VK_SUCCESS);
        VkMappedMemoryRange image_flush = {
            .sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, .pNext = NULL,
            .memory = image_buffer_memory,
            .offset = 0,
            .size = VK_WHOLE_SIZE,
        };

        VkSubmitInfo submit_info = {
            .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
            .pNext = NULL,
            .waitSemaphoreCount = 0,
            .pWaitSemaphores = NULL,
            .pWaitDstStageMask = NULL,
            .commandBufferCount = 1,
            .pCommandBuffers = NULL,
            .signalSemaphoreCount = 0,
            .pSignalSemaphores = NULL,
        };

        for (size_t i = 0; i < NELEMS(filenames); i++){
            submit_info.pCommandBuffers = &draw_buffers[i];
            assert(vkResetFences(device, 1, &fence) == VK_SUCCESS);
            assert(vkQueueSubmit(queue, 1, &submit_info, fence) == VK_SUCCESS);
            assert(vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX) == VK_SUCCESS);
            assert(vkInvalidateMappedMemoryRanges(device, 1, &image_flush) == VK_SUCCESS);
            assert(writeTiff(filenames[i], image_data, render_size, nchannels) == 0);
        }

        vkUnmapMemory(device, image_buffer_memory);
    }

    assert(vkQueueWaitIdle(queue) == VK_SUCCESS);
    vkDestroyFence(device, fence, NULL);

    vkDestroyFramebuffer(device, framebuffer, NULL);
    for (size_t i = 0; i < NELEMS(images); i++){
        vkDestroyImage(device, images[i], NULL);
        vkDestroyImageView(device, views[i], NULL);
        vkFreeMemory(device, image_memories[i], NULL);
    }

    vkDestroyBuffer(device, image_buffer, NULL);
    vkFreeMemory(device, image_buffer_memory, NULL);

    vkDestroyBuffer(device, verts_buffer, NULL);
    vkFreeMemory(device, verts_memory, NULL);

    vkDestroyBuffer(device, index_buffer, NULL);
    vkFreeMemory(device, index_memory, NULL);

    for (size_t i = 0; i < NELEMS(pipelines); i++){
        vkDestroyPipeline(device, pipelines[i], NULL);
    }
    vkDestroyPipelineLayout(device, pipeline_layout, NULL);
    for(size_t i = 0; i < NELEMS(shaders); i++)
        vkDestroyShaderModule(device, shaders[i], NULL);

    vkDestroyRenderPass(device, render_pass, NULL);
    vkFreeCommandBuffers(device, cmd_pool, NELEMS(draw_buffers), draw_buffers);
    vkDestroyCommandPool(device, cmd_pool, NULL);
    vkDestroyDevice(device, NULL);
    {
        PFN_vkDestroyDebugReportCallbackEXT destroyDebugReportCallback =
            (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
        assert(destroyDebugReportCallback);
        destroyDebugReportCallback(instance, debug_callback, NULL);
    }
    vkDestroyInstance(instance, NULL);
    return 0;
}
void SparseShaderIntrinsicsInstanceSampledBase::recordCommands (const VkCommandBuffer		commandBuffer,
																const VkImageCreateInfo&	imageSparseInfo,
																const VkImage				imageSparse,
																const VkImage				imageTexels,
																const VkImage				imageResidency)
{
	const InstanceInterface&		 instance			= m_context.getInstanceInterface();
	const DeviceInterface&			 deviceInterface	= getDeviceInterface();
	const VkPhysicalDevice			 physicalDevice		= m_context.getPhysicalDevice();
	const VkPhysicalDeviceProperties deviceProperties	= getPhysicalDeviceProperties(instance, physicalDevice);

	if (imageSparseInfo.extent.width  > deviceProperties.limits.maxFramebufferWidth  ||
		imageSparseInfo.extent.height > deviceProperties.limits.maxFramebufferHeight ||
		imageSparseInfo.arrayLayers   > deviceProperties.limits.maxFramebufferLayers)
	{
		TCU_THROW(NotSupportedError, "Image size exceeds allowed framebuffer dimensions");
	}

	// Check if device supports image format for sampled images
	if (!checkImageFormatFeatureSupport(instance, physicalDevice, imageSparseInfo.format, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
		TCU_THROW(NotSupportedError, "Device does not support image format for sampled images");

	// Check if device supports image format for color attachment
	if (!checkImageFormatFeatureSupport(instance, physicalDevice, imageSparseInfo.format, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT))
		TCU_THROW(NotSupportedError, "Device does not support image format for color attachment");

	// Make sure device supports VK_FORMAT_R32_UINT format for color attachment
	if (!checkImageFormatFeatureSupport(instance, physicalDevice, mapTextureFormat(m_residencyFormat), VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT))
		TCU_THROW(TestError, "Device does not support VK_FORMAT_R32_UINT format for color attachment");

	// Create buffer storing vertex data
	std::vector<tcu::Vec2> vertexData;

	vertexData.push_back(tcu::Vec2(-1.0f,-1.0f));
	vertexData.push_back(tcu::Vec2( 0.0f, 0.0f));

	vertexData.push_back(tcu::Vec2(-1.0f, 1.0f));
	vertexData.push_back(tcu::Vec2( 0.0f, 1.0f));

	vertexData.push_back(tcu::Vec2( 1.0f,-1.0f));
	vertexData.push_back(tcu::Vec2( 1.0f, 0.0f));

	vertexData.push_back(tcu::Vec2( 1.0f, 1.0f));
	vertexData.push_back(tcu::Vec2( 1.0f, 1.0f));

	const VkDeviceSize			vertexDataSizeInBytes	= sizeInBytes(vertexData);
	const VkBufferCreateInfo	vertexBufferCreateInfo	= makeBufferCreateInfo(vertexDataSizeInBytes, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);

	m_vertexBuffer		= createBuffer(deviceInterface, getDevice(), &vertexBufferCreateInfo);
	m_vertexBufferAlloc	= bindBuffer(deviceInterface, getDevice(), getAllocator(), *m_vertexBuffer, MemoryRequirement::HostVisible);

	deMemcpy(m_vertexBufferAlloc->getHostPtr(), &vertexData[0], static_cast<std::size_t>(vertexDataSizeInBytes));
	flushMappedMemoryRange(deviceInterface, getDevice(), m_vertexBufferAlloc->getMemory(), m_vertexBufferAlloc->getOffset(), vertexDataSizeInBytes);

	// Create render pass
	const VkAttachmentDescription texelsAttachmentDescription =
	{
		(VkAttachmentDescriptionFlags)0,					// VkAttachmentDescriptionFlags		flags;
		imageSparseInfo.format,								// VkFormat							format;
		VK_SAMPLE_COUNT_1_BIT,								// VkSampleCountFlagBits			samples;
		VK_ATTACHMENT_LOAD_OP_CLEAR,						// VkAttachmentLoadOp				loadOp;
		VK_ATTACHMENT_STORE_OP_STORE,						// VkAttachmentStoreOp				storeOp;
		VK_ATTACHMENT_LOAD_OP_DONT_CARE,					// VkAttachmentLoadOp				stencilLoadOp;
		VK_ATTACHMENT_STORE_OP_DONT_CARE,					// VkAttachmentStoreOp				stencilStoreOp;
		VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,			// VkImageLayout					initialLayout;
		VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL			// VkImageLayout					finalLayout;
	};

	const VkAttachmentDescription residencyAttachmentDescription =
	{
		(VkAttachmentDescriptionFlags)0,					// VkAttachmentDescriptionFlags		flags;
		mapTextureFormat(m_residencyFormat),				// VkFormat							format;
		VK_SAMPLE_COUNT_1_BIT,								// VkSampleCountFlagBits			samples;
		VK_ATTACHMENT_LOAD_OP_CLEAR,						// VkAttachmentLoadOp				loadOp;
		VK_ATTACHMENT_STORE_OP_STORE,						// VkAttachmentStoreOp				storeOp;
		VK_ATTACHMENT_LOAD_OP_DONT_CARE,					// VkAttachmentLoadOp				stencilLoadOp;
		VK_ATTACHMENT_STORE_OP_DONT_CARE,					// VkAttachmentStoreOp				stencilStoreOp;
		VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,			// VkImageLayout					initialLayout;
		VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL			// VkImageLayout					finalLayout;
	};

	const VkAttachmentDescription colorAttachmentsDescription[] = { texelsAttachmentDescription, residencyAttachmentDescription };

	const VkAttachmentReference texelsAttachmentReference =
	{
		0u,													// deUint32			attachment;
		VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL			// VkImageLayout	layout;
	};

	const VkAttachmentReference residencyAttachmentReference =
	{
		1u,													// deUint32			attachment;
		VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL			// VkImageLayout	layout;
	};

	const VkAttachmentReference colorAttachmentsReference[] = { texelsAttachmentReference, residencyAttachmentReference };

	const VkAttachmentReference depthAttachmentReference =
	{
		VK_ATTACHMENT_UNUSED,								// deUint32			attachment;
		VK_IMAGE_LAYOUT_UNDEFINED							// VkImageLayout	layout;
	};

	const VkSubpassDescription subpassDescription =
	{
		(VkSubpassDescriptionFlags)0,						// VkSubpassDescriptionFlags		flags;
		VK_PIPELINE_BIND_POINT_GRAPHICS,					// VkPipelineBindPoint				pipelineBindPoint;
		0u,													// deUint32							inputAttachmentCount;
		DE_NULL,											// const VkAttachmentReference*		pInputAttachments;
		2u,													// deUint32							colorAttachmentCount;
		colorAttachmentsReference,							// const VkAttachmentReference*		pColorAttachments;
		DE_NULL,											// const VkAttachmentReference*		pResolveAttachments;
		&depthAttachmentReference,							// const VkAttachmentReference*		pDepthStencilAttachment;
		0u,													// deUint32							preserveAttachmentCount;
		DE_NULL												// const deUint32*					pPreserveAttachments;
	};

	const VkRenderPassCreateInfo renderPassInfo =
	{
		VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO,			// VkStructureType					sType;
		DE_NULL,											// const void*						pNext;
		(VkRenderPassCreateFlags)0,							// VkRenderPassCreateFlags			flags;
		2u,													// deUint32							attachmentCount;
		colorAttachmentsDescription,						// const VkAttachmentDescription*	pAttachments;
		1u,													// deUint32							subpassCount;
		&subpassDescription,								// const VkSubpassDescription*		pSubpasses;
		0u,													// deUint32							dependencyCount;
		DE_NULL												// const VkSubpassDependency*		pDependencies;
	};

	m_renderPass = createRenderPass(deviceInterface, getDevice(), &renderPassInfo);

	// Create descriptor set layout
	DescriptorSetLayoutBuilder descriptorLayerBuilder;

	descriptorLayerBuilder.addSingleBinding(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_FRAGMENT_BIT);

	const Unique<VkDescriptorSetLayout> descriptorSetLayout(descriptorLayerBuilder.build(deviceInterface, getDevice()));

	// Create descriptor pool
	DescriptorPoolBuilder descriptorPoolBuilder;

	descriptorPoolBuilder.addType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, imageSparseInfo.mipLevels);

	descriptorPool = descriptorPoolBuilder.build(deviceInterface, getDevice(), VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, imageSparseInfo.mipLevels);

	// Create sampler object
	const tcu::Sampler			samplerObject(tcu::Sampler::REPEAT_GL, tcu::Sampler::REPEAT_GL, tcu::Sampler::REPEAT_GL, tcu::Sampler::NEAREST_MIPMAP_NEAREST, tcu::Sampler::NEAREST);
	const VkSamplerCreateInfo	samplerCreateInfo = mapSampler(samplerObject, m_format);
	m_sampler = createSampler(deviceInterface, getDevice(), &samplerCreateInfo);

	struct PushConstants
	{
		deUint32	lod;
		deUint32	padding;			// padding needed to satisfy std430 rules
		float		lodWidth;
		float		lodHeight;
	};

	// Create pipeline layout
	const VkPushConstantRange lodConstantRange =
	{
		VK_SHADER_STAGE_FRAGMENT_BIT,	// VkShaderStageFlags	stageFlags;
		0u,								// deUint32			offset;
		sizeof(PushConstants),			// deUint32			size;
	};

	const VkPipelineLayoutCreateInfo pipelineLayoutParams =
	{
		VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO,		// VkStructureType					sType;
		DE_NULL,											// const void*						pNext;
		0u,													// VkPipelineLayoutCreateFlags		flags;
		1u,													// deUint32							setLayoutCount;
		&descriptorSetLayout.get(),							// const VkDescriptorSetLayout*		pSetLayouts;
		1u,													// deUint32							pushConstantRangeCount;
		&lodConstantRange,									// const VkPushConstantRange*		pPushConstantRanges;
	};

	const Unique<VkPipelineLayout> pipelineLayout(createPipelineLayout(deviceInterface, getDevice(), &pipelineLayoutParams));

	// Create graphics pipeline
	{
		Move<VkShaderModule> vertexModule	= createShaderModule(deviceInterface, getDevice(), m_context.getBinaryCollection().get("vertex_shader"), (VkShaderModuleCreateFlags)0);
		Move<VkShaderModule> fragmentModule	= createShaderModule(deviceInterface, getDevice(), m_context.getBinaryCollection().get("fragment_shader"), (VkShaderModuleCreateFlags)0);
		Move<VkShaderModule> geometryModule;

		if (imageSparseInfo.arrayLayers > 1u)
		{
			requireFeatures(instance, physicalDevice, FEATURE_GEOMETRY_SHADER);
			geometryModule = createShaderModule(deviceInterface, getDevice(), m_context.getBinaryCollection().get("geometry_shader"), (VkShaderModuleCreateFlags)0);
		}

		pipelines.push_back(makeVkSharedPtr(makeGraphicsPipeline(
			deviceInterface, getDevice(), *pipelineLayout, *m_renderPass, *vertexModule, *fragmentModule, *geometryModule)));
	}

	const VkPipeline graphicsPipeline = **pipelines[0];

	{
		const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, imageSparseInfo.mipLevels, 0u, imageSparseInfo.arrayLayers);

		VkImageMemoryBarrier imageShaderAccessBarriers[3];

		imageShaderAccessBarriers[0] = makeImageMemoryBarrier
		(
			VK_ACCESS_TRANSFER_WRITE_BIT,
			VK_ACCESS_SHADER_READ_BIT,
			VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
			VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
			imageSparse,
			fullImageSubresourceRange
		);

		imageShaderAccessBarriers[1] = makeImageMemoryBarrier
		(
			0u,
			VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
			VK_IMAGE_LAYOUT_UNDEFINED,
			VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
			imageTexels,
			fullImageSubresourceRange
		);

		imageShaderAccessBarriers[2] = makeImageMemoryBarrier
		(
			0u,
			VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
			VK_IMAGE_LAYOUT_UNDEFINED,
			VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
			imageResidency,
			fullImageSubresourceRange
		);

		deviceInterface.cmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 3u, imageShaderAccessBarriers);
	}

	imageSparseViews.resize(imageSparseInfo.mipLevels);
	imageTexelsViews.resize(imageSparseInfo.mipLevels);
	imageResidencyViews.resize(imageSparseInfo.mipLevels);
	m_framebuffers.resize(imageSparseInfo.mipLevels);
	descriptorSets.resize(imageSparseInfo.mipLevels);

	std::vector<VkClearValue> clearValues;
	clearValues.push_back(makeClearValueColor(tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f)));
	clearValues.push_back(makeClearValueColor(tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f)));

	for (deUint32 mipLevelNdx = 0u; mipLevelNdx < imageSparseInfo.mipLevels; ++mipLevelNdx)
	{
		const vk::VkExtent3D			mipLevelSize	= mipLevelExtents(imageSparseInfo.extent, mipLevelNdx);
		const vk::VkRect2D				renderArea		= makeRect2D(mipLevelSize);
		const VkViewport				viewport		= makeViewport(mipLevelSize);
		const VkImageSubresourceRange	mipLevelRange	= makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, mipLevelNdx, 1u, 0u, imageSparseInfo.arrayLayers);

		// Create color attachments image views
		imageTexelsViews[mipLevelNdx] = makeVkSharedPtr(makeImageView(deviceInterface, getDevice(), imageTexels, mapImageViewType(m_imageType), imageSparseInfo.format, mipLevelRange));
		imageResidencyViews[mipLevelNdx] = makeVkSharedPtr(makeImageView(deviceInterface, getDevice(), imageResidency, mapImageViewType(m_imageType), mapTextureFormat(m_residencyFormat), mipLevelRange));

		const VkImageView attachmentsViews[] = { **imageTexelsViews[mipLevelNdx], **imageResidencyViews[mipLevelNdx] };

		// Create framebuffer
		const VkFramebufferCreateInfo framebufferInfo =
		{
			VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO,	// VkStructureType                             sType;
			DE_NULL,									// const void*                                 pNext;
			(VkFramebufferCreateFlags)0,				// VkFramebufferCreateFlags                    flags;
			*m_renderPass,								// VkRenderPass                                renderPass;
			2u,											// uint32_t                                    attachmentCount;
			attachmentsViews,							// const VkImageView*                          pAttachments;
			mipLevelSize.width,							// uint32_t                                    width;
			mipLevelSize.height,						// uint32_t                                    height;
			imageSparseInfo.arrayLayers,				// uint32_t                                    layers;
		};

		m_framebuffers[mipLevelNdx] = makeVkSharedPtr(createFramebuffer(deviceInterface, getDevice(), &framebufferInfo));

		// Create descriptor set
		descriptorSets[mipLevelNdx] = makeVkSharedPtr(makeDescriptorSet(deviceInterface, getDevice(), *descriptorPool, *descriptorSetLayout));
		const VkDescriptorSet descriptorSet = **descriptorSets[mipLevelNdx];

		// Update descriptor set
		const VkImageSubresourceRange sparseImageSubresourceRange = sampledImageRangeToBind(imageSparseInfo, mipLevelNdx);

		imageSparseViews[mipLevelNdx] = makeVkSharedPtr(makeImageView(deviceInterface, getDevice(), imageSparse, mapImageViewType(m_imageType), imageSparseInfo.format, sparseImageSubresourceRange));

		const VkDescriptorImageInfo imageSparseDescInfo = makeDescriptorImageInfo(*m_sampler, **imageSparseViews[mipLevelNdx], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);

		DescriptorSetUpdateBuilder descriptorUpdateBuilder;

		descriptorUpdateBuilder.writeSingle(descriptorSet, DescriptorSetUpdateBuilder::Location::binding(BINDING_IMAGE_SPARSE), VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &imageSparseDescInfo);
		descriptorUpdateBuilder.update(deviceInterface, getDevice());

		// Begin render pass
		beginRenderPass(deviceInterface, commandBuffer, *m_renderPass, **m_framebuffers[mipLevelNdx], renderArea, (deUint32)clearValues.size(), &clearValues[0]);

		// Bind graphics pipeline
		deviceInterface.cmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);

		// Bind descriptor set
		deviceInterface.cmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipelineLayout, 0u, 1u, &descriptorSet, 0u, DE_NULL);

		// Bind vertex buffer
		{
			const VkDeviceSize offset = 0ull;
			deviceInterface.cmdBindVertexBuffers(commandBuffer, 0u, 1u, &m_vertexBuffer.get(), &offset);
		}

		// Bind Viewport
		deviceInterface.cmdSetViewport(commandBuffer, 0u, 1u, &viewport);

		// Bind Scissor Rectangle
		deviceInterface.cmdSetScissor(commandBuffer, 0u, 1u, &renderArea);

		const PushConstants pushConstants =
		{
			mipLevelNdx,
			0u,											// padding
			static_cast<float>(mipLevelSize.width),
			static_cast<float>(mipLevelSize.height)
		};

		// Update push constants
		deviceInterface.cmdPushConstants(commandBuffer, *pipelineLayout, VK_SHADER_STAGE_FRAGMENT_BIT, 0u, sizeof(PushConstants), &pushConstants);

		// Draw full screen quad
		deviceInterface.cmdDraw(commandBuffer, 4u, 1u, 0u, 0u);

		// End render pass
		endRenderPass(deviceInterface, commandBuffer);
	}

	{
		const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, imageSparseInfo.mipLevels, 0u, imageSparseInfo.arrayLayers);

		VkImageMemoryBarrier imageOutputTransferSrcBarriers[2];

		imageOutputTransferSrcBarriers[0] = makeImageMemoryBarrier
		(
			VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
			VK_ACCESS_TRANSFER_READ_BIT,
			VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
			VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
			imageTexels,
			fullImageSubresourceRange
		);

		imageOutputTransferSrcBarriers[1] = makeImageMemoryBarrier
		(
			VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
			VK_ACCESS_TRANSFER_READ_BIT,
			VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
			VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
			imageResidency,
			fullImageSubresourceRange
		);

		deviceInterface.cmdPipelineBarrier(commandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 2u, imageOutputTransferSrcBarriers);
	}
}
Ejemplo n.º 15
0
PassRefPtr<WebCLBuffer> WebCLContext::createBuffer(unsigned memFlags, unsigned sizeInBytes, ExceptionState& es)
{
    return createBuffer(memFlags, sizeInBytes, nullptr, es);
}
Ejemplo n.º 16
0
 //%
 Buffer i2cReadBuffer(int address, int size, bool repeat = false)
 {
   Buffer buf = createBuffer(size);
   uBit.i2c.read(address << 1, (char*)buf->payload, size, repeat);
   return buf;
 }
Ejemplo n.º 17
0
main(){
  // initialize the ST library runtime, necessary for up() and down()
  st_init();

  //BoundedBuffer into which input from stdin is stored
  BoundedBuffer theInput;
  createBuffer(&theInput, MAX_BUFF_SIZE);

  // create a binary semaphore for use with input thread
  semaphore input_sem;
  createSem(&input_sem, 1);

  ThreadInit getInputThread = {
    NULL, // no input buffer for getInput thread, comes from stdin
    &theInput, // puts data from stdin into BoundedBuffer theInput 
    &input_sem // for mutual exclusion
  };

  // create input thread
  if (st_thread_create(getInput, &getInputThread, 0, 0) == NULL){
    perror("st_thread_create for getInput failure");
    exit(1);
  }

  //BoundedBuffer into which processed data w/o newlines are stored
  BoundedBuffer newLinesProcessed;
  createBuffer(&newLinesProcessed, MAX_BUFF_SIZE);
  
  // create binary semaphore for use with newline thread
  semaphore nl_sem;
  createSem(&nl_sem, 1);

  ThreadInit nlToSpaceThread = {
    &theInput, // processes input from the BoundedBuffer theInput
    &newLinesProcessed, // puts processed data into BB newLinesProcessed
    &nl_sem // for mutual exclusion
  };

  //create newline processing thread
  if (st_thread_create(newlineToSpace, &nlToSpaceThread,0,0) == NULL){
    perror("st_thread_create for newlineToSpace failure");
    exit(1);
  }


  //BoundedBuffer into which processed data after asterisks are handled go
  BoundedBuffer caratsProcessed;
  createBuffer(&caratsProcessed, MAX_BUFF_SIZE);
  
  // create binary semaphore for use with newline thread
  semaphore carat_sem;
  createSem(&carat_sem, 1);

  ThreadInit caratThread = {
    &newLinesProcessed, // buffer from wich input is processed
    &caratsProcessed, // puts processed data into BB caratsProcessed
    &carat_sem // for mutual exclusion
  };

  //create asterisks to carat processing thread
  if (st_thread_create(asterisksToCarat, &caratThread,0,0) == NULL){
    perror("st_thread_create for newlineToSpace failure");
    exit(1);
  }

  // create binary semaphore for use with print thread
  semaphore print_sem;
  createSem(&print_sem, 1);

  ThreadInit printThread = {
    &caratsProcessed, // buffer from which input is processed
    NULL, // no output buffer, just printing to stdout
    &print_sem // for mutual exclusion
  };

  // create print thread
  if (st_thread_create(print80CharLines, &printThread,0,0) == NULL){
    perror("st_thread_create for print80CharLines failure");
    exit(1);
  }

  // exit main thread
  st_thread_exit(NULL);
}
Ejemplo n.º 18
0
// generate vertex array object
void Mesh::generateVAO(int programId) {
    GLuint tmpID;

    if (!vao_dirty_) {
         return;
    }
    obtainDeleter();

    if (vertices_.size() == 0 && normals_.size() == 0
            && tex_coords_.size() == 0) {
        std::string error = "no vertex data yet, shouldn't call here. ";
        throw error;
    }
    if (0 != normals_.size() && vertices_.size() != normals_.size()) {
        LOGW("mesh: number of vertices and normals do not match! vertices %d, normals %d", vertices_.size(), normals_.size());
    }

    GLuint vaoID_;
    GLuint triangle_vboID_;
    GLuint static_vboID_;
    auto it = program_ids_.find(programId);
    if (it != program_ids_.end())
    {

        GLVaoVboId ids = it->second;
        vaoID_ = ids.vaoID;
        triangle_vboID_ = ids.triangle_vboID;
        static_vboID_ = ids.static_vboID;
    }
    else
    {
        glGenVertexArrays(1, &vaoID_);
        glGenBuffers(1, &triangle_vboID_);
        glGenBuffers(1, &static_vboID_);
    }


    glBindVertexArray(vaoID_);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, triangle_vboID_);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER,
            sizeof(unsigned short) * indices_.size(), &indices_[0],
            GL_STATIC_DRAW);
    numTriangles_ = indices_.size() / 3;

    attrMapping.clear();
    int totalStride;
    int attrLength;
    createAttributeMapping(programId, totalStride, attrLength);

    std::vector<GLfloat> buffer;
    createBuffer(buffer, attrLength);
    glBindBuffer(GL_ARRAY_BUFFER, static_vboID_);

    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * buffer.size(),
            &buffer[0], GL_STATIC_DRAW);
    int localCnt = 0;
    for ( std::vector<GLAttributeMapping>::iterator it = attrMapping.begin(); it != attrMapping.end(); ++it)
    {
        GLAttributeMapping currData = *it;
        glVertexAttribPointer(currData.index, currData.size, currData.type, 0, totalStride * sizeof(GLfloat), (GLvoid*) (currData.offset * sizeof(GLfloat)));
        glEnableVertexAttribArray(currData.index);
    }


    // done generation
    glBindVertexArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

    if (it == program_ids_.end())
    {
        GLVaoVboId id;
        id.vaoID = vaoID_;
        id.static_vboID = static_vboID_;
        id.triangle_vboID = triangle_vboID_;
        program_ids_[programId] = id;
    }
    vao_dirty_ = false;
}
Ejemplo n.º 19
0
static void connectServer(const char *stty, const char *dev) {
  int fdmax, newfd;

  fd_set master, read_fds;
  FD_ZERO(&master);
  FD_ZERO(&read_fds);

  int serverfd;
  serverfd = createServerSocket(dev);
  if (serverfd < 0) {
    syslog(LOG_ERR, "mTerm_server: Failed to create server socket\n");
    return;
  }

  struct ttyRaw* tty_sol;
  tty_sol = setTty(openTty(stty), 1);
  if (!tty_sol) {
    syslog(LOG_ERR, "mTerm_server: Failed to set tty to raw mode\n");
    close(serverfd);
    return;
  }

  struct bufStore* buf;
  buf = createBuffer(dev, FILE_SIZE_BYTES);
  if (!buf || (buf->buf_fd < 0)) {
    syslog(LOG_ERR, "mTerm_server: Failed to create the log file\n");
    closeTty(tty_sol);
    close(serverfd);
    return;
  }

  FD_SET(serverfd, &master);
  FD_SET(tty_sol->fd,&master);
  fdmax = (serverfd > tty_sol->fd) ? serverfd : tty_sol->fd;

  for(;;) {
    read_fds = master;
    if (select(fdmax + 1, &read_fds, NULL, NULL, NULL) == -1) {
      syslog(LOG_ERR, "mTerm_server: Server socket: select error\n");
      break;
    }
    if (FD_ISSET(serverfd, &read_fds)) {
      newfd = acceptClient(serverfd);
      if (newfd < 0) {
        syslog(LOG_ERR, "mTerm_server: Error on accepting client\n");
      } else {
        FD_SET(newfd, &master);
        if (newfd > fdmax) {
          fdmax = newfd;
        }
      }
    }
    if (FD_ISSET(tty_sol->fd, &read_fds)) {
      if ( processSol(&master, serverfd, fdmax, tty_sol->fd, buf) < 0) {
        break;
      }
    }
    int i;
    for(i = 0; i <= fdmax; i++) {
      if (FD_ISSET(i, &read_fds)) {
        if ((i == serverfd) || (i == tty_sol->fd)) {
          continue;
        } else {
          processClient(&master, i, tty_sol->fd, buf);
        }
      }
    }
  }
  closeTty(tty_sol);
  close(serverfd);
  closeBuffer(buf);
}