コード例 #1
0
ファイル: Shader.cpp プロジェクト: kedamazigoku/OpenGL
//--------------------------------------------------------------
// Create shader from shader program files
//--------------------------------------------------------------
bool Shader::CreateShader(const char* shadName)
{
	vertShaderId = glCreateShader(GL_VERTEX_SHADER);
	fragShaderId = glCreateShader(GL_FRAGMENT_SHADER);

	shaderName = shadName;
	string prefix("Src\\");
	string suffixVert(".vs");
	string suffixFrag(".fs");
	string pathVertShader = prefix;

	pathVertShader += shaderName;
	pathVertShader += suffixVert;
	//pathVertShader = prefix + shaderName + suffixVert;

	string pathFragShader = prefix;
	pathFragShader += shaderName;
	pathFragShader += suffixFrag;

	ReadSource(vertShaderId, pathVertShader.c_str());
	ReadSource(fragShaderId, pathFragShader.c_str());

	CompileSource(vertShaderId, "vertex");
	CompileSource(fragShaderId, "fragment");

	// Create the shader program object
	shaderProgId = glCreateProgram();

	// Attach the shader objects to the shader program object
	glAttachShader(shaderProgId, vertShaderId);
	glAttachShader(shaderProgId, fragShaderId);
  
	// Delete the shader objects
	glDeleteShader(vertShaderId);
	glDeleteShader(fragShaderId);

	// Link the shader program object to the application
	glLinkProgram(shaderProgId);
	GLint linked;
	glGetProgramiv(shaderProgId, GL_LINK_STATUS, &linked);
	if ( linked == GL_FALSE )
	{
		cerr << "Link error : " << shaderName.c_str() << endl;
		return false;
	}
	PrintProgramInfoLog();

	return true;
}
コード例 #2
0
cl_kernel CRoutine_Sum_NVidia::BuildReductionKernel(int whichKernel, int blockSize, int isPowOf2)
{
    stringstream tmp;
    tmp << "#define T float" << std::endl;
    tmp << "#define blockSize " << blockSize << std::endl;
    tmp << "#define nIsPow2 " << isPowOf2 << std::endl;
    tmp << ReadSource(mSource[0]);

    stringstream kernelName;
    kernelName << "reduce" << whichKernel;
    BuildKernel(tmp.str(), kernelName.str());

    return mKernels[mKernels.size() - 1];
}
コード例 #3
0
ファイル: ag_dual.c プロジェクト: dnaziozeno/ateamscp
/* -------------------------------------------------------------------------
   O primeiro parametro a ser passado para esse agente e' o numero do proce-
   ssador em que esta executando o 'ns'  e o segundo parametro e' o nome  do
   arquivo que contem a instancia do SCP.
   ------------------------------------------------------------------------- */
