示例#1
0
	UINT ShaderGL::CreateFromMemory(char* source)
	{
		mSource = source;

		mProgram = glCreateProgram();

		if (mProgram < 0)
		{
			Debug::ShowError(
				"Could not create shader program.",
				"Shader Loader Error");
		}

		
		if (strstr(mSource, "VERTEX_SHADER") != nullptr)
		{
			const char *vshader[2] = { "#version 330\n#define VERSION_GL\n#define VERTEX_SHADER\n\0", mSource };

			if (!Compile(vshader, mVertexShader, GL_VERTEX_SHADER, 2))
				return S_FALSE;

			glAttachShader(mProgram, mVertexShader);
		}

		
		if (strstr(mSource, "GEOMETRY_SHADER") != nullptr)
		{
			const char *gshader[2] = { "#version 330\n#define VERSION_GL\n#define GEOMETRY_SHADER\n\0", mSource };

			if (!Compile(gshader, mGeometryShader, GL_GEOMETRY_SHADER, 2))
				return S_FALSE;

			glAttachShader(mProgram, mGeometryShader);
		}

		
		if (strstr(mSource, "FRAGMENT_SHADER") != nullptr)
		{
			const char *fshader[2] = { "#version 330\n#define VERSION_GL\n#define FRAGMENT_SHADER\n\0", mSource };

			if (!Compile(fshader, mFragmentShader, GL_FRAGMENT_SHADER, 2))
				return S_FALSE;

			glAttachShader(mProgram, mFragmentShader);
		}

		Debug::Log("Shader Compiled Successfully!");

		
		int didCompile;

		glLinkProgram(mProgram);
		glGetProgramiv(mProgram, GL_LINK_STATUS, &didCompile);

		if (didCompile == GL_FALSE)
		{
			char* compileLog;
			int length;

			glGetProgramiv(mProgram, GL_INFO_LOG_LENGTH, &length);

			compileLog = (char*)malloc(length);

			glGetProgramInfoLog(mProgram, length, &length, compileLog);

			Debug::Log("\nLink Shader Log");
			Debug::Log(compileLog);

			free(compileLog);

			Release();

			return S_FALSE;
		}

		CreateAttribute("Position", VertexAttribute::POSITION);
		CreateAttribute("TexCoord0", VertexAttribute::TEXCOORD0);
		CreateAttribute("TexCoord1", VertexAttribute::TEXCOORD1);
		CreateAttribute("TexCoord2", VertexAttribute::TEXCOORD2);
		CreateAttribute("QuadCoord0", VertexAttribute::QUADCOORD0);
		CreateAttribute("QuadCoord1", VertexAttribute::QUADCOORD1);
		CreateAttribute("QuadCoord2", VertexAttribute::QUADCOORD2);
		CreateAttribute("Normal", VertexAttribute::NORMAL);
		CreateAttribute("Color", VertexAttribute::COLOR);
		CreateAttribute("Tangent", VertexAttribute::TANGENT);
		CreateAttribute("BoneCount", VertexAttribute::BONE_COUNT);
		CreateAttribute("BoneMatrix", VertexAttribute::BONE_INDEX);
		CreateAttribute("BoneWeight", VertexAttribute::BONE_WEIGHT);

		if (CreateAttribute("Matrix", VertexAttribute::MATRIX))
			mAttributeSize += 3;

		VertexLayoutGL* layout = new VertexLayoutGL();

		UINT size = (UINT)mAttributes.size();
		for (UINT x = 0; x < size; ++x)
		{
			layout->AddAttribute(mAttributes[x]);
		}

		mLayout = std::shared_ptr< VertexLayout >(layout);

		CreateUniform("_WorldViewProj", ShaderUniform::WORLD_VIEW_PROJ);
		CreateUniform("_WorldView", ShaderUniform::WORLD_VIEW);
		CreateUniform("_World", ShaderUniform::WORLD);
		CreateUniform("_InvWorld", ShaderUniform::INV_WORLD);
		CreateUniform("_View", ShaderUniform::VIEW);
		CreateUniform("_InvView", ShaderUniform::INV_VIEW);
		CreateUniform("_Proj", ShaderUniform::PROJ);
		CreateUniform("_InvProj", ShaderUniform::INV_PROJ);
		CreateUniform("_Ambient", ShaderUniform::AMBIENT);
		CreateUniform("_Diffuse", ShaderUniform::DIFFUSE);
		CreateUniform("_Specular", ShaderUniform::SPECULAR);
		CreateUniform("_SpecComp", ShaderUniform::SPEC_COMP);
		CreateUniform("_LightPos", ShaderUniform::LIGHT_POS);
		CreateUniform("_LightDir", ShaderUniform::LIGHT_DIR);
		CreateUniform("_LightColor", ShaderUniform::LIGHT_COLOR);
		CreateUniform("_LightAttn", ShaderUniform::LIGHT_ATTN);
		CreateUniform("_LightMatrix", ShaderUniform::LIGHT_MATRIX);
		CreateUniform("_LightCubeMatrix", ShaderUniform::LIGHT_CUBE_MATRIX);
		CreateUniform("_CameraPos", ShaderUniform::CAMERA_POS);
		CreateUniform("_Bones", ShaderUniform::BONES);
		CreateUniform("_DeltaTime", ShaderUniform::DELTA_TIME);

		UINT numTextureCube = 0;
		if (CreateUniform("_TextureCube", ShaderUniform::LIGHT_TEXTURE_CUBE))
			++numTextureCube;

		UINT numTexture = 0;
		char texName[16];
		for (int x = 0; x < MAX_TEXTURES; ++x)
		{
			sprintf_s(texName, "_Texture%d", x);

			if (CreateUniform(texName, ShaderUniform::TEXTURE))
				++numTexture;
		}

		mNumSamplers = numTexture + numTextureCube;

		if (mNumSamplers > 0)
		{
			mSampler = new Sampler*[mNumSamplers];

			UINT index = 0;

			for (; index < numTextureCube; ++index)
				mSampler[index] = new SamplerCubeGL();

			for (; index < mNumSamplers; ++index)
				mSampler[index] = new SamplerGL();
		}

		Debug::Log("Shader Created Successfully!");

		return S_OK;
	}