main(int argc, char *argv[])
{
  
  int flagConnect = 1;		  
  char port[MPI_MAX_PORT_NAME];   
  MPI_Comm commServerMD;          
  	            				            
  MPI_Init(&argc, &argv);               
  MPI_Comm_get_parent(&interfaceComm);
                                       
  /* Tetativa de conectar com o servidor */
  flagConnect = MPI_Lookup_name("ServerMD", MPI_INFO_NULL, port);
  if(flagConnect) 
  {
     printf("\n\n* Termino do Agente Dual Greedy *");
     printf("\n* ERRO : A memoria de solucoes duais nao foi iniciada. *");
     fflush(stdout);
  }	 
  else
   { 
/*
     TimeSleeping  = (int)  ReadAteamParam(1);
     MaxLenDualMem = (int)  ReadAteamParam(2);
     CutsofSol     = (int)  ReadAteamParam(6);
     MaxExeTime    = (int)  ReadAteamParam(11);
     ReducPerc     = (int)  ReadAteamParam(12);
     RandomDual    = (char) ReadAteamParam(17);
*/

     TimeSleeping  = atoi(argv[2]);
     MaxLenDualMem = atoi(argv[3]);
     CutsofSol     = atoi(argv[4]);
     MaxExeTime    = atoi(argv[5]);
     ReducPerc     = atoi(argv[6]);
     RandomDual    = (char) atoi(argv[7]);

     if (!(finput = fopen(argv[1],"r")))
     { printf("\n\n* Erro na abertura do arquivo %s. *\n",argv[1]);
	   exit(1);
     }
     ReadSource();
     fclose(finput);
     Reduction(NULL,NULL);
     srand48(time(NULL));

     MPI_Comm_connect(port, MPI_INFO_NULL, 0, MPI_COMM_SELF, &commServerMD);

     ExecAgDual(commServerMD);
     
     printf("\n\n* Agente Dual Greedy finalizado *");
     printf("\n* Servidor finalizou processamento. *\n");
   }

  /* Finaliza comunicacao com o servidor */
   int message = 1224;
   MPI_Send(&message, 1, MPI_INT, 0, 1, commServerMD);
   
   /* Envia mensagem de Finalizacao para interface */
   //message = 1;
   //MPI_Send(&message, 1, MPI_INT, 0, 1, interfaceComm);
   
  
   MPI_Comm_disconnect(&commServerMD);
   MPI_Finalize();
   printf("\n ==== ag_dual FINALIZADO \n", message);

}
コード例 #4
0
ファイル: FAXAnimationImport.cpp プロジェクト: tweakoz/orkid
bool FArchiveXML::LoadAnimationChannel(FCDObject* object, xmlNode* channelNode)
{ 
	FCDAnimationChannel* animationChannel = (FCDAnimationChannel*)object;
	FCDAnimationChannelData& data = FArchiveXML::documentLinkDataMap[animationChannel->GetDocument()].animationChannelData[animationChannel];

	bool status = true;

	// Read the channel-specific ID
	fm::string daeId = ReadNodeId(channelNode);
	fm::string samplerId = ReadNodeSource(channelNode);
	ReadNodeTargetProperty(channelNode, data.targetPointer, data.targetQualifier);

#ifdef DONT_DEFINE_THIS
	FCDAnimation* anim = animationChannel->GetParent();
	FCDExtra* extra = anim->GetExtra();
	extra->SetTransientFlag(); // Dont save this, its wasted whatever it is.
	FCDEType* type = extra->AddType("AnimTargets");
	FCDETechnique* teq = type->AddTechnique("TEMP");
	teq->AddChildNode("pointer")->SetContent(TO_FSTRING(data.targetPointer));
	teq->AddChildNode("pointer")->SetContent(TO_FSTRING(data.targetQualifier));
#endif
	


	xmlNode* samplerNode = FArchiveXML::FindChildByIdFCDAnimation(animationChannel->GetParent(), samplerId);
	if (samplerNode == NULL || !IsEquivalent(samplerNode->name, DAE_SAMPLER_ELEMENT))
	{
		FUError::Error(FUError::ERROR_LEVEL, FUError::ERROR_MISSING_ELEMENT, channelNode->line);
		return false;
	}

	// Find and process the sources
	xmlNode* inputSource = NULL, * outputSource = NULL, * inTangentSource = NULL, * outTangentSource = NULL, * tcbSource = NULL, * easeSource = NULL, * interpolationSource = NULL;
	xmlNodeList samplerInputNodes;
	fm::string inputDriver;
	FindChildrenByType(samplerNode, DAE_INPUT_ELEMENT, samplerInputNodes);
	for (size_t i = 0; i < samplerInputNodes.size(); ++i) // Don't use iterator here because we are possibly appending source nodes in the loop
	{
		xmlNode* inputNode = samplerInputNodes[i];
		fm::string sourceId = ReadNodeSource(inputNode);
		xmlNode* sourceNode = FArchiveXML::FindChildByIdFCDAnimation(animationChannel->GetParent(), sourceId);
		fm::string sourceSemantic = ReadNodeSemantic(inputNode);

		if (sourceSemantic == DAE_INPUT_ANIMATION_INPUT) inputSource = sourceNode;
		else if (sourceSemantic == DAE_OUTPUT_ANIMATION_INPUT) outputSource = sourceNode;
		else if (sourceSemantic == DAE_INTANGENT_ANIMATION_INPUT) inTangentSource = sourceNode;
		else if (sourceSemantic == DAE_OUTTANGENT_ANIMATION_INPUT) outTangentSource = sourceNode;
		else if (sourceSemantic == DAEFC_TCB_ANIMATION_INPUT) tcbSource = sourceNode;
		else if (sourceSemantic == DAEFC_EASE_INOUT_ANIMATION_INPUT) easeSource = sourceNode;
		else if (sourceSemantic == DAE_INTERPOLATION_ANIMATION_INPUT) interpolationSource = sourceNode;
		else if (sourceSemantic == DAEMAYA_DRIVER_INPUT) inputDriver = sourceId;
	}
	if (inputSource == NULL || outputSource == NULL)
	{
		FUError::Error(FUError::ERROR_LEVEL, FUError::ERROR_MISSING_INPUT, samplerNode->line);
		return false;
	}

	// Calculate the number of curves that in contained by this channel
	xmlNode* outputAccessor = FindTechniqueAccessor(outputSource);
	fm::string accessorStrideString = ReadNodeProperty(outputAccessor, DAE_STRIDE_ATTRIBUTE);
	uint32 curveCount = FUStringConversion::ToUInt32(accessorStrideString);
	if (curveCount == 0) curveCount = 1;

	// Create the animation curves
	for (uint32 i = 0; i < curveCount; ++i)
	{
		animationChannel->AddCurve();
	}

	// Read in the animation curves
	// The input keys and interpolations are shared by all the curves
	FloatList inputs;
    ReadSource(inputSource, inputs);
	size_t keyCount = inputs.size();
	if (keyCount == 0) return true; // Valid although very boring channel.

	UInt32List interpolations; interpolations.reserve(keyCount);
	ReadSourceInterpolation(interpolationSource, interpolations);
	if (interpolations.size() < keyCount)
	{
		// Not enough interpolation types provided, so append BEZIER as many times as needed.
		interpolations.insert(interpolations.end(), keyCount - interpolations.size(), FUDaeInterpolation::FromString(""));
	}

	// Read in the interleaved outputs as floats
	fm::vector<FloatList> tempFloatArrays;
	tempFloatArrays.resize(curveCount);
	fm::pvector<FloatList> outArrays(curveCount);
	for (uint32 i = 0; i < curveCount; ++i) outArrays[i] = &tempFloatArrays[i];
	ReadSourceInterleaved(outputSource, outArrays);
	for (uint32 i = 0; i < curveCount; ++i)
	{
		// Fill in the output array with zeroes, if it was not large enough.
		if (tempFloatArrays[i].size() < keyCount)
		{
			tempFloatArrays[i].insert(tempFloatArrays[i].end(), keyCount - tempFloatArrays[i].size(), 0.0f);
		}

		// Create all the keys, on the curves, according to the interpolation types.
		for (size_t j = 0; j < keyCount; ++j)
		{
			FCDAnimationKey* key = animationChannel->GetCurve(i)->AddKey((FUDaeInterpolation::Interpolation) interpolations[j]);
			key->input = inputs[j];
			key->output = tempFloatArrays[i][j];

			// Set the default values for Bezier/TCB interpolations.
			if (key->interpolation == FUDaeInterpolation::BEZIER)
			{
				FCDAnimationKeyBezier* bkey = (FCDAnimationKeyBezier*) key;
				float previousInput = (j == 0) ? inputs[j] - 1.0f : inputs[j-1];
				float nextInput = (j == keyCount - 1) ? inputs[j] + 1.0f : inputs[j+1];
				bkey->inTangent.x = (previousInput + 2.0f * bkey->input) / 3.0f;
				bkey->outTangent.x = (nextInput + 2.0f * bkey->input) / 3.0f;
				bkey->inTangent.y = bkey->outTangent.y = bkey->output;
			}
			else if (key->interpolation == FUDaeInterpolation::TCB)
			{
				FCDAnimationKeyTCB* tkey = (FCDAnimationKeyTCB*) key;
				tkey->tension = tkey->continuity = tkey->bias = 0.5f;
				tkey->easeIn = tkey->easeOut = 0.0f;
			}
		}
	}
	tempFloatArrays.clear();

	// Read in the interleaved in_tangent source.
	if (inTangentSource != NULL)
	{
		fm::vector<FMVector2List> tempVector2Arrays;
		tempVector2Arrays.resize(curveCount);
		fm::pvector<FMVector2List> arrays(curveCount);
		for (uint32 i = 0; i < curveCount; ++i) arrays[i] = &tempVector2Arrays[i];

		uint32 stride = ReadSourceInterleaved(inTangentSource, arrays);
		if (stride == curveCount)
		{
			// Backward compatibility with 1D tangents.
			// Remove the relativity from the 1D tangents and calculate the second-dimension.
			for (uint32 i = 0; i < curveCount; ++i)
			{
				FMVector2List& inTangents = tempVector2Arrays[i];
				FCDAnimationKey** keys = animationChannel->GetCurve(i)->GetKeys();
				size_t end = min(inTangents.size(), keyCount);
				for (size_t j = 0; j < end; ++j)
				{
					if (keys[j]->interpolation == FUDaeInterpolation::BEZIER)
					{
						FCDAnimationKeyBezier* bkey = (FCDAnimationKeyBezier*) keys[j];
						bkey->inTangent.y = bkey->output - inTangents[j].x;
					}
				}
			}
		}
		else if (stride == curveCount * 2)
		{
			// This is the typical, 2D tangent case.
			for (uint32 i = 0; i < curveCount; ++i)
			{
				FMVector2List& inTangents = tempVector2Arrays[i];
				FCDAnimationKey** keys = animationChannel->GetCurve(i)->GetKeys();
				size_t end = min(inTangents.size(), keyCount);
				for (size_t j = 0; j < end; ++j)
				{
					if (keys[j]->interpolation == FUDaeInterpolation::BEZIER)
					{
						FCDAnimationKeyBezier* bkey = (FCDAnimationKeyBezier*) keys[j];
						bkey->inTangent = inTangents[j];
					}
				}
			}
		}
	}

	// Read in the interleaved out_tangent source.
	if (outTangentSource != NULL)
	{
		fm::vector<FMVector2List> tempVector2Arrays;
		tempVector2Arrays.resize(curveCount);
		fm::pvector<FMVector2List> arrays(curveCount);
		for (uint32 i = 0; i < curveCount; ++i) arrays[i] = &tempVector2Arrays[i];

		uint32 stride = ReadSourceInterleaved(outTangentSource, arrays);
		if (stride == curveCount)
		{
			// Backward compatibility with 1D tangents.
			// Remove the relativity from the 1D tangents and calculate the second-dimension.
			for (uint32 i = 0; i < curveCount; ++i)
			{
				FMVector2List& outTangents = tempVector2Arrays[i];
				FCDAnimationKey** keys = animationChannel->GetCurve(i)->GetKeys();
				size_t end = min(outTangents.size(), keyCount);
				for (size_t j = 0; j < end; ++j)
				{
					if (keys[j]->interpolation == FUDaeInterpolation::BEZIER)
					{
						FCDAnimationKeyBezier* bkey = (FCDAnimationKeyBezier*) keys[j];
						bkey->outTangent.y = bkey->output + outTangents[j].x;
					}
				}
			}
		}
		else if (stride == curveCount * 2)
		{
			// This is the typical, 2D tangent case.
			for (uint32 i = 0; i < curveCount; ++i)
			{
				FMVector2List& outTangents = tempVector2Arrays[i];
				FCDAnimationKey** keys = animationChannel->GetCurve(i)->GetKeys();
				size_t end = min(outTangents.size(), keyCount);
				for (size_t j = 0; j < end; ++j)
				{
					if (keys[j]->interpolation == FUDaeInterpolation::BEZIER)
					{
						FCDAnimationKeyBezier* bkey = (FCDAnimationKeyBezier*) keys[j];
						bkey->outTangent = outTangents[j];
					}
				}
			}
		}
	}

	if (tcbSource != NULL)
	{
		//Process TCB parameters
		fm::vector<FMVector3List> tempVector3Arrays;
		tempVector3Arrays.resize(curveCount);
		fm::pvector<FMVector3List> arrays(curveCount);
		for (uint32 i = 0; i < curveCount; ++i) arrays[i] = &tempVector3Arrays[i];

		ReadSourceInterleaved(tcbSource, arrays);

		for (uint32 i = 0; i < curveCount; ++i)
		{
			FMVector3List& tcbs = tempVector3Arrays[i];
			FCDAnimationKey** keys = animationChannel->GetCurve(i)->GetKeys();
			size_t end = min(tcbs.size(), keyCount);
			for (size_t j = 0; j < end; ++j)
			{
				if (keys[j]->interpolation == FUDaeInterpolation::TCB)
				{
					FCDAnimationKeyTCB* tkey = (FCDAnimationKeyTCB*) keys[j];
					tkey->tension = tcbs[j].x;
					tkey->continuity = tcbs[j].y;
					tkey->bias = tcbs[j].z;
				}
			}
		}
	}

	if (easeSource != NULL)
	{
		//Process Ease-in and ease-out data
		fm::vector<FMVector2List> tempVector2Arrays;
		tempVector2Arrays.resize(curveCount);
		fm::pvector<FMVector2List> arrays(curveCount);
		for (uint32 i = 0; i < curveCount; ++i) arrays[i] = &tempVector2Arrays[i];

		ReadSourceInterleaved(easeSource, arrays);

		for (uint32 i = 0; i < curveCount; ++i)
		{
			FMVector2List& eases = tempVector2Arrays[i];
			FCDAnimationKey** keys = animationChannel->GetCurve(i)->GetKeys();
			size_t end = min(eases.size(), keyCount);
			for (size_t j = 0; j < end; ++j)
			{
				if (keys[j]->interpolation == FUDaeInterpolation::TCB)
				{
					FCDAnimationKeyTCB* tkey = (FCDAnimationKeyTCB*) keys[j];
					tkey->easeIn = eases[j].x;
					tkey->easeOut = eases[j].y;
				}
			}
		}
	}

	// Read in the pre/post-infinity type
	xmlNodeList mayaParameterNodes; StringList mayaParameterNames;
	xmlNode* mayaTechnique = FindTechnique(inputSource, DAEMAYA_MAYA_PROFILE);
	FindParameters(mayaTechnique, mayaParameterNames, mayaParameterNodes);
	size_t parameterCount = mayaParameterNodes.size();
	for (size_t i = 0; i < parameterCount; ++i)
	{
		xmlNode* parameterNode = mayaParameterNodes[i];
		const fm::string& paramName = mayaParameterNames[i];
		const char* content = ReadNodeContentDirect(parameterNode);

		if (paramName == DAEMAYA_PREINFINITY_PARAMETER)
		{
			size_t curveCount = animationChannel->GetCurveCount();
			for (size_t c = 0; c < curveCount; ++c)
			{
				animationChannel->GetCurve(c)->SetPreInfinity(FUDaeInfinity::FromString(content));
			}
		}
		else if (paramName == DAEMAYA_POSTINFINITY_PARAMETER)
		{
			size_t curveCount = animationChannel->GetCurveCount();
			for (size_t c = 0; c < curveCount; ++c)
			{
				animationChannel->GetCurve(c)->SetPostInfinity(FUDaeInfinity::FromString(content));
			}
		}
		else
		{
			// Look for driven-key input target
			if (paramName == DAE_INPUT_ELEMENT)
			{
				fm::string semantic = ReadNodeSemantic(parameterNode);
				if (semantic == DAEMAYA_DRIVER_INPUT)
				{
					inputDriver = ReadNodeSource(parameterNode);
				}
			}
		}
	}

	if (!inputDriver.empty())
	{
		const char* driverTarget = FUDaeParser::SkipPound(inputDriver);
		if (driverTarget != NULL)
		{
			fm::string driverQualifierValue;
			FUStringConversion::SplitTarget(driverTarget, data.driverPointer, driverQualifierValue);
			data.driverQualifier = FUStringConversion::ParseQualifier(driverQualifierValue);
			if (data.driverQualifier < 0) data.driverQualifier = 0;
		}
	}
	animationChannel->SetDirtyFlag();

	return status;
}
コード例 #5
0
void CRoutine_FTtoV2::Init()
{
	// Read the kernel, compile it
	string source = ReadSource(mSource[0]);
    BuildKernel(source, "ft_to_vis2", mSource[0]);
}
コード例 #6
0
static gcSHADER
CompileFile(
    IN gcoOS Os,
    IN gctCONST_STRING FileName,
    IN gcoHAL Hal,
    IN gctUINT Option,
    IN gctBOOL DumpLog,
    IN gctBOOL DumpCompiledShader
    )
{
    gceSTATUS   status;
    gctINT      shaderType;
    gctSIZE_T   sourceSize;
    gctSTRING   source          = gcvNULL;
    gcSHADER    binary;
    gctSTRING   log             = gcvNULL;
    gctSIZE_T   bufferSize;
    gctSTRING   buffer;
    gctSTRING   dataFileName    = gcvNULL;
    gctSIZE_T   length;
    gctFILE     logFile         = gcvNULL;

    gcmASSERT(FileName);

    shaderType = GetShaderType(FileName);

    if (!ReadSource(Os, FileName, &sourceSize, &source)) return gcvNULL;

    status = gcCompileShader(Hal,
                             shaderType,
                             sourceSize, source,
                             &binary,
                             &log);

    if (log != gcvNULL)
    {
        printf("<LOG>\n");
        printf("%s", log);
        printf("</LOG>\n");
    }

    if (gcmIS_ERROR(status))
    {
        gcmASSERT(binary == gcvNULL);
        binary = gcvNULL;

        printf("*ERROR* Failed to compile %s (error: %d)\n", FileName, status);
        goto Exit;
    }

    gcmASSERT(binary != gcvNULL);

    if (DumpLog)
    {
        gcmVERIFY_OK(gcoOS_StrLen(FileName, &length));
        length += 5;
        gcmVERIFY_OK(gcoOS_Allocate(Os, length, (gctPOINTER *) &dataFileName));
        gcmVERIFY_OK(gcoOS_StrCopySafe(dataFileName, length, FileName));
        gcmVERIFY_OK(gcoOS_StrCatSafe(dataFileName, length, ".log"));

        status = gcoOS_Open(Os, dataFileName, gcvFILE_CREATETEXT, &logFile);
        if (gcmIS_ERROR(status))
        {
            logFile = gcvNULL;

            printf("*ERROR* Failed to open the log file: %s\n", dataFileName);
        }
        gcoOS_Free(Os, dataFileName);
    }

    gcmVERIFY_OK(gcSHADER_SetOptimizationOption(binary, Option));

    status = gcOptimizeShader(binary, logFile);

    if (!gcmIS_SUCCESS(status))
    {
        printf("*ERROR* Failed to optimize %s (error: %d)\n", FileName, status);
    }

    if (logFile != gcvNULL)
    {
        gcmVERIFY_OK(gcoOS_Close(Os, logFile));
    }

    if (DumpCompiledShader)
    {
        status = gcSHADER_Save(binary, gcvNULL, &bufferSize);
        if (gcmIS_ERROR(status))
        {
            printf("*ERROR* Failed to get the buffer size of the shader\n");
            goto Exit;
        }

        status = gcoOS_Allocate(Os, bufferSize, (gctPOINTER *) &buffer);
        if (!gcmIS_SUCCESS(status))
        {
            printf("*ERROR* Not enough memory\n");
            goto Exit;
        }

        status = gcSHADER_Save(binary, buffer, &bufferSize);
        if (status != gcvSTATUS_OK)
        {
            printf("*ERROR* Failed to get the buffer size of the shader\n");
            gcoOS_Free(Os, buffer);
            goto Exit;
        }

        OutputShaderData(Os, FileName, bufferSize, buffer);

        gcoOS_Free(Os, buffer);
    }


Exit:
    if (DumpLog && log != gcvNULL)
    {
        printf("**************** Compile Log ****************");
        printf("%s", log);
        printf("*********************************************");
    }

    if (log != gcvNULL) gcoOS_Free(Os, log);

    if (source != gcvNULL) gcoOS_Free(Os, source);

    return binary;
}
コード例 #7
0
ファイル: opencl_device.cpp プロジェクト: Hincoin/mid-autumn
void OpenCLDevice::SetKernelFile(const char* file, const char *kernel_name)
{
	/* Create the kernel program */
	cl_int status;
	std::string source_string;
	ReadSource(file,&source_string);
	const char* source_code = source_string.c_str();
	program_ = clCreateProgramWithSource(
		context_,
		1,
		&source_code,
		NULL,
		&status);
	if (status != CL_SUCCESS) {
		fprintf(stderr, "Failed to open OpenCL kernel sources: %d\n", status);
		exit(-1);
	}

#ifdef __APPLE__
	status = clBuildProgram(program_, 1, devices_, "-I. -D__APPLE__", NULL, NULL);
#else
	status = clBuildProgram(program_, 1, devices_, "-I. ", NULL, NULL);
#endif
	if (status != CL_SUCCESS) {
		fprintf(stderr, "Failed to build OpenCL kernel: %d\n", status);

		size_t kernel_info_size;
		status = clGetProgramBuildInfo(
			program_,
			selected_device_,
			CL_PROGRAM_BUILD_LOG,
			0,
			NULL,
			&kernel_info_size);
		if (status != CL_SUCCESS) {
			fprintf(stderr, "Failed to get OpenCL kernel info size: %d\n", status);
			exit(-1);
		}

		char *build_log = (char *)malloc(kernel_info_size+ 1);
		status = clGetProgramBuildInfo(
			program_,
			selected_device_,
			CL_PROGRAM_BUILD_LOG,
			kernel_info_size,
			build_log,
			NULL);
		if (status != CL_SUCCESS) {
			fprintf(stderr, "Failed to get OpenCL kernel info: %d\n", status);
			exit(-1);
		}
		build_log[kernel_info_size] = '\0';

		fprintf(stderr, "OpenCL Program Build Log: %s\n", build_log);
		free(build_log);
	}
		kernel_ = clCreateKernel(program_, kernel_name, &status);
		if (status != CL_SUCCESS) {
			fprintf(stderr, "Failed to create OpenCL kernel: %d\n", status);
			exit(-1);
		}
		size_t work_group_size = 0;
		status = clGetKernelWorkGroupInfo(kernel_, selected_device_,
			CL_KERNEL_WORK_GROUP_SIZE,sizeof(work_group_size),&work_group_size,NULL);
		if(status != CL_SUCCESS)
		{
			fprintf(stderr, "Failed to get OpenCL kernel work group size info: %d\n", status);
			exit(-1);
		}
		work_group_size_ = work_group_size;
		printf("work_group_size: %d ",work_group_size_);
}
コード例 #8
0
ファイル: initMD.c プロジェクト: dnaziozeno/ateamscp
/* -------------------------------------------------------------------------
   O primeiro parametro a ser passado para esse agente e' o numero do proce-
   ssador em que esta executando o 'ns',  o segundo parametro e' o  nome  do
   arquivo que contem a instancia do SCP e o terceiro e' o nome do diretorio
   em que serao gerados os arquivos de estatisticas.
   ------------------------------------------------------------------------- */