示例#2
0
void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
{
	m_sCurrentController = this;
	m_sCurrentLogicManager = logicmgr;
	
	PyObject *excdict=		NULL;
	PyObject* resultobj=	NULL;
	
	switch(m_mode) {
	case SCA_PYEXEC_SCRIPT:
	{
		if (m_bModified)
			if (Compile()==false) // sets m_bModified to false
				return;
		if (!m_bytecode)
			return;
		
		/*
		 * This part here with excdict is a temporary patch
		 * to avoid python/gameengine crashes when python
		 * inadvertently holds references to game objects
		 * in global variables.
		 * 
		 * The idea is always make a fresh dictionary, and
		 * destroy it right after it is used to make sure
		 * python won't hold any gameobject references.
		 * 
		 * Note that the PyDict_Clear _is_ necessary before
		 * the Py_DECREF() because it is possible for the
		 * variables inside the dictionary to hold references
		 * to the dictionary (ie. generate a cycle), so we
		 * break it by hand, then DECREF (which in this case
		 * should always ensure excdict is cleared).
		 */

		excdict= PyDict_Copy(m_pythondictionary);

#if PY_VERSION_HEX >=  0x03020000
		resultobj = PyEval_EvalCode((PyObject *)m_bytecode, excdict, excdict);
#else
		resultobj = PyEval_EvalCode((PyCodeObject *)m_bytecode, excdict, excdict);
#endif

		/* PyRun_SimpleString(m_scriptText.Ptr()); */
		break;
	}
	case SCA_PYEXEC_MODULE:
	{
		if (m_bModified || m_debug)
			if (Import()==false) // sets m_bModified to false
				return;
		if (!m_function)
			return;
		
		PyObject *args= NULL;
		
		if(m_function_argc==1) {
			args = PyTuple_New(1);
			PyTuple_SET_ITEM(args, 0, GetProxy());
		}
		
		resultobj = PyObject_CallObject(m_function, args);
		Py_XDECREF(args);
		break;
	}
	
	} /* end switch */
	
	
	
	/* Free the return value and print the error */
	if (resultobj)
	{
		Py_DECREF(resultobj);
	}
	else
	{
		// something is wrong, tell the user what went wrong
		printf("Python script error from controller \"%s\":\n", GetName().Ptr());
		PyErr_Print();
		
		/* Added in 2.48a, the last_traceback can reference Objects for example, increasing
		 * their user count. Not to mention holding references to wrapped data.
		 * This is especially bad when the PyObject for the wrapped data is free'd, after blender 
		 * has already dealocated the pointer */
		PySys_SetObject( (char *)"last_traceback", NULL);
		PyErr_Clear(); /* just to be sure */
	}
	
	if(excdict) /* Only for SCA_PYEXEC_SCRIPT types */
	{
		/* clear after PyErrPrint - seems it can be using
		 * something in this dictionary and crash? */
		// This doesn't appear to be needed anymore
		//PyDict_Clear(excdict);
		Py_DECREF(excdict);
	}	
	
	m_triggeredSensors.clear();
	m_sCurrentController = NULL;
}
示例#3
0
文件: Shader.cpp 项目: realn/CodeBox
 CShader::CShader(ShaderType const type, cb::string const & source)
   : CShader(type)
 {
   Compile(source);
 }
示例#4
0
文件: view.cpp 项目: mongrelx/efte
int EView::ExecCommand(int Command, ExState &State) {
    switch (Command) {
    case ExSwitchTo:
        return SwitchTo(State);
    case ExFilePrev:
        return FilePrev();
    case ExFileNext:
        return FileNext();
    case ExFileLast:
        return FileLast();
    case ExFileOpen:
        return FileOpen(State);
    case ExFileOpenInMode:
        return FileOpenInMode(State);
    case ExFileSaveAll:
        return FileSaveAll();
    case ExListRoutines:
        return ViewRoutines(State);
    case ExDirOpen:
        return DirOpen(State);
    case ExViewMessages:
        return ViewMessages(State);
    case ExCompile:
        return Compile(State);
    case ExRunCompiler:
        return RunCompiler(State);
    case ExCompilePrevError:
        return CompilePrevError(State);
    case ExCompileNextError:
        return CompileNextError(State);
    case ExCvs:
        return Cvs(State);
    case ExRunCvs:
        return RunCvs(State);
    case ExViewCvs:
        return ViewCvs(State);
    case ExClearCvsMessages:
        return ClearCvsMessages(State);
    case ExCvsDiff:
        return CvsDiff(State);
    case ExRunCvsDiff:
        return RunCvsDiff(State);
    case ExViewCvsDiff:
        return ViewCvsDiff(State);
    case ExCvsCommit:
        return CvsCommit(State);
    case ExRunCvsCommit:
        return RunCvsCommit(State);
    case ExViewCvsLog:
        return ViewCvsLog(State);
    case ExSvn:
        return Svn(State);
    case ExRunSvn:
        return RunSvn(State);
    case ExViewSvn:
        return ViewSvn(State);
    case ExClearSvnMessages:
        return ClearSvnMessages(State);
    case ExSvnDiff:
        return SvnDiff(State);
    case ExRunSvnDiff:
        return RunSvnDiff(State);
    case ExViewSvnDiff:
        return ViewSvnDiff(State);
    case ExSvnCommit:
        return SvnCommit(State);
    case ExRunSvnCommit:
        return RunSvnCommit(State);
    case ExViewSvnLog:
        return ViewSvnLog(State);
    case ExViewBuffers:
        return ViewBuffers(State);
    case ExShowKey:
        return ShowKey(State);
    case ExToggleSysClipboard:
        return ToggleSysClipboard(State);
    case ExSetPrintDevice:
        return SetPrintDevice(State);
    case ExShowVersion:
        return ShowVersion();
    case ExViewModeMap:
        return ViewModeMap(State);
    case ExClearMessages:
        return ClearMessages();
    case ExTagNext:
        return TagNext(this);
    case ExTagPrev:
        return TagPrev(this);
    case ExTagPop:
        return TagPop(this);
    case ExTagClear:
        TagClear();
        return 1;
    case ExTagLoad:
        return TagLoad(State);
    case ExShowHelp:
        return SysShowHelp(State, 0);
    case ExConfigRecompile:
        return ConfigRecompile(State);
    case ExRemoveGlobalBookmark:
        return RemoveGlobalBookmark(State);
    case ExGotoGlobalBookmark:
        return GotoGlobalBookmark(State);
    case ExPopGlobalBookmark:
        return PopGlobalBookmark();
    }
    return Model ? Model->ExecCommand(Command, State) : 0;
}
示例#5
0
 ArgumentParser(const std::string& grammar)
 {
   Compile(grammar);
 }
示例#6
0
	Shader::Shader( ShaderType::shader_type_t shader, const std::string& code )
	{
		obj = gc.Create( glCreateShader( shader ), glDeleteShader );
		Source( code );
		Compile();
	}
示例#7
0
glFragmentShader::glFragmentShader(char *filename)
{
    m_object = glCreateShader(GL_FRAGMENT_SHADER);
    Load(filename);
    Compile();
}
示例#8
0
void SCA_PythonController::Trigger(SCA_LogicManager* logicmgr)
{
	m_sCurrentController = this;
	m_sCurrentLogicManager = logicmgr;
	
	PyObject *excdict=		NULL;
	PyObject *resultobj=	NULL;
	
	switch (m_mode) {
		case SCA_PYEXEC_SCRIPT:
		{
			if (m_bModified)
				if (Compile()==false) // sets m_bModified to false
					return;
			if (!m_bytecode)
				return;

			/*
			 * This part here with excdict is a temporary patch
			 * to avoid python/gameengine crashes when python
			 * inadvertently holds references to game objects
			 * in global variables.
			 *
			 * The idea is always make a fresh dictionary, and
			 * destroy it right after it is used to make sure
			 * python won't hold any gameobject references.
			 *
			 * Note that the PyDict_Clear _is_ necessary before
			 * the Py_DECREF() because it is possible for the
			 * variables inside the dictionary to hold references
			 * to the dictionary (ie. generate a cycle), so we
			 * break it by hand, then DECREF (which in this case
			 * should always ensure excdict is cleared).
			 */

			excdict= PyDict_Copy(m_pythondictionary);

			resultobj = PyEval_EvalCode((PyObject *)m_bytecode, excdict, excdict);

			/* PyRun_SimpleString(m_scriptText.Ptr()); */
			break;
		}
		case SCA_PYEXEC_MODULE:
		{
			if (m_bModified || m_debug)
				if (Import()==false) // sets m_bModified to false
					return;
			if (!m_function)
				return;

			PyObject *args= NULL;

			if (m_function_argc==1) {
				args = PyTuple_New(1);
				PyTuple_SET_ITEM(args, 0, GetProxy());
			}

			resultobj = PyObject_CallObject(m_function, args);
			Py_XDECREF(args);
			break;
		}

	} /* end switch */


	/* Free the return value and print the error */
	if (resultobj)
		Py_DECREF(resultobj);
	else
		ErrorPrint("Python script error");
	
	if (excdict) /* Only for SCA_PYEXEC_SCRIPT types */
	{
		/* clear after PyErrPrint - seems it can be using
		 * something in this dictionary and crash? */
		// This doesn't appear to be needed anymore
		//PyDict_Clear(excdict);
		Py_DECREF(excdict);
	}
	
	m_triggeredSensors.clear();
	m_sCurrentController = NULL;
}
示例#9
0
string ParseMaterialFile(char *mbuf)
{
    auto p = mbuf;

    string err;
    string last;
    string vfunctions, pfunctions, cfunctions, vertex, pixel, compute, vdecl, pdecl, csdecl, shader;
    string *accum = nullptr;

    auto word = [&]()
    {
        p += strspn(p, " \t\r");
        size_t len = strcspn(p, " \t\r\0");
        last = string(p, len);
        p += len;
    };

    auto finish = [&]() -> bool
    {
        if (!shader.empty())
        {

            auto sh = new Shader();
            if (compute.length())
            {
                auto header = "#version 430\n";
                err = sh->Compile(shader.c_str(),
                                  (header + csdecl + cfunctions + "void main()\n{\n" + compute + "}\n").c_str());
            }
            else
            {
                string header;
                #ifdef PLATFORM_ES2
                    header += "#ifdef GL_ES\nprecision highp float;\n#endif\n";
                #else
                    //#ifdef __APPLE__
                    header += "#version 120\n";
                    //#else
                    //header += "#version 130\n";
                    //#endif
                #endif
                err = sh->Compile(shader.c_str(),
                                  (header + vdecl + vfunctions + "void main()\n{\n" + vertex + "}\n").c_str(),
                                  (header + pdecl + pfunctions + "void main()\n{\n" + pixel + "}\n").c_str());
            }
            if (!err.empty())
                return true;
            shadermap[shader] = sh;
            shader.clear();
        }
        return false;
    };

    for (;;)
    {
        auto start = p;
        auto end = p + strcspn(p, "\n\0");
        bool eof = !*end;
        *end = 0;
        
        word();

        if (!last.empty())
        {
            if      (last == "VERTEXFUNCTIONS")  { if (finish()) return err; vfunctions.clear(); accum = &vfunctions; }
            else if (last == "PIXELFUNCTIONS")   { if (finish()) return err; pfunctions.clear(); accum = &pfunctions; }
            else if (last == "COMPUTEFUNCTIONS") { if (finish()) return err; cfunctions.clear(); accum = &cfunctions; }
            else if (last == "VERTEX")           {                           vertex.clear();     accum = &vertex;     }
            else if (last == "PIXEL")            {                           pixel.clear();      accum = &pixel;      }
            else if (last == "COMPUTE")          {                           compute.clear();    accum = &compute;    }
            else if (last == "SHADER")
            {
                if (finish()) return err;
                word();
                shader = last;
                vdecl.clear();
                pdecl.clear();
                csdecl.clear();
                vertex.clear();
                pixel.clear();
                compute.clear();
                accum = nullptr;
            }
            else if (last == "UNIFORMS")
            {
                string &decl = accum == &compute ? csdecl : (accum == &vertex ? vdecl : pdecl);
                for (;;)
                {
                    word();
                    if (last.empty()) break;
                    else if (last == "mvp")          decl += "uniform mat4 mvp;\n";
                    else if (last == "col")          decl += "uniform vec4 col;\n";
                    else if (last == "camera")       decl += "uniform vec3 camera;\n";
                    else if (last == "light1")       decl += "uniform vec3 light1;\n";
                    else if (last == "lightparams1") decl += "uniform vec2 lightparams1;\n";
                    else if (last == "bones")        decl += "uniform vec4 bones[230];\n";   // FIXME: configurable
                    else if (last == "pointscale")   decl += "uniform float pointscale;\n";
                    else if (!strncmp(last.c_str(), "tex", 3))
                    {
                        auto p = last.c_str() + 3;
                        bool cubemap = false;
                        bool floatingp = false;
                        if (!strncmp(p, "cube", 4))
                        {
                            p += 4;
                            cubemap = true;
                        }
                        if (*p == 'f')
                        {
                            p++;
                            floatingp = true;
                        }
                        auto unit = atoi(p);
                        if (accum == &compute)
                        {
                            decl += "layout(binding = " + to_string(unit) + ", " +
                                    (floatingp ? "rgba32f" : "rgba8") + ") ";
                        }
                        decl += "uniform ";
                        decl += accum == &compute ? (cubemap ? "imageCube" : "image2D")
                                                  : (cubemap ? "samplerCube" : "sampler2D");
                        decl += " " + last + ";\n";
                    }
                    else return "unknown uniform: " + last; 
                }
            }
            else if (last == "UNIFORM")
            {
                string &decl = accum == &compute ? csdecl : (accum == &vertex ? vdecl : pdecl);
                word();
                auto type = last;
                word();
                auto name = last;
                if (type.empty() || name.empty()) return "uniform decl must specify type and name";
                decl += "uniform " + type + " " + name + ";\n";
            }
            else if (last == "INPUTS")
            {
                string decl;
                for (;;)
                {
                    word();
                    if (last.empty()) break;
                    auto pos = strstr(last.c_str(), ":");
                    if (!pos)
                    {
                        return "input " + last + " doesn't specify number of components, e.g. anormal:3";
                    }
                    int comp = atoi(pos + 1);
                    if (comp <= 0 || comp > 4)
                    {
                        return "input " + last + " can only use 1..4 components";
                    }
                    last = last.substr(0, pos - last.c_str());
                    string d = " vec" + to_string(comp) + " " + last + ";\n";
                    if (accum == &vertex) vdecl += "attribute" + d;
                    else { d = "varying" + d; vdecl += d; pdecl += d; }
                }
            }
            else if (last == "LAYOUT")
            {
                word();
                auto xs = last;
                word();
                auto ys = last;
                csdecl += "layout(local_size_x = " + xs + ", local_size_y = " + ys + ") in;\n";
            }
            else
            {
                if (!accum) return "GLSL code outside of FUNCTIONS/VERTEX/PIXEL block: " + string(start);
                *accum += start;
                *accum += "\n";
            }
        }

        if (eof) break;
        *end = '\n';

        p = end + 1;
    }

    finish();
    return err;
}
示例#10
0
/***********************
 *                     *
 * ProcessCmd cmd      *
 *                     *
 ***********************/ 