main(int argc,char *argv[])
{

  int numSpawns = 1,                    /* Qtd de processos de serverMD      */ 
      errcodes[numSpawns],              /* Array de erros para o spawn. Um   */
  					                    /* código por processo               */										
      
      /* Variáveis de controle de um grupo de processos da MPI*/
      size,
      rank;	
	

  MPI_Init(&argc, &argv);               
  MPI_Comm_size(MPI_COMM_WORLD, &size);   					                     
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);                                         
  MPI_Comm interComSpawn; 		        
                                        
  char        	 *look        = NULL,
                 path[200];
  unsigned long  NbServerMD   = 0;
               
/*
  MaxLenDualMem = (int)  ReadAteamParam(2);
  ReducPerc     = (int)  ReadAteamParam(12);
  RandomInitMD  = (char) ReadAteamParam(16);
*/

  MaxLenDualMem = atoi(argv[3]);
  ReducPerc     = atoi(argv[4]);
  RandomInitMD  = (char) atoi(argv[5]);

  /* OBS: Esse arquivo de ser passado por argv[2] */
  if (!(finput = fopen(argv[1],"r")))
   { printf("\n\n* Erro na abertura do arquivo %s. *",argv[1]);
     exit(1);
   }
  
   
  ReadSource();          /* Localizada em readsc.c */
  fclose(finput);
  Reduction(NULL,NULL); /* Localizada em reduction.c */
  srand48(time(NULL));

  if (argc == 10)
    strcpy(path,argv[2]);
  else
    strcpy(path,"./");
  look = argv[1];
  while (look)
    if (look = (char *) strstr(argv[1],"/"))
      argv[1] = (look + 1);
  strcat(path,argv[1]);
  