int
ProcessCmd(PARSE_RESULT *result)
{
     CT_EXPR     *ctExpr     = NULL;
     COMB_EXPR   *combExpr   = NULL;
     M_INSTR     *macroCode  = NULL;
     CT_VAR_BASE *var_base   = NULL;
     ST_TYPE     *st_type;
     ST_KEY       funKey;

     switch (result->tag) {
	case SETCOMMAND: 
	  ge_ProcessSetCommand(result->info.setcommand);
	  break;
	case COMMAND: 
	  return (ge_ProcessCommand(result->info.command));
	  break;
	case QUERY:
	  ge_ProcessQuery(result->info.query);
	  break;
	case DATA:
	  addDatatype(result->info.data);
	  break;
	case ALIAS:
	  addAlias (result->info.alias);
	  break;

	case DEF:
#if 0
printf("RHS PARSE TREE:\n");
display_PE_EXPR(result->info.def->expr, 0);
#endif
 	  funKey = st_AddFunction(result->info.def);

	  /* typecheck the term logic parse tree */
	  tc_open_typechecker();
	  tc_typecheck_PE_DEF(result->info.def, funKey);
	  /* if this point reached then typecheck of def was successful */

	  ctExpr = pmTranslate(result->info.def->expr,1);

          if ( printCT_EXPR ) {
 	      printMsg(MSG, "\nCore term logic for the function is: \n");
              printMsg(MSG, "def %s{%L} = %V =>", result->info.def->id,
                                                result->info.def->macros,
                                                var_base);
 	      printMsg(MSG, "%r\n", ctExpr);
          }   /*  fi  */

          /* close after typecheck & patt translation are complete */
          /* we need to remove DEF if patt translation fails */
	  tc_close_typechecker(0);

	  ct_TranslateOpen();

	  /* if function definition contains any macros, we must add the   */
	  /* environment to the variable base                              */
	  if (result->info.def->macros) {
	       var_base = VarBasePairNew(parseHeapDesc, 
					 vb_pmTranslate(result->info.def->var_base),
					 &ct_vb_env);
	  }
	  else 
	       var_base = vb_pmTranslate(result->info.def->var_base);

	  ctExpr = ctPreTranslate (ctExpr);     /* [#@] */

	  combExpr = ctTranslate(result->info.def->id,
				 var_base,
				 ctExpr);

	  printMsg(MSG,"Function added:  %s%S",st_KeyToName(funKey),st_GetTypeSig(funKey));

	  macroCode = Compile(result->info.def->id, combExpr); 
	  CodeTableAdd(result->info.def->id, combExpr,  
		       macroCode);

	  ct_TranslateClose();
	  break;

	case EXPR:
#if 0
printf("PARSE TREE:\n");
display_PE_EXPR(result->info.expr, 0);
#endif
	  /* typecheck the term logic parse tree */
	  tc_open_typechecker();
	  st_type = tc_typecheck_PE_EXPR(result->info.expr);
	  /* if this point reached then typecheck was successful */
	  /* don't close typechecker until AFTER result st_type is printed below */

	  ctExpr = pmTranslate(result->info.expr,0);

          if ( printCT_EXPR )
	      printMsg(MSG, "\nCore term logic for the expression is: \n%r\n", ctExpr);

	  ct_TranslateOpen();

	  ctExpr = ctPreTranslate (ctExpr);     /* [#@] */

	  combExpr = ctTranslate(NULL, vb_pmTranslate(VBbang()), ctExpr);

	  mc_MachineOpen();
	  combExpr = Evaluate(combExpr, st_type);
	  kludge = 1;
	  combExprPrint(combExpr,PP_MAX_SHOW_DEPTH,PP_MAX_RECORD_DEPTH,st_type);
	  mc_MachineClose();
	  tc_close_typechecker(0);
	  ct_TranslateClose();
	  break;
	case EMPTY_INPUT:
	  break;
	default:
	  printMsg(FATAL_MSG, "ProcessCmd - Invalid tag (%d)", result->tag);
	  break;
	}
     return(1);
}   /*  end ProcessCmd  */
示例#11
0
文件: Eval.c 项目: overzeroe/Vyquon
/* Eval front-end: compile to bytecode, then evaluate the bytecode */
VyObj Eval(VyObj sexp){
    Bytecode* bytecode = Compile(sexp);
    VyObj result = EvalBytecode(bytecode);
    FreeBytecode(bytecode);
    return result;
}
示例#12
0
/***********************************************************
constructor
***********************************************************/
MapModel::MapModel(int nbfaces, MapFace *	faces)
    : _nbfaces(nbfaces), _faces(faces), _compiled(false)
{
    Compile(-1);
}
示例#13
0
void GLShader::Compile( const std::string& path )
{
	Compile(InferShaderType(path), path);
}
示例#14
0
文件: mode.hpp 项目: arrrrrrr/ebftpd
 Mode(const std::string& str) { Compile(str); }
示例#15
0
bool C4ObjectInfoCore::Load(C4Group &hGroup)
{
	StdStrBuf Source;
	return hGroup.LoadEntryString(C4CFN_ObjectInfoCore, &Source) &&
	       Compile(Source.getData());
}
示例#16
0
文件: bench.cpp 项目: deemonster/pire
	void Prepare(Algorithm a, const std::vector<Patterns>& patterns)
	{
		alg = a;
		Compile(patterns, alg == DefaultRun);
	}
 void IncrementalParser::Initialize() {
   CompilationOptions CO;
   CO.DeclarationExtraction = 0;
   CO.ValuePrinting = 0;
   Compile("", CO); // Consume initialization.
 }
示例#18
0
void SectionEndSelector::Select(SelectionTracker* tracker)
{
	Compile(tracker);
	for(auto it : mCompiledSections)
		SelectSectionEnd(tracker, it);
}
示例#19
0
glGeometryShader::glGeometryShader(char *filename)
{
    m_object = glCreateShader(GL_GEOMETRY_SHADER_EXT);
    Load(filename);
    Compile();
}
示例#20
0
void WayPointSelector::Select(SelectionTracker* tracker)
{
	Compile(tracker);
	for(auto it : mCompiledSections)
		SelectWayPoint(tracker, it);
}
示例#21
0
文件: thin3d_gl.cpp 项目: kg/ppsspp
void Thin3DGLVertexFormat::GLRestore() {
	Compile();
}
示例#22
0
void EventListener::ProcessEvent(Event& event)
{
	// If we've got nothing to do, abort
	if (!callable && source_code.Empty())
		return;

	// Do we need to compile the code?
	if (!callable && !source_code.Empty())
	{
		// Attempt to compile the code
		if (!Compile())
			return;
	}

	PyObject* py_namespace = GetGlobalNamespace();

	// Store current globals
	PyObject* old_event = PyDict_GetItemString(py_namespace, "event");
	PyObject* old_self = PyDict_GetItemString(py_namespace, "self");
	PyObject* old_document = PyDict_GetItemString(py_namespace, "document");
	// Clear any pending errors (KeyErrors if they didn't exist)
	PyErr_Clear();

	// Increase the ref to store the old values locally
	Py_XINCREF(old_event);
	Py_XINCREF(old_self);
	Py_XINCREF(old_document);

	// Set up the new expected globals
	PyDict_SetItemString(py_namespace, "event", Rocket::Core::Python::Utilities::MakeObject(&event).ptr());
	PyDict_SetItemString(py_namespace, "self", Rocket::Core::Python::Utilities::MakeObject(element).ptr());

	// Call the bound function
	PyObject* result = NULL;
	try
	{
		result = PyObject_CallObject(callable, NULL);
	}
	catch (python::error_already_set&)
	{		
	}

	// Check error conditions
	if (result)
	{
		Py_DECREF(result);
	}
	else
	{		
		Rocket::Core::Python::Utilities::PrintError(true);
	}

	// Remove the globals
	PyDict_DelItemString(py_namespace, "document");
	PyDict_DelItemString(py_namespace, "self");
	PyDict_DelItemString(py_namespace, "event");

	// Restore old events if necessary
	if (old_event)
	{
		PyDict_SetItemString(py_namespace, "event", old_event);
		Py_DECREF(old_event);
	}
	if (old_self)
	{
		PyDict_SetItemString(py_namespace, "self", old_self);
		Py_DECREF(old_self);
	}
	if (old_document)
	{
		PyDict_SetItemString(py_namespace, "document", old_document);
		Py_DECREF(old_document);
	}
}
bool OGLIndexedDraw::Init(int windowWidth, int windowHeight)
{
    bool res = gs::Stage::Init(windowWidth, windowHeight);
    
    if (res) {
        res &= InitGUI();
        
		/******************************* Shaders ********************************/
		
        auto vertexShader = std::make_unique<gs::Shader>(GL_VERTEX_SHADER);
        auto fragmentShader = std::make_unique<gs::Shader>(GL_FRAGMENT_SHADER);
        auto program = std::make_shared<gs::Program>();
        
        vertexShader->SetSource("heightmap.vert");
        res &= vertexShader->Compile();
        fragmentShader->SetSource("heightmap.frag");
        res &= fragmentShader->Compile();
        
        program->Attach(vertexShader->get());
        program->Attach(fragmentShader->get());
		res &= program->Link();
        program->Use();
        
        programs.push_back(program);
        
        glm::mat4 MVP = projection * glm::lookAt(glm::vec3(0, 40, -30), glm::vec3(0), glm::vec3(0, 1, 0));
        GLint mvpLocation = glGetUniformLocation(program->get(), "MVP");
		glUniformMatrix4fv(mvpLocation, 1, GL_FALSE, glm::value_ptr(MVP));	

		hDivLocation = glGetUniformLocation(program->get(), "heightDivider");
        
		/******************************* Geometry ********************************/
        auto vao = std::make_unique<gs::VertexArray>();
        vao->BindVAO();
        vaos.push_back(std::move(vao));

		auto vbo = std::make_unique<gs::VertexBuffer>(GL_ARRAY_BUFFER);
		vbo->BindVBO();
		vbos.push_back(std::move(vbo));

		heights = { 4.0f, 2.0f, 3.0f, 1.0f,
					3.0f, 5.0f, 8.0f, 2.0f,
					7.0f, 10.0f, 12.0f, 6.0f,
					4.0f, 6.0f, 8.0f, 3.0f };

		const float halfX = WORLD_SIZE_X * 0.5f;
		const float halfZ = WORLD_SIZE_Z * 0.5f;

		for (size_t i = 0; i < HM_SIZE_Z; i++) {
			for (size_t j = 0; j < HM_SIZE_X; j++)
			{
				short currentLineOffset = (short)j * HM_SIZE_Z;

				float xPos = j / (float)(HM_SIZE_X - 1) * WORLD_SIZE_X - halfX;
				float yPos = heights[i + currentLineOffset];
				float zPos = i / (float)(HM_SIZE_Z - 1) * WORLD_SIZE_Z - halfZ;
				vertices[i + currentLineOffset] = glm::vec3(xPos, yPos, zPos);
			}
		}
		glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * vertices.size(), vertices.data(), GL_STATIC_DRAW);

		/******************************* Indices ********************************/
		auto ibo = std::make_unique<gs::VertexBuffer>(GL_ELEMENT_ARRAY_BUFFER);
		ibo->BindVBO();
		vbos.push_back(std::move(ibo));

		const GLushort restartIndex = HM_SIZE_X * HM_SIZE_Z;
		indices = { 0, 4, 1, 5, 2, 6, 3, 7, restartIndex,
					4, 8, 5, 9, 6, 10, 7, 11, restartIndex,
					8, 12, 9, 13, 10, 14, 11, 15};
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * indices.size(), indices.data(), GL_STATIC_DRAW);

		glEnableVertexAttribArray(0);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);

		glEnable(GL_PRIMITIVE_RESTART);
		glEnable(GL_DEPTH_TEST);
		glPrimitiveRestartIndex(restartIndex);
    }
    return res;
}
示例#24
0
	void cShader<S>::Load(const cBlob& zBlob, GLenum zBinaryFormat)
	{
		unsigned id[1] = {Id()};
		glShaderBinary(1, id,zBinaryFormat,zBlob.Data(), zBlob.Length());
		Compile();
	}