//  char *param = malloc(200 * sizeof(char));
//  strcpy(param, path);
 
    char *param[7];
    param[0] = (char *) malloc (512 * sizeof(char));
    param[1] = (char *) malloc (16 * sizeof(char));
    param[2] = (char *) malloc (16 * sizeof(char));
    param[3] = (char *) malloc (16 * sizeof(char));
    param[4] = (char *) malloc (16 * sizeof(char));
    param[5] = (char *) malloc (16 * sizeof(char));
    param[6] = NULL;

    strcpy(param[0], path);
    strcpy(param[1], argv[3]);
    strcpy(param[2], argv[6]);
    strcpy(param[3], argv[7]);
    strcpy(param[4], argv[8]);
    strcpy(param[5], argv[9]);

  /* ------------------------------------------------------------------------- */
  /* Iniciando o serverMD */
  
   MPI_Comm_spawn("../../AteamMPI/bin/serverMD", 
      param, 1, MPI_INFO_NULL, 0,  MPI_COMM_SELF, &interComSpawn, errcodes);		                  
  /* ------------------------------------------------------------------------- */
  /* Espera bloqueante necessária para não dar crash */
  	
  	char messageBlock[1];
  	MPI_Status status;
  	MPI_Recv(messageBlock, 1, MPI_CHAR, 0, MPI_ANY_TAG, interComSpawn, &status); 
  /* ------------------------------------------------------------------------- */
  
  
  int  method = INIT_GLOBAL_VARS, /* Primeira função a ser chamada pelo      */
         			              /* serverMD (INIT_GLOBAL_VARS)             */
       position = 0,              /* Marca as posicoes de cada dado 
                                                                  empacotado */
       flagConnect = 1;		      /* Flag para verificar se conectou com o 
       				                 servidor                                */
       
  char * buffer,                  /* Buffer contendo a mensagem a ser enviada*/
       port[MPI_MAX_PORT_NAME];   /* Porta para conectar com o serverMD      */
       
  MPI_Comm commServerMD;          /* Comunicador retornado apos a conexao com
  						                                          serverMD   */

  
 
  /* Verificando a existencia do serverMD - se sim recebe a porta */
  /* para conectar                                                */
  flagConnect = MPI_Lookup_name("ServerMD", MPI_INFO_NULL, port);

  if(flagConnect) 
  {
      printf("\n\n Erro: Porta não concebida \n\n");fflush(stdout);
  
  }else{	  
  	  
  	  /* Conecta como serverMD */	
      MPI_Comm_connect(port, MPI_INFO_NULL, 0, MPI_COMM_SELF, &commServerMD);
	  
	  buffer = malloc(3 * sizeof(int) + sizeof(float) + sizeof(unsigned long));
      
      /* Sequência de empacotamento da primeira mensagem */
	  MPI_Pack(&method, 1, MPI_INT, buffer, 3 * sizeof(int) + sizeof(float) + 
	  	sizeof(unsigned long), &position, commServerMD);
	  
	  /*
	   * Position foi incrementada: passa a referenciar a primeira
	   * posição livre no buffer e assim sucessivamente.   
	   */
	  MPI_Pack(&nb_lin, 1, MPI_INT, buffer, 3 * sizeof(int) + sizeof(float) + 
	  	sizeof(unsigned long), &position, commServerMD);
	  MPI_Pack(&nb_col, 1, MPI_INT, buffer, 3 * sizeof(int) + sizeof(float) + 
	  	sizeof(unsigned long), &position, commServerMD);
	  MPI_Pack(&density, 1, MPI_FLOAT, buffer, 3 * sizeof(int) + sizeof(float) + 
	  	sizeof(unsigned long), &position, commServerMD);
	  MPI_Pack(&NbServerMD, 1, MPI_UNSIGNED_LONG, buffer, 3 * sizeof(int) + 
	  	sizeof(float) + sizeof(unsigned long), &position, commServerMD);	 
	  /*
	   * Envia a mensagem empacotada para o serverMD, fazendo uso do comu-
	   * nicador interComSpawn resultante da chamada a rotina spawn
       */
  	  MPI_Send(buffer, position, MPI_PACKED, 0, 1, commServerMD);
  	  free(buffer);
  }
  
 
   /* A heuristica dual gulosa sera chamada <MaxLenDualMem> vezes para  gerar
	  solucoes que permitam preencher total ou parcialmente a memoria de solu-
	  coes duais. */
   ExecAgInitMD(commServerMD);
   FreeSource();
	
   int i = 0;
   int message = 1224;
   //printf("\n \n Messagen 1224 %d: \n", message);
   
   MPI_Send(&message, 1, MPI_INT, 0, 1, commServerMD);
 
   MPI_Comm_disconnect(&commServerMD);
   //printf("\n\n* Termino do Agente InitMD *");
   //printf("\n* A memoria de solucoes duais foi inicializada. *\n");
   
   MPI_Finalize();
}
コード例 #9
0
ファイル: CRoutine_Square.cpp プロジェクト: fabienbaron/liboi
/// Initialize the Chi2 routine.  Note, this internally allocates some memory for computing a parallel sum.
void CRoutine_Square::Init()
{
	// Read the kernel, compile it
	string source = ReadSource(mSource[0]);
    BuildKernel(source, "square", mSource[0]);
}
コード例 #10
0
ファイル: SpireLib.cpp プロジェクト: Angelineguan/Spire
	void ShaderLibFile::FromString(const String & src)
	{
		Clear();
		CoreLib::Text::Parser parser(src);
		while (!parser.IsEnd())
		{
			auto fieldName = parser.ReadWord();
			if (fieldName == L"name")
			{
				MetaData.ShaderName = parser.ReadWord();
			}
			else if (fieldName == L"source")
			{
				parser.Read(L"{");
				ReadSource(Sources, parser, src);
				parser.Read(L"}");
			}
			else if (fieldName == L"binary")
			{
			}
			else if (fieldName == L"world")
			{
				WorldMetaData world;
				world.Name = parser.ReadWord();
				parser.Read(L"{");
				while (!parser.LookAhead(L"}"))
				{
					auto subFieldName = parser.ReadWord();
					if (subFieldName == L"target")
						world.TargetName = parser.ReadWord();
					else if (subFieldName == L"in")
					{
						world.InputBlocks.Add(parser.ReadWord());
						parser.Read(L";");
					}
					else if (subFieldName == L"out")
					{
						world.OutputBlock = parser.ReadWord();
						parser.Read(L";");
					}
					else if (subFieldName == L"comp")
					{
						auto compName = parser.ReadWord();
						parser.Read(L";");
						world.Components.Add(compName);
					}
				}
				parser.Read(L"}");
				MetaData.Worlds[world.Name] = world;
			}
			else if (fieldName == L"interface")
			{
				InterfaceBlockMetaData block;
				if (!parser.LookAhead(L"{") && !parser.LookAhead(L"size"))
					block.Name = parser.ReadWord();
				if (parser.LookAhead(L"size"))
				{
					parser.ReadWord();
					block.Size = parser.ReadInt();
				}
				parser.Read(L"{");
				while (!parser.LookAhead(L"}") && !parser.IsEnd())
				{
					InterfaceBlockEntry entry;
					entry.Type = ILBaseTypeFromString(parser.ReadWord());
					entry.Name = parser.ReadWord();
					parser.Read(L":");
					entry.Offset = parser.ReadInt();
					parser.Read(L",");
					entry.Size = parser.ReadInt();
					if (parser.LookAhead(L"{"))
					{
						parser.Read(L"{");
						while (!parser.LookAhead(L"}") && !parser.IsEnd())
						{
							auto attribName = parser.ReadWord();
							parser.Read(L":");
							auto attribValue = parser.ReadStringLiteral();
							parser.Read(L";");
							entry.Attributes[attribName] = attribValue;
						}
						parser.Read(L"}");
					}
					parser.Read(L";");
					block.Entries.Add(entry);
				}
				parser.Read(L"}");
				MetaData.InterfaceBlocks[block.Name] = block;
			}
		}
	}