示例#25
0
deferred_point::deferred_point()
	: Shader() {
	LoadShader("deferred-lighting.vs",GL_VERTEX_SHADER);
	LoadShader("deferred-point.fs",GL_FRAGMENT_SHADER);
	Compile();
};
/// Output the ISA representative of the compilation
void kcCLICommanderDX::RunCompileCommands(const Config& config, LoggingCallBackFuncP callback)
{
    bool isInitSuccessful = Init(config, callback);
    if (isInitSuccessful)
    {
        bool bIL = (config.m_ILFile.length() > 0);
        if (bIL)
        {
            callback("Warning: IL code generation for DX is currently not supported. --il command line switch will be ignored.\n");
        }

        bool bISA = false;
        bool bStatistics = false;
		bool bRegisterLiveness = false;
        if (config.m_ISAFile.length() > 0)
        {
            bISA = true;
        }
        if (config.m_AnalysisFile.length() > 0)
        {
            bStatistics = true;
        }
		if (config.m_LiveRegisterAnalysisFile.length() > 0)
		{
			bRegisterLiveness = true;
		}
        vector <AnalysisData> AnalysisDataVec;
        vector <string> DeviceAnalysisDataVec;

        // check for input correctness
        if ((config.m_FXC.length() > 0) && (config.m_SourceLanguage != SourceLanguage_DXasm))
        {
            std::stringstream s_Log;
            s_Log << "DXAsm must be specified when using FXC";
            LogCallBack(s_Log.str());
            return;
        }

        // check flags first
        if ((config.m_Profile.length() == 0) && (config.m_SourceLanguage == SourceLanguage_HLSL))
        {
            std::stringstream s_Log;
            s_Log << "-P Must be specified. Check compiler target: vs_5_0, ps_5_0 etc.";
            LogCallBack(s_Log.str());
            return;
        }

        if ((config.m_SourceLanguage != SourceLanguage_HLSL) && (config.m_SourceLanguage != SourceLanguage_DXasm) && (config.m_SourceLanguage != SourceLanguage_DXasmT))
        {
            std::stringstream s_Log;
            s_Log << "Source language is not supported. Please use ";
            LogCallBack(s_Log.str());
            return;
        }

        // Run FXC if required. It must be first because this is the input for the compilation. we cannot check for success.
        if (config.m_FXC.length() > 0)
        {
            std::string fixedCmd("\"");
            fixedCmd += config.m_FXC;
            fixedCmd += "\"";
            int iRet = ::system(fixedCmd.c_str());
            if (iRet != 0)
            {
                std::stringstream s_Log;
                s_Log << "FXC failed. Please check the arguments and path are correct. If path contains spaces, you need to put it in \\\"\\\" for example\n";
                s_Log << "-f  VsMain1 -s DXAsm -p vs_5_0 c:\\temp\\ClippingBlob.obj  --isa c:\\temp\\dxTest.isa -c tahiti --FXC \"\\\"C:\\Program Files (x86)\\Windows Kits\\8.1\\bin\\x86\\fxc.exe\\\" /E VsMain1 /T vs_5_0  /Fo c:/temp/ClippingBlob.obj c:/temp/Clipping.fx\" ";
                LogCallBack(s_Log.str());
                return;
            }
        }

        // see if the user asked for specific asics
        InitRequestedAsicList(config);

        // for logging purposes we will iterate through the requested ASICs, if input by user
        std::vector<string>::const_iterator asicIter;
        if (!config.m_ASICs.empty())
            asicIter = config.m_ASICs.begin();

        // We need to iterate over the selected devices
        bool bCompileSucces = false;
        for (std::vector<GDT_GfxCardInfo>::iterator devIter = m_dxDefaultAsicsList.begin(); devIter != m_dxDefaultAsicsList.end(); ++devIter)
        {
            // prepare for logging
            string sDevicenametoLog;
            if (!config.m_ASICs.empty() && asicIter != config.m_ASICs.end())
            {
                sDevicenametoLog = *asicIter;
                ++asicIter;
            }
            else
            {
                sDevicenametoLog = devIter->m_szCALName;
            }

            if (Compile(config, *devIter, sDevicenametoLog))
            {
                bCompileSucces = true;
                beStatus backendRet;
                size_t isaSizeInBytes = 0;
                string isail;
                bool rc = false;
                bool isIsaSizeDetected = false;
                bool shouldDetectIsaSize = true;

                if (bISA)
                {
                    backendRet = be->theOpenDXBuilder()->GetDxShaderISAText(devIter->m_szCALName, config.m_Function, config.m_Profile, isail);
                    string fileName = config.m_ISAFile;
                    if (backendRet == beStatus_SUCCESS)
                    {
                        std::stringstream s_Log;
                        rc = KAUtils::WriteTextFile(s_Log, fileName, IsaSuffix, isail, sDevicenametoLog, "");
                        LogCallBack(s_Log.str());

                        // Detect the ISA size.
                        isIsaSizeDetected = be->theOpenDXBuilder()->GetIsaSize(isail, isaSizeInBytes);

                        // If we managed to detect the ISA size, don't do it again.
                        shouldDetectIsaSize = !isIsaSizeDetected;

						if (bRegisterLiveness)
						{
							// Call the kcUtils routine to analyze <generatedFileName> and write
							// the analysis file.s
						}
                    }

                    if ((backendRet == beStatus_SUCCESS) && rc)
                    {
                        std::stringstream s_Log;
                        s_Log << KA_CLI_STR_EXTRACTING_ISA << sDevicenametoLog << KA_CLI_STR_STATUS_SUCCESS << std::endl;
                        LogCallBack(s_Log.str());
                    }
                    else
                    {
                        std::stringstream s_Log;
                        s_Log << KA_CLI_STR_EXTRACTING_ISA << sDevicenametoLog << KA_CLI_STR_STATUS_FAILURE << std::endl;
                        LogCallBack(s_Log.str());
                    }
                }

                if (bStatistics)
                {
                    AnalysisData analysis;

                    backendRet = be->theOpenDXBuilder()->GetStatistics(devIter->m_szCALName, config.m_Function, analysis);
                    if (backendRet == beStatus_SUCCESS)
                    {
                        if (shouldDetectIsaSize)
                        {
                            backendRet = be->theOpenDXBuilder()->GetDxShaderISAText(devIter->m_szCALName, config.m_Function, config.m_Profile, isail);
                            if (backendRet == beStatus_SUCCESS)
                            {
                                // Detect the ISA size.
                                isIsaSizeDetected = be->theOpenDXBuilder()->GetIsaSize(isail, isaSizeInBytes);
                            }
                        }

                        if (isIsaSizeDetected)
                        {
                            // assign IsaSize returned above
                            analysis.ISASize = isaSizeInBytes;
                        }
                        else
                        {
                            // assign largest unsigned value, used as warning
                            LogCallBack("Warning: ISA size not available.\n");
                        }

                        // Get WavefrontSize
                        size_t nWavefrontSize = 0;
                        if (be->theOpenDXBuilder()->GetWavefrontSize(devIter->m_szCALName, nWavefrontSize))
                        {
                            analysis.wavefrontSize = nWavefrontSize;
                        }
                        else
                        {
                            LogCallBack("Warning: wavefrontSize size not available.\n");
                        }

                        AnalysisDataVec.push_back(analysis);
                        DeviceAnalysisDataVec.push_back(sDevicenametoLog);

                        std::stringstream s_Log;
                        s_Log << KA_CLI_STR_EXTRACTING_STATISTICS << sDevicenametoLog << KA_CLI_STR_STATUS_SUCCESS << std::endl;
                        LogCallBack(s_Log.str());
                    }
                    else
                    {
                        std::stringstream s_Log;
                        s_Log << KA_CLI_STR_EXTRACTING_STATISTICS << sDevicenametoLog << KA_CLI_STR_STATUS_FAILURE << std::endl;
                        LogCallBack(s_Log.str());
                    }
                }
            }
            std::stringstream s_Log;
            LogCallBack(s_Log.str());
        }

        if ((AnalysisDataVec.size() > 0) && bCompileSucces)
        {
            std::stringstream s_Log;
            WriteAnalysisDataForDX(config, AnalysisDataVec, DeviceAnalysisDataVec, config.m_AnalysisFile, s_Log);
            LogCallBack(s_Log.str());
        }

        // this we should do only once because it is the same to all devices
        if ((config.m_DumpMSIntermediate.size() > 0) && bCompileSucces)
        {
            string sDumpMSIntermediate;
            beStatus beRet = be->theOpenDXBuilder()->GetIntermediateMSBlob(sDumpMSIntermediate);
            if (beRet == beStatus_SUCCESS)
            {
                std::stringstream s_Log;
                if (KAUtils::WriteTextFile(s_Log, config.m_DumpMSIntermediate, "", sDumpMSIntermediate, "", ""))
                {
                    std::stringstream ss;
                    ss << KA_CLI_STR_D3D_ASM_GENERATION_SUCCESS << config.m_DumpMSIntermediate << endl;
                    LogCallBack(ss.str());
                }
                else
                {
                    std::stringstream ss;
                    ss << KA_CLI_STR_D3D_ASM_GENERATION_FAILURE << s_Log.str() << endl;
                    LogCallBack(ss.str());
                }
            }
        }
    }
}
示例#27
0
string LoadMaterialFile(const char *mfile)
{
    auto mbuf = (char *)LoadFile(mfile);
    auto p = mbuf;

    string err;
    string last;
    string vfunctions, pfunctions, vertex, pixel, vdecl, pdecl, shader;
    string *accum = NULL;

    string header;
    #if defined(__IOS__) || defined(ANDROID)
    header += "#ifdef GL_ES\nprecision highp float;\n#endif\n";
    #else
    //#ifdef __APPLE__
    header += "#version 120\n";
    //#else
    //header += "#version 130\n";
    //#endif
    #endif

    auto word = [&]()
    {
        p += strspn(p, " \t\r");
        size_t len = strcspn(p, " \t\r\0");
        last = string(p, len);
        p += len;
    };

    auto finish = [&]() -> bool
    {
        if (!shader.empty())
        {
            auto sh = new Shader();
            err = sh->Compile(shader.c_str(),
                              (header + vdecl + vfunctions + "void main()\n{\n" + vertex + "}\n").c_str(),
                              (header + pdecl + pfunctions + "void main()\n{\n" + pixel  + "}\n").c_str());
            if (!err.empty())
                return true;
            shadermap[shader] = sh;
            shader.clear();
        }
        return false;
    };

    for (;;)
    {
        auto start = p;
        auto end = p + strcspn(p, "\n\0");
        bool eof = !*end;
        *end = 0;
        
        word();

        if (!last.empty())
        {
            if      (last == "VERTEXFUNCTIONS") { if (finish()) goto out; vfunctions.clear(); accum = &vfunctions; }
            else if (last == "PIXELFUNCTIONS")  { if (finish()) goto out; pfunctions.clear(); accum = &pfunctions; }
            else if (last == "VERTEX")          {                         vertex.clear();     accum = &vertex;     }
            else if (last == "PIXEL")           {                         pixel.clear();      accum = &pixel;      }
            else if (last == "SHADER")
            {
                if (finish()) goto out;
                word();
                shader = last;
                vdecl.clear();
                pdecl.clear();
                accum = NULL;
            }
            else if (last == "UNIFORMS")
            {
                string &decl = accum == &vertex ? vdecl : pdecl;
                for (;;)
                {
                    word();
                    if (last.empty()) break;
                    else if (last == "mvp")    decl += "uniform mat4 mvp;\n";
                    else if (last == "col")    decl += "uniform vec4 col;\n";
                    else if (last == "camera") decl += "uniform vec3 camera;\n";
                    else if (last == "light1") decl += "uniform vec3 light1;\n";
                    else if (last == "bones")  decl += "uniform vec4 bones[240];\n";   // FIXME: configurable
                    else if (strstr(last.c_str(), "tex")) decl += "uniform sampler2D " + last + ";\n";
                    else { err = "unknown uniform: " + last; goto out; }
                }
            }
            else if (last == "INPUTS")
            {
                string decl;
                for (;;)
                {
                    word();
                    if (last.empty()) break;
                    auto pos = strstr(last.c_str(), ":");
                    if (!pos) { err = "input " + last + " doesn't specify number of components, e.g. anormal:3"; goto out; }
                    int comp = atoi(pos + 1);
                    if (comp <= 0 || comp > 4) { err = "input " + last + " can only use 1..4 components"; goto out; }
                    last = last.substr(0, pos - last.c_str());
                    string d = string(" vec") + inttoa(comp) + " " + last + ";\n";
                    if (accum == &vertex) vdecl += "attribute" + d;
                    else { d = "varying" + d; vdecl += d; pdecl += d; }
                }
            }
            else
            {
                if (!accum) { err = "GLSL code outside of FUNCTIONS/VERTEX/PIXEL block: " + string(start); goto out; }
                *accum += start;
                *accum += "\n";
            }
        }

        if (eof) break;

        p = end + 1;
    }

    finish();

    out:
    free(mbuf);

    return err;
}
bool OGLSimpleLighting::Init(int windowWidth, int windowHeight)
{
    bool res = gs::Stage::Init(windowWidth, windowHeight);
    
    if (res) {
        res &= InitGUI();

		// Program textured objects setup
        auto vertexShader = std::make_unique<gs::Shader>(GL_VERTEX_SHADER);
        auto programTex = std::make_shared<gs::Program>();
        
        vertexShader->SetSource("simpleLighting.vert");
        res &= vertexShader->Compile();
        programTex->Attach(vertexShader->get());
        
        auto fragmentShader = std::make_unique<gs::Shader>(GL_FRAGMENT_SHADER);
        fragmentShader->SetSource("simpleLighting.frag");
        res &= fragmentShader->Compile();
        programTex->Attach(fragmentShader->get());
        
		res &= programTex->Link();
		programTex->Use();
        programs.push_back(programTex);

		mvpLocation = glGetUniformLocation(programTex->get(), "MVP");
		normalMatrixLocation = glGetUniformLocation(programTex->get(), "NormalMatrix");
		light.direction = glm::vec3(-1.0f, 0.0f, 0.0f);
		light.ambientColor = glm::vec3(0.2f);
		light.diffuseColor = glm::vec3(1.0f);
		light.specularColor = light.diffuseColor;

		lightDirLoc = glGetUniformLocation(programTex->get(), "light.direction");
		diffuseLoc = glGetUniformLocation(programTex->get(), "light.diffuseColor");
		ambientLoc = glGetUniformLocation(programTex->get(), "light.ambientColor");
        
		//Texture setup
		auto textureFloor = std::make_unique<gs::Texture>(IMAGE_TYPE::GLI);
		res &= textureFloor->LoadTexture("Floor.dds");
		textureFloor->ChangeParameter(GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
		textureFloor->ChangeParameter(GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		textures.push_back(std::move(textureFloor));

		auto textureCamouflage = std::make_unique<gs::Texture>(IMAGE_TYPE::GLI);
		res &= textureCamouflage->LoadTexture("Hieroglyphes.dds");
		textures.push_back(std::move(textureCamouflage));

		// Geometry setup
        auto vao = std::make_unique<gs::VertexArray>();
        vao->BindVAO();
        vaos.push_back(std::move(vao));
        
		auto vbo = std::make_unique<gs::VertexBuffer>(GL_ARRAY_BUFFER);
		vbo->BindVBO();

		std::vector<gs::Vertex> vertices;
		OGLCube cube;
		cube.InitVertices(glm::vec3(0));
		vertices.insert(vertices.end(), cube.GetVertices().begin(), cube.GetVertices().end());		

		OGLQuad quad;
		quad.SetSize(1000);
		quad.InitVertices(glm::vec3(0));
		vertices.insert(vertices.end(), quad.GetVertices().begin(), quad.GetVertices().end());

		glBufferData(GL_ARRAY_BUFFER, sizeof(gs::Vertex) * vertices.size(), vertices.data(), GL_STATIC_DRAW);

		vbos.push_back(std::move(vbo));

		glEnableVertexAttribArray(0);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(gs::Vertex), (void*)offsetof(gs::Vertex, position));
		glEnableVertexAttribArray(1);
		glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(gs::Vertex), (void*)offsetof(gs::Vertex, texCoords));
		glEnableVertexAttribArray(2);
		glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(gs::Vertex), (void*)offsetof(gs::Vertex, normal));

		// Camera setup
        camera.SetPosition(glm::vec3(0.0f, 0.0f, 3.0f));
        camera.SetSpeed(8.0f);
        camera.SetupProjection(45.0f, windowWidth/(float)windowHeight);

		lightObj.Load("");

		// OpenGL setup
		glEnable(GL_DEPTH_TEST);
    }
    return res;
}
示例#29
0
文件: Shader.cpp 项目: realn/CodeBox
 bool CShader::Compile(cb::string const & source) {
   LoadSource(source);
   return Compile();
 }
void TestArchive::TestSources(int num_runs, std::vector<Path> other_sources) {
    if (is_interactive) {
        other_sources.push_back(official_source);
    }
    EnsureChecker(checker);
    Compile(checker);
    Compile(official_source);
    for (auto itr : other_sources) {
        Compile(itr);
    }
    stable_sort(testcases.begin(), testcases.end());
    srand(time(NULL));
    rand();
    srand(rand());
    rand();
    srand(rand());
    rand();
    srand(rand());
    int seed = rand();
    for (int run_number = 0; run_number <= num_runs; run_number += 1) {
        int test_number = 0;
        for (auto testcase : testcases) {
            std::cerr << GetBloatware() << "\t" << Colored(4, 2, 3, "Generating") << " input for test "
                      << Colored(5, 1, 2, Allign(StrCat("#", test_number), 3)) << '\t' << "run\t"
                      << Colored(5, 1, 1, Allign(StrCat("#", run_number), 3)) << '\n';
            seed -= 1;
            std::string input;
            if (run_number == 0) {
                input = testcase.Input();
            } else {
                input = testcase.Input(seed);
            }

            int test_gen_seed = seed;
            if (run_number == 0) {
                test_gen_seed = testcase.GetSeed();
            }

            os.WriteFile(Path::default_path + "/tumbletest/in.txt", input);

            if (not is_interactive) {
                EggResult official_result = debug_eggecutor.Run(official_source, input); std::cerr << '\n';
                std::string stdok = official_result.stdout;
                if (run_number == 0 and testcase.has_output) {
                    stdok = testcase.output;
                }

                for (auto itr : other_sources) {
                    EggResult other_result = debug_eggecutor.Run(itr, input); 

                    auto checker_results = deploy_eggecutor.RunChecker(checker, official_result.stdin,
                                                                       stdok, other_result.stdout);

                    std::cerr << "Checker: " << (checker_results.second.passed ? Colored(Color::green, "Passed!")
                                                                               : Colored(Color::red, "Not passed"))
                              << "\t" << Colored(Color::light_magenta, checker_results.second.message) << '\n';

                    if (not checker_results.second.passed) {
                        std::cerr << Colored(Color::red, "[Failed]") << '\n';
                        std::cerr << "Checker message:\"" << checker_results.second.message << '\n';
                        std::cerr << Colored(Color::light_magenta, "Test information\n");
                        std::cerr << testcase.Details(test_gen_seed) << '\n';
                        std::cerr << "Input Ok and Output have been written to tumbletest/{in,ok,out}.txt\n";

                        os.WriteFile(Path::default_path + "/tumbletest/in.txt", official_result.stdin);
                        os.WriteFile(Path::default_path + "/tumbletest/ok.txt", stdok);
                        os.WriteFile(Path::default_path + "/tumbletest/out.txt", other_result.stdout);
                        
                        exit(0);
                    }
                }
            } else {
                os.WriteFile(Path::default_path + "/tumbletest/in.txt", input);
                for (auto itr : other_sources) {
                    auto all_results = deploy_eggecutor.RunInteractive(itr, checker, input);

                    std::cerr << "Checker: " << (all_results.second.passed ? Colored(Color::green, "Passed!")
                                                                               : Colored(Color::red, "Not passed"))
                              << "\t" << Colored(Color::light_magenta, all_results.second.message) << '\n';

                    if (not all_results.second.passed) {
                        std::cerr << Colored(Color::red, "[Failed]") << '\n';
                        std::cerr << "Checker message:\"" << all_results.second.message << '\n';
                        std::cerr << Colored(Color::light_magenta, "Test information\n");
                        std::cerr << testcase.Details(test_gen_seed) << '\n';
                        std::cerr << "Input Ok and Output have been written to tumbletest/{in,ok,out}.txt\n";

                        exit(0);
                    }
                }
            }

            test_number += 1;
        }
    }
}