コード例 #11
0
ファイル: SpireLib.cpp プロジェクト: Angelineguan/Spire
	void ShaderLibFile::AddSource(CoreLib::Basic::String source, CoreLib::Text::Parser & parser)
	{
		ReadSource(Sources, parser, source);
	}
コード例 #12
0
ファイル: freclien.cpp プロジェクト: jetlive/skiaming
/*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M
  Method:   CMainWindow::DoMenu

  Summary:  Dispatch and handle the main menu commands.

  Args:     WPARAM wParam,
              First message parameter (word sized).
            LPARAM lParam)
              Second message parameter (long sized).

  Modifies: m_ofnFile, ...

  Returns:  LRESULT
              Standard Windows WindowProc return value.
M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/
LRESULT CMainWindow::DoMenu(
    WPARAM wParam,
    LPARAM lParam)
{
    LRESULT lResult = FALSE;

    switch (LOWORD(wParam))
    {
    //----------------------------------------------------------------------
    // Handle File Menu Commands.
    //----------------------------------------------------------------------
    case IDM_FILE_EXIT:
        // The user commands us to exit this application so we tell the
        // Main window to close itself.
        ::PostMessage(m_hWnd, WM_CLOSE, 0, 0);
        break;

    //----------------------------------------------------------------------
    // Handle Help Menu Commands.
    //----------------------------------------------------------------------
    case IDM_HELP_CONTENTS:
        // We have some stubbed support here for bringing up the online
        //   Help for this application.
        if (::FileExist(m_szHelpFile))
            ::WinHelp(m_hWnd, m_szHelpFile, HELP_CONTEXT, IDH_CONTENTS);
        else
            m_pMsgBox->ErrorID(IDS_NOHELPFILE);
        break;
    case IDM_HELP_README:
        // Call the APPUTIL utility function ReadMe to read the FRECLIEN.TXT
        // "readme" file associated with this tutorial code sample.
        ReadMeFile(m_hWnd, TEXT(READMEDLL_CLIENT_FILE_STR));
        break;
    case IDM_HELP_READMEDLL:
        // Call the APPUTIL utility function ReadMe to read the FRESERVE.TXT
        // "readme" file associated with the companion FRESERVE DLL.
        ReadMeFile(m_hWnd, TEXT(READMEDLL_SERVER_FILE_STR));
        break;
    case IDM_HELP_READSOURCE:
        // Call the APPUTIL utility function ReadSource to allow the
        // user to open and read any of the source files of FRECLIEN.
        ReadSource(m_hWnd, &m_ofnFile);
        break;
    case IDM_HELP_ABOUT:
    {
        CAboutBox dlgAboutBox;

        // Show the standard About Box dialog for this EXE by telling the
        // dialog C++ object to show itself by invoking its ShowDialog
        // method.  Pass it this EXE instance and the parent window handle.
        // Use a dialog resource ID for the dialog template stored in
        // this EXE module's resources.
        dlgAboutBox.ShowDialog(
            m_hInst,
            MAKEINTRESOURCE(IDM_HELP_ABOUT),
            m_hWnd);
    }
    break;

    default:
        // Defer all messages NOT handled here to the Default Window Proc.
        lResult = ::DefWindowProc(m_hWnd, WM_COMMAND, wParam, lParam);
        break;
    }

    return(lResult);
}