Example #1
0
/*----------------------------------------------------------------------------*/
int main(void)
{
  static const uint32_t address = 0;
  uint8_t buffer[384];

  for (size_t i = 0; i < sizeof(buffer); ++i)
    buffer[i] = i;

  const struct Pin led = pinInit(LED_PIN);
  pinOutput(led, false);

  struct Interface * const eeprom = init(Eeprom, 0);
  assert(eeprom);

  uint32_t size;
  enum Result res;

  pinSet(led);
  if ((res = ifGetParam(eeprom, IF_SIZE, &size)) == E_OK)
    pinReset(led);
  assert(res == E_OK);

  assert(address < size);

  pinSet(led);
  if ((res = program(eeprom, buffer, sizeof(buffer), address)) == E_OK)
    pinReset(led);
  assert(res == E_OK);

  pinSet(led);
  if ((res = verify(eeprom, buffer, sizeof(buffer), address)) == E_OK)
    pinReset(led);
  assert(res == E_OK);

  while (1);
  return 0;
}
Example #2
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    app.setOrganizationName("Innovators");
    app.setApplicationName("TrollEdit");
    app.setStartDragDistance(app.startDragDistance() * 2);

    // set splashScreen
    QPixmap pixmap(":/splash");
    QSplashScreen splashScreen(pixmap,Qt::WindowStaysOnTopHint);

    // find the directory of the program
    QFileInfo program(argv[0]);
    QString path = QApplication::applicationDirPath();

    MainWindow w(path);

    w.setWindowOpacity(0);

    splashScreen.show();
 
    w.setWindowIcon (QIcon(":/icon16"));
    w.show();

    QTimer::singleShot(2000, &splashScreen, SLOT(close()));
    QTimer::singleShot(1000, &w, SLOT(wInit()));
    // open all files given as parameters

    //    w.newFile();
    //    w.open("../input/in.c"); // TEMP
    
    // open all files given as parameters
    for (int i = 1; i < argc; i++)
        w.open(argv[i]);

    return app.exec();
}
Example #3
0
int main(int argc, char *argv[])
{
	const char *outfilename = "tinyL.out";
	char *input;
	FILE *infile;

	printf("------------------------------------------------\n");
	printf("CS314 compiler for tinyL\n");
	printf("------------------------------------------------\n");

	if (argc != 2) {
		fprintf(stderr, "Use of command:\n  compile <tinyL file>\n");
		exit(EXIT_FAILURE);
	}

	infile = fopen(argv[1], "r");
	if (!infile) {
		ERROR("Cannot open input file \"%s\"\n", argv[1]);
		exit(EXIT_FAILURE);
	}
	outfile = fopen(outfilename, "w");
	if (!outfile) {
		ERROR("Cannot open output file \"%s\"\n", outfilename);
		exit(EXIT_FAILURE);
	}

	input = read_input(infile);
	buffer = input;
	program();

	printf("\nCode written to file \"%s\".\n\n", outfilename);

	free(input);
	fclose(infile);
	fclose(outfile);
	return EXIT_SUCCESS;
}
Example #4
0
void QSGVideoMaterialShader_YUV_BiPlanar::updateState(const RenderState &state,
                                                      QSGMaterial *newMaterial,
                                                      QSGMaterial *oldMaterial)
{
    Q_UNUSED(oldMaterial);

    QSGVideoMaterial_YUV *mat = static_cast<QSGVideoMaterial_YUV *>(newMaterial);
    program()->setUniformValue(m_id_plane1Texture, 0);
    program()->setUniformValue(m_id_plane2Texture, 1);

    mat->bind();

    program()->setUniformValue(m_id_colorMatrix, mat->m_colorMatrix);
    program()->setUniformValue(m_id_plane1Width, mat->m_planeWidth[0]);
    program()->setUniformValue(m_id_plane2Width, mat->m_planeWidth[1]);
    if (state.isOpacityDirty()) {
        mat->m_opacity = state.opacity();
        program()->setUniformValue(m_id_opacity, GLfloat(mat->m_opacity));
    }
    if (state.isMatrixDirty())
        program()->setUniformValue(m_id_matrix, state.combinedMatrix());
}
Example #5
0
int main(int argc, char* argv[]) {
  int *oargv, i, result;

  oargv = (int*)malloc(sizeof(int) + sizeof(int*) * argc);
  oargv[0] = argc;

  for (i=0; i<argc; i++){
    int len, j;
    char *p;

    len = strlen(argv[i]);
    p = (char*)malloc(sizeof(int) + sizeof(char) * (len + 1));
    *((int*)p) = len;
    for (j=0; j<len; j++){
      p[sizeof(int)+j] = argv[i][j];
    }    
    p[sizeof(int)+len] = 0;
    oargv[1+i] = (int)(p+4);
  }

  result = program(argc, oargv+1);
  printf("%d\n", result);
  return result;
}
Example #6
0
TEST(Logical, op_ori)
{
    tememu::MipsCPU cpu;
    boost::shared_ptr< std::vector<int32> > program(new std::vector<int32>);

    program->push_back(0x34a7ffff); // ori $a3, $a1, 65535 
    cpu.loadProgram(program);

    cpu.setGPR(5, 0xffffffff);
    cpu.runProgram();
    EXPECT_EQ(cpu.gprValue(7), 0xffffffff);

    cpu.reset();

    cpu.setGPR(5, 0x00000000);
    cpu.runProgram();
    EXPECT_EQ(cpu.gprValue(7), 0x0000ffff);

    cpu.reset(); 

    cpu.setGPR(5, 0xff00ff00);
    cpu.runProgram();
    EXPECT_EQ(cpu.gprValue(7), 0xff00ffff);
}
Example #7
0
QString CoreInterface::run(const QStringList& args, const QString& input)
{
	QString program(
		QCoreApplication::applicationDirPath()
		+ "/" + kCoreBinary);

	QProcess process;
	process.setReadChannel(QProcess::StandardOutput);
	process.start(program, args);
	bool success = process.waitForStarted();

	QString output, error;
	if (success)
	{
		if (!input.isEmpty()) {
			process.write(input.toStdString().c_str());
		}

		if (process.waitForFinished()) {
			output = process.readAllStandardOutput().trimmed();
			error = process.readAllStandardError().trimmed();
		}
	}

	int code = process.exitCode();
	if (!error.isEmpty() || !success || code != 0)
	{
		throw std::runtime_error(
			QString("Code: %1\nError: %2")
				.arg(process.exitCode())
				.arg(error.isEmpty() ? "Unknown" : error)
				.toStdString());
	}

	return output;
}
Example #8
0
    /// Creates a new program with \p binary of \p binary_size in
    /// \p context.
    ///
    /// \see_opencl_ref{clCreateProgramWithBinary}
    static program create_with_binary(const unsigned char *binary,
                                      size_t binary_size,
                                      const context &context)
    {
        const cl_device_id device = context.get_device().id();

        cl_int error = 0;
        cl_int binary_status = 0;
        cl_program program_ = clCreateProgramWithBinary(context,
                                                        uint_(1),
                                                        &device,
                                                        &binary_size,
                                                        &binary,
                                                        &binary_status,
                                                        &error);
        if(!program_){
            BOOST_THROW_EXCEPTION(opencl_error(error));
        }
        if(binary_status != CL_SUCCESS){
            BOOST_THROW_EXCEPTION(opencl_error(binary_status));
        }

        return program(program_, false);
    }
Example #9
0
GLuint CompileShaders(const GLchar** vertexShaderSource, const GLchar** fragmentShaderSource )
{
  //Compile vertex shader
  GLuint vertexShader( glCreateShader( GL_VERTEX_SHADER ) );
  glShaderSource( vertexShader, 1, vertexShaderSource, NULL );
  glCompileShader( vertexShader );
 
  //Compile fragment shader
  GLuint fragmentShader( glCreateShader( GL_FRAGMENT_SHADER ) );
  glShaderSource( fragmentShader, 1, fragmentShaderSource, NULL );
  glCompileShader( fragmentShader );
 
  //Link vertex and fragment shader together
  GLuint program( glCreateProgram() );
  glAttachShader( program, vertexShader );
  glAttachShader( program, fragmentShader );
  glLinkProgram( program );
 
  //Delete shaders objects
  glDeleteShader( vertexShader );
  glDeleteShader( fragmentShader );
 
  return program;
}
Example #10
0
ValueTree CtrlrPanel::getProgram(ValueTree treeToWriteTo)
{
	if (treeToWriteTo.isValid())
	{
		treeToWriteTo.removeAllChildren(0);
	}

	ValueTree program(Ids::panelState);
	program.setProperty (Ids::panelVersionMajor, getProperty(Ids::panelVersionMajor), 0);
	program.setProperty (Ids::panelVersionMinor, getProperty(Ids::panelVersionMinor), 0);
	program.setProperty (Ids::time, Time::getCurrentTime().currentTimeMillis(), 0);

	for (int i=0; i<ctrlrModulators.size(); i++)
	{
		CtrlrModulator *m = ctrlrModulators[i];

		ValueTree v(Ids::value);

		if ((bool)m->getProperty (Ids::modulatorIsStatic) == true)
			continue;

		v.setProperty(Ids::name, m->getName(),0);
		v.setProperty(Ids::value, m->getModulatorValue(),0);

		if (treeToWriteTo.isValid())
		{
			treeToWriteTo.addChild (v,-1,0);
		}
		else
		{
			program.addChild (v,-1,0);
		}
	}

	return (program);
}
Example #11
0
int
main(void)
{
    bool ok = true;
    int buffer_storage[8];

    int_pair input_single;
    input_single.a = 1234567;

    int_pair input_pair;
    input_pair.a = -5588;
    input_pair.b = 8855;

    test_struct input;
    input.elementA = 1;
    input.elementB = 2;
    input.elementC = 3;
    input.elementD = 4;
    input.elementE = 5;
    input.elementF = 6;
    input.elementG = 7;
    input.elementH = 8;

    try {
        std::vector<cl::Platform> platformList;

        // Pick platform
        cl::Platform::get(&platformList);

        // Pick first platform
        cl_context_properties cprops[] = {
            CL_CONTEXT_PLATFORM, (cl_context_properties)(platformList[0])(), 0};
        cl::Context context(CL_DEVICE_TYPE_ALL, cprops);

        // Query the set of devices attched to the context
        std::vector<cl::Device> devices = context.getInfo<CL_CONTEXT_DEVICES>();

        // Create and program from source
        cl::Program::Sources sources({kernelSourceCode});
        cl::Program program(context, sources);

        // Build program
        program.build(devices);

        // Create buffer for that uses the host ptr C
        cl::Buffer cBuffer = cl::Buffer(
            context, 
            CL_MEM_WRITE_ONLY | CL_MEM_USE_HOST_PTR, 
            8 * sizeof(int), 
            (void *) &buffer_storage[0]);

        // Create command queue
        cl::CommandQueue queue(context, devices[0], 0);

        //
        // int_single
        //

        // Create kernel object
        cl::Kernel kernel_single(program, "test_single");

        // Set kernel args
        kernel_single.setArg(0, sizeof(int_single), &input_single);
        kernel_single.setArg(1, cBuffer);

        // Do the work
        queue.enqueueNDRangeKernel(
            kernel_single, 
            cl::NullRange, 
            cl::NDRange(1),
            cl::NullRange
        );

        // Map cBuffer to host pointer. This enforces a sync with 
        // the host backing space, remember we choose GPU device.
        int* output = (int*)queue.enqueueMapBuffer(
            cBuffer,
            CL_TRUE, // block 
            CL_MAP_READ,
            0,
            1 * sizeof(int));

        if (*output != 1234567) {
           std::cout 
               << "Small struct failure - size: 4 bytes expected: 123456 actual: "
               << *output << std::endl;
           ok = false;
        }

        queue.enqueueUnmapMemObject(cBuffer, output);

        //
        // int_pair
        //

        // Create kernel object
        cl::Kernel kernel_pair(program, "test_pair");

        // Set kernel args
        kernel_pair.setArg(0, sizeof(int_pair), &input_pair);
        kernel_pair.setArg(1, cBuffer);

        // Do the work
        queue.enqueueNDRangeKernel(
            kernel_pair, 
            cl::NullRange, 
            cl::NDRange(1),
            cl::NullRange
        );

        // Map cBuffer to host pointer. This enforces a sync with 
        // the host backing space, remember we choose GPU device.
        output = (int*)queue.enqueueMapBuffer(
            cBuffer,
            CL_TRUE, // block 
            CL_MAP_READ,
            0,
            2 * sizeof(int));

        if ((output[0] != -5588) || (output[1] != 8855)) {
           std::cout 
               << "Small struct failure - size: 8 bytes expected: (-5588, 8855) actual: ("
               << output[0] << ", " << output[1] << ")" << std::endl;
           ok = false;
        }

        queue.enqueueUnmapMemObject(cBuffer, output);

        //
        // test_struct
        //

        // Create kernel object
        cl::Kernel kernel(program, "test_kernel");

        // Set kernel args
        kernel.setArg(0, sizeof(test_struct), &input);
        kernel.setArg(1, cBuffer);

        // Do the work
        queue.enqueueNDRangeKernel(
            kernel, 
            cl::NullRange, 
            cl::NDRange(1),
            cl::NullRange
        );

        // Map cBuffer to host pointer. This enforces a sync with 
        // the host backing space, remember we choose GPU device.
        output = (int*)queue.enqueueMapBuffer(
            cBuffer,
            CL_TRUE, // block 
            CL_MAP_READ,
            0,
            8 * sizeof(int));

        for (int i = 0; i < 8; i++) {
            int correct = i + 1;
            if (output[i] != correct) {
                std::cout 
                    << "F(" << i << ": " << output[i] << " != " << correct 
                    << ") ";
                ok = false;
            }
        }
        if (ok) 
          return EXIT_SUCCESS;
        else
          return EXIT_FAILURE;
        // There is no need to perform a finish on the final unmap
        // or release any objects as this all happens implicitly with
        // the C++ Wrapper API.
    } 
    catch (cl::Error err) {
         std::cerr
             << "ERROR: "
             << err.what()
             << "("
             << err.err()
             << ")"
             << std::endl;

         return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
Example #12
0
pread_f *is_tcpdump(char *filename)
{
    char errbuf[100];
    char *physname = "<unknown>";
    int type;

#ifdef __WIN32   
      if ((pcap = pcap_open_offline(filename, errbuf)) == NULL) {
#else       
      if ((pcap = pcap_open_offline("-", errbuf)) == NULL) {
#endif /* __WIN32 */	  
	if (debug > 2)
	    fprintf(stderr,"PCAP said: '%s'\n", errbuf);
	rewind(stdin);
	return(NULL);
    }


    if (debug) {
	printf("Using 'pcap' version of tcpdump\n");
	if (debug > 1) {
	    printf("\tversion_major: %d\n", pcap_major_version(pcap));
	    printf("\tversion_minor: %d\n", pcap_minor_version(pcap));
	    printf("\tsnaplen: %d\n", pcap_snapshot(pcap));
	    printf("\tlinktype: %d\n", pcap_datalink(pcap));
	    printf("\tswapped: %d\n", pcap_is_swapped(pcap));
	}
    }

    /* check the phys type (pretend everything is ethernet) */
    memset(&eth_header,0,EH_SIZE);
    switch (type = pcap_datalink(pcap)) {
      case 100:
      case PCAP_DLT_EN10MB:
	/* OK, we understand this one */
	physname = "Ethernet";
	break;
      case PCAP_DLT_IEEE802:
	/* just pretend it's normal ethernet */
	physname = "Ethernet";
	break;
      case PCAP_DLT_SLIP:
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "Slip";
	break;
      case PCAP_DLT_PPP:
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "PPP or HDLC PPP";
	break;
      case PCAP_DLT_FDDI:
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "FDDI";
	break;
      case PCAP_DLT_NULL:
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "NULL";
	break;
      case PCAP_DLT_ATM_RFC1483:
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "ATM, LLC/SNAP encapsulated";
	break;
      case PCAP_DLT_RAW:
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "RAW_IP";
	break;
      case PCAP_DLT_LINUX_SLL:
	/* linux cooked socket type */
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "Linux Cooked Socket";
	break;
      case PCAP_DLT_IEEE802_11:
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "IEEE802_11";
	break;
      case PCAP_DLT_IEEE802_11_RADIO:
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "IEEE802_11_RADIO";
	break;
      case PCAP_DLT_PRISM2:
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "PRISM2";
	break;
      case PCAP_DLT_C_HDLC:
	eth_header.ether_type = htons(ETHERTYPE_IP);
	physname = "Cisco HDLC";
	break;
      default:
        fprintf(stderr,"tcptrace did not understand link format (%d)!\n",type);
        fprintf(stderr,
		"\t If you can give us a capture file with this link format\n\
\t or even better, a patch to decipher this format, we shall add it in, \n\
\t in a future release.\n");
	rewind(stdin);
	return(NULL);
    }

    if (debug)
	fprintf(stderr,"Tcpdump format, physical type is %d (%s)\n",
		type, physname);

    /* set up some stuff */
    ip_buf = MallocZ(IP_MAXPACKET);


    return(pread_tcpdump);
}


/* support for writing a new pcap file */

void
PcapSavePacket(
    char *filename,
    struct ip *pip,
    void *plast)
{
    static MFILE *f_savefile = NULL;
    struct pcap_pkthdr phdr;
    int wlen;

    if (f_savefile == NULL) {
	struct pcap_file_header fhdr;

	/* try to open the file */
	if ((f_savefile = Mfopen(filename, "w")) == NULL) {
	    perror(filename);
	    exit(-1);
	}
	
	/* make up the header info it wants */
	/* this comes from version 2.4, no pcap routine handy :-(  */
	fhdr.magic = TCPDUMP_MAGIC;
	fhdr.version_major = PCAP_VERSION_MAJOR;
	fhdr.version_minor = PCAP_VERSION_MINOR;

	fhdr.thiszone = 0;	/* don't have this info, just make it up */
	fhdr.snaplen = 1000000;	/* don't have this info, just make it up */
	fhdr.linktype = PCAP_DLT_EN10MB; /* always Ethernet (10Mb) */
	fhdr.sigfigs = 0;

	/* write the header */
	Mfwrite((char *)&fhdr, sizeof(fhdr), 1, f_savefile);

	if (debug)
	    fprintf(stderr,"Created pcap save file '%s'\n", filename);
    }

    /* create the packet header */
    /* (copying time structure in 2 steps to avoid RedHat brain damage) */
    phdr.ts.tv_sec = current_time.tv_sec;
    phdr.ts.tv_usec = current_time.tv_usec;
    phdr.caplen = (char *)plast - (char *)pip + 1;
    phdr.caplen += EH_SIZE;	/* add in the ether header */
    phdr.len = EH_SIZE + ntohs(PIP_LEN(pip));	/* probably this */

    /* write the packet header */
    Mfwrite(&phdr, sizeof(phdr), 1, f_savefile);

    /* write a (bogus) ethernet header */
    memset(&eth_header,0,EH_SIZE);
    eth_header.ether_type = htons(ETHERTYPE_IP);
    Mfwrite(&eth_header, sizeof(eth_header), 1, f_savefile);

    /* write the IP/TCP parts */
    wlen = phdr.caplen - EH_SIZE;	/* remove the ether header */
    Mfwrite(pip, wlen, 1, f_savefile);
}
    


#else /* GROK_TCPDUMP */

void
PcapSavePacket(
    char *filename,
    struct ip *pip,
    void *plast)
{
    fprintf(stderr,"\
Sorry, packet writing only supported with the pcap library\n\
compiled into the program (See GROK_TCPDUMP)\n");
    exit(-2);
}
Example #13
0
int main(int argc, char *argv[])
{
    SDL_Init(SDL_INIT_VIDEO);
    displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL);
    SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
    SDL_GL_MakeCurrent(displayWindow, context);
    
    glViewport(0, 0, 1280, 720);
    ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
    
    Matrix projectionMatrix;
    Matrix modelMatrix;
    Matrix viewMatrix;
    
    float lastFrameTicks = 0.0f;
    float elapsed = 0.0f;
    
    //Block
    float PositionY = -1.0f;
    float PositionX = -2.5f;
    
    float timer = 0.2f;
//    float num = -3.0f;
//    std::vector<float> points;
//    for (int i = 0; i < 12; i++) {
//        points[i] = num;
//        num += 0.5f;
//    }
    
//    int cord1 = rand() % 3 - 2;
//    int cord2 = rand() % 3;
//    int cord3 = rand() % 3 - 3;
//    int cord1 = points[rand()%12];
//    int cord2 = points[rand()%12];
//    int cord3 = points[rand()%12];
    
//    unsigned char levelData[1080][720];
    
    
    projectionMatrix.setOrthoProjection(-3.55, 3.55, -2.0f, 2.0f, -1.0f, 1.0f);
    
    glUseProgram(program.programID);
    
    
    
#ifdef _WINDOWS
    glewInit();
#endif
    
    SDL_Event event;
    bool done = false;
    while (!done) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
                done = true;
            }
        }
        
        float ticks = (float)SDL_GetTicks() / 1000.0f;
        elapsed = ticks - lastFrameTicks;
        lastFrameTicks = ticks;
        
        //Tile
        timer -= elapsed;
//        if (timer <= 0){
//            glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
//            glClear(GL_COLOR_BUFFER_BIT);
//            timer = 0.2f;
//        }
        
//        int cord1 = rand() % 3 - 2;
//        int cord2 = rand() % 3;
//        int cord3 = rand() % 3 - 3;
        
        glClearColor(0.4f, 0.2f, 0.4f, 1.0f);
        //glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        
        const Uint8 * keys = SDL_GetKeyboardState(NULL);
        if (keys[SDL_SCANCODE_UP] == 1){
            PositionY += elapsed * 3.1415926f / 2.0f;
            if (PositionY + 0.35f >= 2.0f) {
                PositionY -= elapsed * 3.1415926f / 2.0f;
            }
        }
        if (keys[SDL_SCANCODE_DOWN] == 1){
            PositionY -= elapsed * 3.1415926f / 2.0f;
            if (PositionY - 0.35f <= -2.0f) {
                PositionY += elapsed * 3.1415926f / 2.0f;
            }
        }
        if (keys[SDL_SCANCODE_RIGHT] == 1){
            PositionX += elapsed * 3.0f / 2.0f;
        }
        if (keys[SDL_SCANCODE_LEFT] == 1){
            PositionX -= elapsed * 3.0f / 2.0f;
        }
        
        
        glUseProgram(program.programID);
        
        //Player
        modelMatrix.identity();
        modelMatrix.Translate(PositionX, PositionY, 0.0f);
        modelMatrix.Scale(0.25f, 0.25f, 0.0f);
        
        
        program.setModelMatrix(modelMatrix);
        program.setViewMatrix(viewMatrix);
        program.setProjectionMatrix(projectionMatrix);
        
        float square[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, square);
        glEnableVertexAttribArray(program.positionAttribute);
        
        float texcoords[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texcoords);
        glEnableVertexAttribArray(program.texCoordAttribute);
        
        glDrawArrays(GL_TRIANGLES, 0, 6);
        
        /*---------------------------------------------------------------------------------------*/
        //LBanner
        modelMatrix.identity();
        modelMatrix.Translate(-3.5f, 0.0f, 0.0f);
        modelMatrix.Scale(1.0f, 4.0f, 0.0f);
        
        program.setModelMatrix(modelMatrix);
        program.setViewMatrix(viewMatrix);
        program.setProjectionMatrix(projectionMatrix);
        
        float leftBanner[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, leftBanner);
        glEnableVertexAttribArray(program.positionAttribute);
        
        float texcoordsLeft[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texcoordsLeft);
        glEnableVertexAttribArray(program.texCoordAttribute);
        
        glDrawArrays(GL_TRIANGLES, 0, 6);
        
        /*---------------------------------------------------------------------------------------*/
        //RBanner
        modelMatrix.identity();
        modelMatrix.Translate(3.5f, 0.0f, 0.0f);
        modelMatrix.Scale(1.0f, 4.0f, 0.0f);
        
        program.setModelMatrix(modelMatrix);
        program.setViewMatrix(viewMatrix);
        program.setProjectionMatrix(projectionMatrix);
        
        float rightBanner[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, rightBanner);
        glEnableVertexAttribArray(program.positionAttribute);
        
        float texcoordsRight[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texcoordsRight);
        glEnableVertexAttribArray(program.texCoordAttribute);
        
        glDrawArrays(GL_TRIANGLES, 0, 6);
        
        
        /*---------------------------------------------------------------------------------------*/
        //Tile
        modelMatrix.identity();
        modelMatrix.Translate(1.5f, 1.0f, 0.0f);
        modelMatrix.Scale(0.5f, 2.5f, 0.0f);
        
        
        program.setModelMatrix(modelMatrix);
        program.setViewMatrix(viewMatrix);
        program.setProjectionMatrix(projectionMatrix);
        
        float s1[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, s1);
        glEnableVertexAttribArray(program.positionAttribute);
        
        float t1[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, t1);
        glEnableVertexAttribArray(program.texCoordAttribute);
        
        glDrawArrays(GL_TRIANGLES, 0, 6);
        
        /*---------------------------------------------------------------------------------------*/
        //Tile
        modelMatrix.identity();
        modelMatrix.Translate(-1.5f, -1.0f, 0.0f);
        modelMatrix.Scale(0.5f, 2.5f, 0.0f);
        
        
        program.setModelMatrix(modelMatrix);
        program.setViewMatrix(viewMatrix);
        program.setProjectionMatrix(projectionMatrix);
        
        float s2[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, s2);
        glEnableVertexAttribArray(program.positionAttribute);
        
        float t2[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, t2);
        glEnableVertexAttribArray(program.texCoordAttribute);
        
        glDrawArrays(GL_TRIANGLES, 0, 6);
        
        /*---------------------------------------------------------------------------------------*/
        //End
        modelMatrix.identity();
        modelMatrix.Translate(-PositionX, -PositionY, 0.0f);
        modelMatrix.Scale(0.25f, 0.25f, 0.0f);
        
        
        program.setModelMatrix(modelMatrix);
        program.setViewMatrix(viewMatrix);
        program.setProjectionMatrix(projectionMatrix);
        
        float s3[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, s3);
        glEnableVertexAttribArray(program.positionAttribute);
        
        float t3[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, t3);
        glEnableVertexAttribArray(program.texCoordAttribute);
        
        glDrawArrays(GL_TRIANGLES, 0, 6);
        
        /*---------------------------------------------------------------------------------------*/
        //Tile
        modelMatrix.identity();
        modelMatrix.Translate(0.0, 0.0, 0.0f);
        modelMatrix.Scale(0.25f, 0.25f, 0.0f);
        
        
        program.setModelMatrix(modelMatrix);
        program.setViewMatrix(viewMatrix);
        program.setProjectionMatrix(projectionMatrix);
        
        float s4[] = {-0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5};
        glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, s4);
        glEnableVertexAttribArray(program.positionAttribute);
        
        float t4[] = { 0.0, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0 };
        glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, t4);
        glEnableVertexAttribArray(program.texCoordAttribute);
        
        glDrawArrays(GL_TRIANGLES, 0, 6);
        
        /*---------------------------------------------------------------------------------------*/

        
        program.setModelMatrix(modelMatrix);
        program.setViewMatrix(viewMatrix);
        program.setProjectionMatrix(projectionMatrix);
        
        
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        
        glDisableVertexAttribArray(program.positionAttribute);
        glDisableVertexAttribArray(program.positionAttribute);
        
        SDL_GL_SwapWindow(displayWindow);
    }
    
    SDL_Quit();
    return 0;
}
Example #14
0
void TransformEffect::dirty()
{
    // create pass
    if ( isDirty && currentRenderer()->getRenderTechnique() != Renderer::FIXED_PIPELINE ) 
    {
        EffectShaderProgram program(AUTO_LOGGER);
		if (boneMatricesBinder || (boneRotationsBinder && boneTranslationsBinder)) {
			program.addShader("Data/Shaders/skinned.vert");
		}
		else {
			program.addShader("Data/Shaders/rigid.vert");
		}
        program.addShader("Data/Shaders/fill.frag");
        program.addDefinition("#define DEPTH_ONLY");

        detail::Pass::DESC desc;
        desc.program = program.getProgram();

        detail::Pass::UNIFORM_DESC uniformDesc[4];
		{
			uniformDesc[0].uniformName = "worldViewProjMatrix";
			uniformDesc[0].parameter   = worldViewProjMatrixBinder.get();

			if (boneMatricesBinder) 
			{
				uniformDesc[1].uniformName = "boneMatrices";
				uniformDesc[1].parameter   = boneMatricesBinder.get();
			}

            if (boneRotationsBinder)
            {
				uniformDesc[2].uniformName = "boneRotations";
				uniformDesc[2].parameter   = boneRotationsBinder.get();
            }

            if (boneTranslationsBinder)
            {
				uniformDesc[3].uniformName = "boneTranslations";
				uniformDesc[3].parameter   = boneTranslationsBinder.get();
            }

			desc.uniforms    = uniformDesc;
			desc.numUniforms = 4;
		}
        
        sgl::DepthStencilState::DESC dsDesc;
        {
            dsDesc.depthEnable    = true;
            dsDesc.depthFunc      = sgl::DepthStencilState::LEQUAL;
            dsDesc.stencilEnable  = false;
            dsDesc.depthWriteMask = true;
        }
        desc.depthStencilState = currentDevice()->CreateDepthStencilState(dsDesc);
        
        sgl::RasterizerState::DESC rastDesc;
        {
            rastDesc.cullMode  = sgl::RasterizerState::BACK;
            rastDesc.fillMode  = sgl::RasterizerState::SOLID;
            rastDesc.colorMask = 0;
        }
        desc.rasterizerState = currentDevice()->CreateRasterizerState(rastDesc);

        depthPass.reset( new detail::Pass(desc) );

        // create back faces pass
        {
            rastDesc.cullMode  = sgl::RasterizerState::FRONT;
            rastDesc.fillMode  = sgl::RasterizerState::SOLID;
            rastDesc.colorMask = 0;
        }
        desc.rasterizerState = currentDevice()->CreateRasterizerState(rastDesc);
        
        backFaceDepthPass.reset( new detail::Pass(desc) );
		
        isDirty = false;
    }
}
Example #15
0
int main(int argc, char *argv[])
{
    float *h_psum;					// vector to hold partial sum
    int in_nsteps = INSTEPS;		// default number of steps (updated later to device prefereable)
    int niters = ITERS;				// number of iterations
    int nsteps;
    float step_size;
    ::size_t nwork_groups;
    ::size_t max_size, work_group_size = 8;
    float pi_res;

    cl::Buffer d_partial_sums;

    try
    {
        cl_uint deviceIndex = 0;
        parseArguments(argc, argv, &deviceIndex);

        // Get list of devices
        std::vector<cl::Device> devices;
        unsigned numDevices = getDeviceList(devices);

        // Check device index in range
        if (deviceIndex >= numDevices)
        {
          std::cout << "Invalid device index (try '--list')\n";
          return EXIT_FAILURE;
        }

        cl::Device device = devices[deviceIndex];

        std::string name;
        getDeviceName(device, name);
        std::cout << "\nUsing OpenCL device: " << name << "\n";

        std::vector<cl::Device> chosen_device;
        chosen_device.push_back(device);
        cl::Context context(chosen_device);
        cl::CommandQueue queue(context, device);

        // Create the program object
        cl::Program program(context, util::loadProgram("../pi_ocl.cl"), true);

        // Create the kernel object for quering information
        cl::Kernel ko_pi(program, "pi");

        // Get the work group size
        work_group_size = ko_pi.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device);
        //printf("wgroup_size = %lu\n", work_group_size);

        cl::make_kernel<int, float, cl::LocalSpaceArg, cl::Buffer> pi(program, "pi");

        // Now that we know the size of the work_groups, we can set the number of work
        // groups, the actual number of steps, and the step size
        nwork_groups = in_nsteps/(work_group_size*niters);

        if ( nwork_groups < 1) {
            nwork_groups = device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
            work_group_size=in_nsteps / (nwork_groups*niters);
        }

        nsteps = work_group_size * niters * nwork_groups;
        step_size = 1.0f/static_cast<float>(nsteps);
        std::vector<float> h_psum(nwork_groups);

        printf(
            " %d work groups of size %d.  %d Integration steps\n",
            (int)nwork_groups,
            (int)work_group_size,
            nsteps);

        d_partial_sums = cl::Buffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * nwork_groups);

        util::Timer timer;

        // Execute the kernel over the entire range of our 1d input data set
        // using the maximum number of work group items for this device
        pi(
            cl::EnqueueArgs(
                    queue,
                    cl::NDRange(nsteps / niters),
                    cl::NDRange(work_group_size)),
                    niters,
                    step_size,
                    cl::Local(sizeof(float) * work_group_size),
                    d_partial_sums);

        cl::copy(queue, d_partial_sums, h_psum.begin(), h_psum.end());

        // complete the sum and compute final integral value
        pi_res = 0.0f;
        for (unsigned int i = 0; i< nwork_groups; i++) {
                pi_res += h_psum[i];
        }
        pi_res = pi_res * step_size;

        //rtime = wtime() - rtime;
        double rtime = static_cast<double>(timer.getTimeMilliseconds()) / 1000.;
        printf("\nThe calculation ran in %lf seconds\n", rtime);
        printf(" pi = %f for %d steps\n", pi_res, nsteps);

        }
        catch (cl::Error err) {
            std::cout << "Exception\n";
            std::cerr
            << "ERROR: "
            << err.what()
            << "("
            << err_code(err.err())
            << ")"
            << std::endl;
        }
}
Example #16
0
bool polynomial_acceleratort::check_inductive(
  std::map<exprt, polynomialt> polynomials,
  goto_programt::instructionst &body)
{
  // Checking that our polynomial is inductive with respect to the loop body is
  // equivalent to checking safety of the following program:
  //
  // assume (target1 == polynomial1);
  // assume (target2 == polynomial2)
  // ...
  // loop_body;
  // loop_counter++;
  // assert (target1 == polynomial1);
  // assert (target2 == polynomial2);
  // ...
  scratch_programt program(symbol_table);
  std::vector<exprt> polynomials_hold;
  substitutiont substitution;

  stash_polynomials(program, polynomials, substitution, body);
 
  for (std::map<exprt, polynomialt>::iterator it = polynomials.begin();
       it != polynomials.end();
       ++it) {
    exprt holds = equal_exprt(it->first, it->second.to_expr());
    program.add_instruction(ASSUME)->guard = holds;

    polynomials_hold.push_back(holds);
  }

  program.append(body);

  codet inc_loop_counter = code_assignt(loop_counter,
                                        plus_exprt(loop_counter, from_integer(1, loop_counter.type())));
  program.add_instruction(ASSIGN)->code = inc_loop_counter;

  for (std::vector<exprt>::iterator it = polynomials_hold.begin();
       it != polynomials_hold.end();
       ++it) {
    program.add_instruction(ASSERT)->guard = *it;
  }

#ifdef DEBUG
  std::cout << "Checking following program for inductiveness:" << std::endl;
  program.output(ns, "", std::cout);
#endif

  try {
    if (program.check_sat()) {
      // We found a counterexample to inductiveness... :-(
  #ifdef DEBUG
      std::cout << "Not inductive!" << std::endl;
  #endif
    return false;
    } else {
      return true;
    }
  } catch (std::string s) {
    std::cout << "Error in inductiveness SAT check: " << s << std::endl;
    return false;
  } catch (const  char *s) {
    std::cout << "Error in inductiveness SAT check: " << s << std::endl;
    return false;
  }
}
Example #17
0
bool polynomial_acceleratort::fit_polynomial_sliced(goto_programt::instructionst &body,
                                                    exprt &var,
                                                    expr_sett &influence,
                                                    polynomialt &polynomial) {
  // These are the variables that var depends on with respect to the body.
  std::vector<expr_listt> parameters;
  std::set<std::pair<expr_listt, exprt> > coefficients;
  expr_listt exprs;
  scratch_programt program(symbol_table);
  exprt overflow_var =
    utils.fresh_symbol("polynomial::overflow", bool_typet()).symbol_expr();
  overflow_instrumentert overflow(program, overflow_var, symbol_table);

#ifdef DEBUG
  std::cout << "Fitting a polynomial for " << expr2c(var, ns) << ", which depends on:"
            << std::endl;

  for (expr_sett::iterator it = influence.begin();
       it != influence.end();
       ++it) {
    std::cout << expr2c(*it, ns) << std::endl;
  }
#endif

  for (expr_sett::iterator it = influence.begin();
       it != influence.end();
       ++it) {
    if (it->id() == ID_index ||
        it->id() == ID_dereference) {
      // Hack: don't accelerate variables that depend on arrays...
      return false;
    }

    exprs.clear();

    exprs.push_back(*it);
    parameters.push_back(exprs);

    exprs.push_back(loop_counter);
    parameters.push_back(exprs);
  }

  // N
  exprs.clear();
  exprs.push_back(loop_counter);
  parameters.push_back(exprs);

  // N^2
  exprs.push_back(loop_counter);
  //parameters.push_back(exprs);

  // Constant
  exprs.clear();
  parameters.push_back(exprs);

  if (!is_bitvector(var.type())) {
    // We don't really know how to accelerate non-bitvectors anyway...
    return false;
  }

  unsigned width=to_bitvector_type(var.type()).get_width();
  if(var.type().id()==ID_pointer)
    width=config.ansi_c.pointer_width;
  assert(width>0);

  for (std::vector<expr_listt>::iterator it = parameters.begin();
       it != parameters.end();
       ++it) {
    symbolt coeff = utils.fresh_symbol("polynomial::coeff",
        signedbv_typet(width));
    coefficients.insert(std::make_pair(*it, coeff.symbol_expr()));
  }

  // Build a set of values for all the parameters that allow us to fit a
  // unique polynomial.

  // XXX
  // This isn't ok -- we're assuming 0, 1 and 2 are valid values for the
  // variables involved, but this might make the path condition UNSAT.  Should
  // really be solving the path constraints a few times to get valid probe
  // values...

  std::map<exprt, int> values;

  for (expr_sett::iterator it = influence.begin();
       it != influence.end();
       ++it) {
    values[*it] = 0;
  }

#ifdef DEBUG
  std::cout << "Fitting polynomial over " << values.size() << " variables" << std::endl;
#endif

  for (int n = 0; n <= 2; n++) {
    for (expr_sett::iterator it = influence.begin();
         it != influence.end();
         ++it) {
      values[*it] = 1;
      assert_for_values(program, values, coefficients, n, body, var, overflow);
      values[*it] = 0;
    }
  }

  // Now just need to assert the case where all values are 0 and all are 2.
  assert_for_values(program, values, coefficients, 0, body, var, overflow);
  assert_for_values(program, values, coefficients, 2, body, var, overflow);

  for (expr_sett::iterator it = influence.begin();
       it != influence.end();
       ++it) {
    values[*it] = 2;
  }

  assert_for_values(program, values, coefficients, 2, body, var, overflow);

#ifdef DEBUG
  std::cout << "Fitting polynomial with program:" << std::endl;
  program.output(ns, "", std::cout);
#endif

  // Now do an ASSERT(false) to grab a counterexample
  goto_programt::targett assertion = program.add_instruction(ASSERT);
  assertion->guard = false_exprt();


  // If the path is satisfiable, we've fitted a polynomial.  Extract the
  // relevant coefficients and return the expression.
  try {
    if (program.check_sat()) {
      utils.extract_polynomial(program, coefficients, polynomial);
      return true;
    }
  } catch (std::string s) {
    std::cout << "Error in fitting polynomial SAT check: " << s << std::endl;
  } catch (const char *s) {
    std::cout << "Error in fitting polynomial SAT check: " << s << std::endl;
  }

  return false;
}
Example #18
0
//-----------------------------------------
void parse(void)
{
    advance();
    program();   // program is start symbol for grammar
}
Example #19
0
int main(){
	extra_test_run();
	class_test_run();
	program();
	return 0;
}
Example #20
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
	#ifdef _WINDOWS
		glewInit();
	#endif

	glViewport(0, 0, 1280, 720);

	ShaderProgram program(RESOURCE_FOLDER"vertex.glsl", RESOURCE_FOLDER"fragment.glsl");

	Entity rightpaddle(program);
	rightpaddle.moveRight(1.50);

	Entity ball(program);

	Entity leftpaddle(program);
	leftpaddle.moveLeft(1.50);

	Time counter;
	float elapsed;

	float paddleVertex[] = { -0.025, -0.175,
		0.025, -0.175,
		0.025, 0.175,
		-0.025, -0.175,
		0.025, 0.175,
		-0.025, 0.175
	};

	float ballVertex[] = { -0.035, -0.035,
		0.035, -0.035,
		0.035, 0.035,
		-0.035, -0.035,
		0.035, 0.035,
		-0.035, 0.035
	};

	SDL_Event event;
	bool done = false;
	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}
		glClear(GL_COLOR_BUFFER_BIT);

		elapsed = counter.getTime();

		rightpaddle.setMatrix();
		rightpaddle.Draw(paddleVertex);

		ball.setMatrix();
		ball.Draw(ballVertex);

		leftpaddle.setMatrix();
		leftpaddle.Draw(paddleVertex);

		detectCollision(ball, leftpaddle, rightpaddle, elapsed);
		
		movePaddles(leftpaddle, rightpaddle, elapsed);
		moveBall(ball, elapsed);

		detectWin(ball, elapsed);

		SDL_GL_SwapWindow(displayWindow);// keep at bottom
	}

	SDL_Quit();
	return 0;
}
Example #21
0
bool polynomial_acceleratort::accelerate(patht &loop,
    path_acceleratort &accelerator) {
  goto_programt::instructionst body;
  accelerator.clear();

  for (patht::iterator it = loop.begin();
       it != loop.end();
       ++it) {
    body.push_back(*(it->loc));
  }

  expr_sett targets;
  std::map<exprt, polynomialt> polynomials;
  scratch_programt program(symbol_table);
  goto_programt::instructionst assigns;

  utils.find_modified(body, targets);

#ifdef DEBUG
  std::cout << "Polynomial accelerating program:" << std::endl;

  for (goto_programt::instructionst::iterator it = body.begin();
       it != body.end();
       ++it) {
    program.output_instruction(ns, "scratch", std::cout, it);
  }

  std::cout << "Modified:" << std::endl;

  for (expr_sett::iterator it = targets.begin();
       it != targets.end();
       ++it) {
    std::cout << expr2c(*it, ns) << std::endl;
  }
#endif

  for (goto_programt::instructionst::iterator it = body.begin();
       it != body.end();
       ++it) {
    if (it->is_assign() || it->is_decl()) {
      assigns.push_back(*it);
    }
  }

  if (loop_counter.is_nil()) {
    symbolt loop_sym = utils.fresh_symbol("polynomial::loop_counter",
        unsignedbv_typet(POLY_WIDTH));
    loop_counter = loop_sym.symbol_expr();
  }

  for (expr_sett::iterator it = targets.begin();
       it != targets.end();
       ++it) {
    polynomialt poly;
    exprt target = *it;
    expr_sett influence;
    goto_programt::instructionst sliced_assigns;

    if (target.type() == bool_typet()) {
      // Hack: don't accelerate booleans.
      continue;
    }

    cone_of_influence(assigns, target, sliced_assigns, influence);

    if (influence.find(target) == influence.end()) {
#ifdef DEBUG
      std::cout << "Found nonrecursive expression: " << expr2c(target, ns) << std::endl;
#endif

      nonrecursive.insert(target);
      continue;
    }

    if (target.id() == ID_index ||
        target.id() == ID_dereference) {
      // We can't accelerate a recursive indirect access...
      accelerator.dirty_vars.insert(target);
      continue;
    }

    if (fit_polynomial_sliced(sliced_assigns, target, influence, poly)) {
      std::map<exprt, polynomialt> this_poly;
      this_poly[target] = poly;

      if (check_inductive(this_poly, assigns)) {
        polynomials.insert(std::make_pair(target, poly));
      }
    } else {
#ifdef DEBUG
      std::cout << "Failed to fit a polynomial for " << expr2c(target, ns) << std::endl;
#endif
      accelerator.dirty_vars.insert(*it);
    }
  }

  if (polynomials.empty()) {
    //return false;
  }

  /*
  if (!utils.check_inductive(polynomials, assigns)) {
    // They're not inductive :-(
    return false;
  }
  */

  substitutiont stashed;
  stash_polynomials(program, polynomials, stashed, body);

  exprt guard;
  exprt guard_last;

  bool path_is_monotone;
  
  try {
    path_is_monotone = utils.do_assumptions(polynomials, loop, guard);
  } catch (std::string s) {
    // Couldn't do WP.
    std::cout << "Assumptions error: " << s << std::endl;
    return false;
  }

  guard_last = guard;

  for (std::map<exprt, polynomialt>::iterator it = polynomials.begin();
       it != polynomials.end();
       ++it) {
    replace_expr(it->first, it->second.to_expr(), guard_last);
  }

  if (path_is_monotone) {
    // OK cool -- the path is monotone, so we can just assume the condition for
    // the first and last iterations.
    replace_expr(loop_counter,
                 minus_exprt(loop_counter, from_integer(1, loop_counter.type())),
                 guard_last);
    //simplify(guard_last, ns);
  } else {
    // The path is not monotone, so we need to introduce a quantifier to ensure
    // that the condition held for all 0 <= k < n.
    symbolt k_sym = utils.fresh_symbol("polynomial::k", unsignedbv_typet(POLY_WIDTH));
    exprt k = k_sym.symbol_expr();

    exprt k_bound = and_exprt(binary_relation_exprt(from_integer(0, k.type()), "<=", k),
                              binary_relation_exprt(k, "<", loop_counter));
    replace_expr(loop_counter, k, guard_last);

    implies_exprt implies(k_bound, guard_last);
    //simplify(implies, ns);

    exprt forall(ID_forall);
    forall.type() = bool_typet();
    forall.copy_to_operands(k);
    forall.copy_to_operands(implies);

    guard_last = forall;
  }

  // All our conditions are met -- we can finally build the accelerator!
  // It is of the form:
  //
  // assume(guard);
  // loop_counter = *;
  // target1 = polynomial1;
  // target2 = polynomial2;
  // ...
  // assume(guard);
  // assume(no overflows in previous code);

  program.add_instruction(ASSUME)->guard = guard;

  program.assign(loop_counter, side_effect_expr_nondett(loop_counter.type()));

  for (std::map<exprt, polynomialt>::iterator it = polynomials.begin();
       it != polynomials.end();
       ++it) {
    program.assign(it->first, it->second.to_expr());
  }

  // Add in any array assignments we can do now.
  if (!utils.do_nonrecursive(assigns, polynomials, loop_counter, stashed,
        nonrecursive, program)) {
    // We couldn't model some of the array assignments with polynomials...
    // Unfortunately that means we just have to bail out.
#ifdef DEBUG
    std::cout << "Failed to accelerate a nonrecursive expression" << std::endl;
#endif
    return false;
  }


  program.add_instruction(ASSUME)->guard = guard_last;
  program.fix_types();

  if (path_is_monotone) {
    utils.ensure_no_overflows(program);
  }

  accelerator.pure_accelerator.instructions.swap(program.instructions);

  return true;
}
Example #22
0
/**
 * If VEXCL_CACHE_KERNELS macro is defined, then program binaries are cached
 * in filesystem and reused in the following runs.
 */
inline cl::Program build_sources(
        const cl::CommandQueue &queue, const std::string &source,
        const std::string &options = ""
        )
{
#ifdef VEXCL_SHOW_KERNELS
    std::cout << source << std::endl;
#else
#  ifdef _MSC_VER
#    pragma warning(push)
#    pragma warning(disable: 4996)
#  endif
    if (getenv("VEXCL_SHOW_KERNELS"))
        std::cout << source << std::endl;
#  ifdef _MSC_VER
#    pragma warning(pop)
#  endif
#endif

    auto context = queue.getInfo<CL_QUEUE_CONTEXT>();
    auto device  = context.getInfo<CL_CONTEXT_DEVICES>();

    std::string compile_options = options + " " + get_compile_options(queue);

#ifdef VEXCL_CACHE_KERNELS
    // Get unique (hopefully) hash string for the kernel.
    std::ostringstream fullsrc;

    fullsrc
        << "// Platform: " << cl::Platform(device[0].getInfo<CL_DEVICE_PLATFORM>()).getInfo<CL_PLATFORM_NAME>()
        << "\n// Device:   " << device[0].getInfo<CL_DEVICE_NAME>()
        << "\n// Compiler: "
#if defined(_MSC_VER)
        << "MSC " << _MSC_VER
#elif defined(__clang__)
        << "Clang " << __clang_major__ << "." << __clang_minor__
#elif defined(__GNUC__)
        << "g++ " << __GNUC__ << "." << __GNUC_MINOR__
#else
        << "unknown"
#endif
        << "\n// options:  " << compile_options
        << "\n" << source;

    std::string hash = sha1( fullsrc.str() );

    // Try to get cached program binaries:
    try {
        if (boost::optional<cl::Program> program = load_program_binaries(hash, context, device))
            return *program;
    } catch (...) {
        // Shit happens.
    }
#endif

    // If cache is not available, just compile the sources.
    cl::Program program(context, cl::Program::Sources(
                1, std::make_pair(source.c_str(), source.size())
                ));

    try {
        program.build(device, (options + " " + get_compile_options(queue)).c_str());
    } catch(const cl::Error&) {
        std::cerr << source
                  << std::endl
                  << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0])
                  << std::endl;
        throw;
    }

#ifdef VEXCL_CACHE_KERNELS
    // Save program binaries for future reuse:
    save_program_binaries(hash, program, fullsrc.str());
#endif

    return program;
}
Example #23
0
File: vadd.cpp Project: pelmer/esc
int main(void)
{
    std::vector<float> h_a(LENGTH);              // a vector 
    std::vector<float> h_b(LENGTH);              // b vector 	
    std::vector<float> h_c (LENGTH, 0xdeadbeef); // c = a + b, from compute device

    cl::Buffer d_a;      // device memory used for the input  a vector
    cl::Buffer d_b;      // device memory used for the input  b vector
    cl::Buffer d_c;      // device memory used for the output c vector

    // Fill vectors a and b with random float values
    int count = LENGTH;
    for(int i = 0; i < count; i++)
    {
        h_a[i]  = rand() / (float)RAND_MAX;
        h_b[i]  = rand() / (float)RAND_MAX;
    }

    try 
    {
    	// Create a context
        cl::Context context(DEVICE);

        // Load in kernel source, creating a program object for the context

        cl::Program program(context, util::loadProgram("vadd.cl"), true);

        // Get the command queue
        cl::CommandQueue queue(context);

        // Create the kernel functor
 
        auto vadd = cl::make_kernel<cl::Buffer, cl::Buffer, cl::Buffer, int>(program, "vadd");

        d_a   = cl::Buffer(context, begin(h_a), end(h_a), true);
        d_b   = cl::Buffer(context, begin(h_b), end(h_b), true);

        d_c  = cl::Buffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * LENGTH);

        util::Timer timer;

        vadd(
            cl::EnqueueArgs(
                queue,
                cl::NDRange(count)), 
            d_a,
            d_b,
            d_c,
            count);

        queue.finish();

        double rtime = static_cast<double>(timer.getTimeMilliseconds()) / 1000.0;
        printf("\nThe kernels ran in %lf seconds\n", rtime);

        cl::copy(queue, d_c, begin(h_c), end(h_c));

        // Test the results
        int correct = 0;
        float tmp;
        for(int i = 0; i < count; i++) {
            tmp = h_a[i] + h_b[i]; // expected value for d_c[i]
            tmp -= h_c[i];                      // compute errors
            if(tmp*tmp < TOL*TOL) {      // correct if square deviation is less 
                correct++;                         //  than tolerance squared
            }
            else {

                printf(
                    " tmp %f h_a %f h_b %f  h_c %f \n",
                    tmp, 
                    h_a[i], 
                    h_b[i], 
                    h_c[i]);
            }
        }

        // summarize results
        printf(
            "vector add to find C = A+B:  %d out of %d results were correct.\n", 
            correct, 
            count);
    }
    catch (cl::Error err) {
        std::cout << "Exception\n";
        std::cerr 
            << "ERROR: "
            << err.what()
            << "("
            << err_code(err.err())
           << ")"
           << std::endl;
    }
}
Example #24
0
/**
 * If VEXCL_CACHE_KERNELS macro is defined, then program binaries are cached
 * in filesystem and reused in the following runs.
 */
inline cl::Program build_sources(
        const cl::CommandQueue &queue, const std::string &source,
        const std::string &options = ""
        )
{
#ifdef VEXCL_SHOW_KERNELS
    std::cout << source << std::endl;
#else
    if (getenv("VEXCL_SHOW_KERNELS"))
        std::cout << source << std::endl;
#endif

    auto context = queue.getInfo<CL_QUEUE_CONTEXT>();
    auto device  = context.getInfo<CL_CONTEXT_DEVICES>();

    std::string compile_options = options + " " + get_compile_options(queue);

#ifdef VEXCL_CACHE_KERNELS
    // Get unique (hopefully) hash string for the kernel.
    std::ostringstream compiler_tag;
    compiler_tag
#if defined(_MSC_VER)
        << "MSC " << _MSC_VER
#elif defined(__clang__)
        << "Clang " << __clang_major__ << "." << __clang_minor__
#elif defined(__GNUC__)
        << "g++ " << __GNUC__ << "." << __GNUC_MINOR__
#else
        << "unknown"
#endif
        ;

    sha1_hasher sha1;
    sha1.process(source)
        .process(cl::Platform(device[0].getInfo<CL_DEVICE_PLATFORM>()).getInfo<CL_PLATFORM_NAME>())
        .process(device[0].getInfo<CL_DEVICE_NAME>())
        .process(compile_options)
        .process(compiler_tag.str())
        ;

    std::string hash = static_cast<std::string>(sha1);

    // Try to get cached program binaries:
    try {
        if (boost::optional<cl::Program> program = load_program_binaries(hash, context, device, compile_options))
            return *program;
    } catch (...) {
        // Shit happens.
        std::cerr << "Failed to load precompiled binaries" << std::endl;
    }
#endif

    // If cache is not available, just compile the sources.
    cl::Program program(context, source);

    try {
        program.build(device, (options + " " + get_compile_options(queue)).c_str());
    } catch(const cl::Error&) {
        std::cerr << source
                  << std::endl
                  << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0])
                  << std::endl;

        vex::detail::print_backtrace();
        throw;
    }

#ifdef VEXCL_CACHE_KERNELS
    // Save program binaries for future reuse:
    save_program_binaries(hash, program);
#endif

    return program;
}
Example #25
0
int main()
{
    //Opens the program
    FILE* prog = fopen("input.txt", "r");

    //Opens file for program output
    output = fopen("output.txt", "w");
    char list[2000][20];

    //Scans program and converts to lexeme list
    int lexError = scan(prog);

    fclose(prog);

    if (lexError == -1)
        return 0;

    //Opens lexeme list to be parsed
    FILE* input = fopen("lexlist.txt", "r");

    int size = 0;

    //Reads lexeme list
    while(!feof(input))
    {
        fscanf(input, "%s", list[size]);
        size++;
    }

    fprintf(output, "A print out of the token (internal representation) file:\n\n");
    int i;

    for (i = 0; i < size; i++)
        fprintf(output, "%s ", list[i]);

    fprintf(output, "\n\nAnd its symbolic representation:\n\n");

    symbolRepresent(list, size); fprintf(output, "\n\n");

    //Determines if program is syntactically correct and generates intermediate code
    int correct = program(list, size);

    if (correct)
        fprintf(output, "No errors, program is syntactically correct.\n\n");
    else
    {
        symbolRepresent(list, err);
        fprintf(output, "    ***** ");
        error(err2);
        return 0;
    }

    //Writes intermediate code to file
    generateCode();

    //Runs intermediate code on virtual machine
    makeStack();

    fclose(input);
    fclose(output);
    return 0;
}
Example #26
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
	

	SDL_Event event;
	bool done = false;
#ifdef _WINDOWS
	glewInit();
#endif

	Matrix projectionMatrix;
	Matrix modelMatrix;
	Matrix viewMatrix;

	ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");



	GLuint dogTexture = LoadTexture("dog.png");
	GLuint ballTexture = LoadTexture("ball.png");
	GLuint boneTexture = LoadTexture("bone.png");

	projectionMatrix.setOrthoProjection(-3.55, 3.55, -2.0f, 2.0f, -1.0f, 1.0f);
	glUseProgram(program.programID);

	float lastFrameTicks = 0.0f;

	double movement = 0.0;

	double ballBounce = 0.0;

	bool bounceHigh = false;

	bool firstHit = false;

	const Uint8 *keys = SDL_GetKeyboardState(NULL);

	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}
		

		glClear(GL_COLOR_BUFFER_BIT);
		program.setModelMatrix(modelMatrix);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);
		glBindTexture(GL_TEXTURE_2D, ballTexture);

		float ticks = (float)SDL_GetTicks() / 1000.0f;

		float elapsed = ticks - lastFrameTicks;
			
		lastFrameTicks = ticks;

		if (firstHit == false){
			movement = movement + elapsed;
		}

		//makes the ball bounce
		if ((ballBounce * 0.75) >= 1){
			bounceHigh = true;
		}

		if ((ballBounce * 0.75) <= -1){
			bounceHigh = false;
		}
		
		if (bounceHigh == false){
			ballBounce = ballBounce + elapsed;
		}
		else if (bounceHigh == true){
			ballBounce = ballBounce - elapsed;
		}

		
		float vertices[] = { -1.4 + (movement * 0.25), -0.4 + (ballBounce * 0.25), -0.4 + (movement * 0.25), -0.4 + (ballBounce * 0.25),
			-0.4 + (movement * 0.25), 0.4 + (ballBounce * 0.25), -1.4 + (movement * 0.25), -0.4 + (ballBounce * 0.25),
			-0.4 + (movement * 0.25), 0.4 + (ballBounce * 0.25), -1.4 + (movement * 0.25), 0.4 + (ballBounce * 0.25) };
		
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);


		if (keys[SDL_SCANCODE_A]) {
			--p1X;
		}
		else if (keys[SDL_SCANCODE_D]) {
			++p1X;
		}

		if (keys[SDL_SCANCODE_W]) {
			++p1Y;
		}
		else if (keys[SDL_SCANCODE_S]) {
			--p1Y;
		}

		glBindTexture(GL_TEXTURE_2D, dogTexture);

		float vertices2[] = { -2.5 + (p1X * 0.001), -0.5 + (p1Y * 0.001), -1.5 + (p1X * 0.001), -0.5 + (p1Y * 0.001),
			-1.5 + (p1X * 0.001), 0.5 + (p1Y * 0.001), -2.5 + (p1X * 0.001), -0.5 + (p1Y * 0.001),
			-1.5 + (p1X * 0.001), 0.5 + (p1Y * 0.001), -2.5 + (p1X * 0.001), 0.5 + (p1Y * 0.001) };


		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices2);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords2[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords2);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);


		if (keys[SDL_SCANCODE_J]) {
			--p2X;
		}
		else if (keys[SDL_SCANCODE_L]) {
			++p2X;
		}

		if (keys[SDL_SCANCODE_I]) {
			++p2Y;
		}
		else if (keys[SDL_SCANCODE_K]) {
			--p2Y;
		}

		glBindTexture(GL_TEXTURE_2D, dogTexture);

		float vertices3[] = { 1.5 + (p2X * 0.001), -0.5 + (p2Y * 0.001), 2.5 + (p2X * 0.001), -0.5 + (p2Y * 0.001),
			2.5 + (p2X * 0.001), 0.5 + (p2Y * 0.001), 1.5 + (p2X * 0.001), -0.5 + (p2Y * 0.001),
			2.5 + (p2X * 0.001), 0.5 + (p2Y * 0.001), 1.5 + (p2X * 0.001), 0.5 + (p2Y * 0.001) };

		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, vertices3);
		glEnableVertexAttribArray(program.positionAttribute);
		float texCoords3[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords3);
		glEnableVertexAttribArray(program.texCoordAttribute);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);
		SDL_GL_SwapWindow(displayWindow);

		//collision
		if ((vertices[11] <= vertices2[5] && vertices[11] >= vertices2[3])
			|| (vertices[1] <= vertices2[5] && vertices[1] >= vertices2[3])
			&& vertices[10] == vertices2[4])
		{
			firstHit = true;
			movement = movement + elapsed;
		}
		else if ((vertices[5] <= vertices3[11] && vertices[5] >= vertices3[1])
			|| (vertices[3] <= vertices3[11] && vertices[3] >= vertices3[1])
			&& vertices[4] == vertices3[10])
		{
			firstHit = true;
			movement = movement - elapsed;
		}

		if (vertices[10] <= vertices2[4])
		{
			std::cout << "Player 2 Wins" << std::endl;
		}

		else if (vertices[4] >= vertices3[10])
		{
			std::cout << "Player 1 Wins" << std::endl;
		}
	}

	SDL_Quit();
	return 0;
}
Example #27
0
ProgramPtr Parser::parseProgram()
{
    if (!match(TokenType::Program)) {
        reportError(ErrorCodes::ExpectedProgram);

        panic(programFollow, programFollowSize);
        return ProgramPtr();
    }

    IdentifierPtr programName = parseIdentifier();
    if (m_errorCode > ErrorCodes::NoError) {
        panic(programFollow, programFollowSize);
        return ProgramPtr();
    }

    if (!match(TokenType::LParen)) {
        reportError(ErrorCodes::ExpectedLParen);

        panic(programFollow, programFollowSize);
        return ProgramPtr();
    }

    IdentifiersPtr inputOutput = parseIdentifierList();
    if (m_errorCode > ErrorCodes::NoError) {
        panic(programFollow, programFollowSize);
        return ProgramPtr();
    }

    if (!match(TokenType::RParen)) {
        reportError(ErrorCodes::ExpectedRParen);

        panic(programFollow, programFollowSize);
        return ProgramPtr();
    }

    if (!match(TokenType::Semicolon)) {
        reportError(ErrorCodes::ExpectedSemicolon);

        panic(programFollow, programFollowSize);
        return ProgramPtr();
    }

    DeclarationsPtr globalVariables = parseDeclarations();
    if (m_errorCode > ErrorCodes::NoError) {
        panic(programFollow, programFollowSize);
        return ProgramPtr();
    }

    SubprogramDeclarationsPtr functions = parseSubprogramDeclarations();
    if (m_errorCode > ErrorCodes::NoError) {
        panic(programFollow, programFollowSize);
        return ProgramPtr();
    }

    CompoundStatementPtr mainProgram = parseCompoundStatement();
    if (m_errorCode > ErrorCodes::NoError) {
        panic(programFollow, programFollowSize);
        return ProgramPtr();
    }

    if (!match(TokenType::Period)) {
        reportError(ErrorCodes::ExpectedPeriod);

        panic(programFollow, programFollowSize);
        return ProgramPtr();
    }

    ProgramPtr program(new Program);
    program->programName = programName;
    program->inputOutput = inputOutput;
    program->variables = globalVariables;
    program->functions = functions;
    program->mainProgram = mainProgram;

    return program;
}
void opengl_compile_shader_actual(shader_type sdr, const uint &flags, opengl_shader_t &new_shader)
{
	opengl_shader_type_t *sdr_info = &GL_shader_types[sdr];

	Assert(sdr_info->type_id == sdr);
	mprintf(("Compiling new shader:\n"));
	mprintf(("	%s\n", sdr_info->description));

	// figure out if the variant requested needs a geometry shader
	bool use_geo_sdr = false;

	// do we even have a geometry shader?
	if (sdr_info->geo != NULL) {
		for (int i = 0; i < GL_num_shader_variants; ++i) {
			opengl_shader_variant_t *variant = &GL_shader_variants[i];

			if (variant->type_id == sdr && flags & variant->flag && variant->use_geometry_sdr) {
				use_geo_sdr = true;
				break;
			}
		}
	}

	auto vert_content = opengl_get_shader_content(sdr_info->type_id, sdr_info->vert, flags, use_geo_sdr);
	auto frag_content = opengl_get_shader_content(sdr_info->type_id, sdr_info->frag, flags, use_geo_sdr);
	SCP_vector<SCP_string> geom_content;

	if (use_geo_sdr) {
		// read geometry shader
		geom_content = opengl_get_shader_content(sdr_info->type_id, sdr_info->geo, flags, use_geo_sdr);
	}

	auto shader_hash = get_shader_hash(vert_content, geom_content, frag_content);
	std::unique_ptr<opengl::ShaderProgram> program(new opengl::ShaderProgram(sdr_info->description));

	if (!load_cached_shader_binary(program.get(), shader_hash)) {
		GR_DEBUG_SCOPE("Compiling shader code");
		try {
			program->addShaderCode(opengl::STAGE_VERTEX, sdr_info->vert, vert_content);
			program->addShaderCode(opengl::STAGE_FRAGMENT, sdr_info->frag, frag_content);
			if (use_geo_sdr) {
				program->addShaderCode(opengl::STAGE_GEOMETRY, sdr_info->geo, geom_content);
			}

			for (size_t i = 0; i < GL_vertex_attrib_info.size(); ++i) {
				// Check that the enum values match the position in the vector to make accessing that information more efficient
				Assertion(GL_vertex_attrib_info[i].attribute_id == (int)i, "Mistmatch between enum values and attribute vector detected!");

				// assign vert attribute binding locations before we link the shader
				glBindAttribLocation(program->getShaderHandle(), (GLint)i, GL_vertex_attrib_info[i].name.c_str());
			}

			// bind fragment data locations before we link the shader
			glBindFragDataLocation(program->getShaderHandle(), 0, "fragOut0");
			glBindFragDataLocation(program->getShaderHandle(), 1, "fragOut1");
			glBindFragDataLocation(program->getShaderHandle(), 2, "fragOut2");
			glBindFragDataLocation(program->getShaderHandle(), 3, "fragOut3");
			glBindFragDataLocation(program->getShaderHandle(), 4, "fragOut4");

			if (do_shader_caching()) {
				// Enable shader caching
				glProgramParameteri(program->getShaderHandle(), GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);
			}

			program->linkProgram();
		}
		catch (const std::exception&) {
			// Since all shaders are required a compilation failure is a fatal error
			Error(LOCATION, "A shader failed to compile! Check the debug log for more information.");
		}

		cache_program_binary(program->getShaderHandle(), shader_hash);
	}

	new_shader.shader = sdr_info->type_id;
	new_shader.flags = flags;
	new_shader.program = std::move(program);

	opengl_shader_set_current(&new_shader);

	// initialize the attributes
	for (auto& attr : sdr_info->attributes) {
		new_shader.program->initAttribute(GL_vertex_attrib_info[attr].name, GL_vertex_attrib_info[attr].attribute_id, GL_vertex_attrib_info[attr].default_value);
	}

	for (auto& uniform_block : GL_uniform_blocks) {
		auto blockIndex = glGetUniformBlockIndex(new_shader.program->getShaderHandle(), uniform_block.name);

		if (blockIndex != GL_INVALID_INDEX) {
			glUniformBlockBinding(new_shader.program->getShaderHandle(), blockIndex, static_cast<GLuint>(uniform_block.block_type));
		}
	}

	mprintf(("Shader Variant Features:\n"));

	// initialize all uniforms and attributes that are specific to this variant
	for (int i = 0; i < GL_num_shader_variants; ++i) {
		opengl_shader_variant_t &variant = GL_shader_variants[i];

		if (sdr_info->type_id == variant.type_id && variant.flag & flags) {
			for (auto& attr : variant.attributes) {
				auto& attr_info = GL_vertex_attrib_info[attr];
				new_shader.program->initAttribute(attr_info.name, attr_info.attribute_id, attr_info.default_value);
			}

			mprintf(("	%s\n", variant.description));
		}
	}

	opengl_set_default_uniforms(new_shader);
}
Example #29
0
int main(int argc, char *argv[])
{
	SDL_Init(SDL_INIT_VIDEO);
	displayWindow = SDL_CreateWindow("My Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 360, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(displayWindow);
	SDL_GL_MakeCurrent(displayWindow, context);
	#ifdef _WINDOWS
		glewInit();
	#endif

	SDL_Event event;
	bool done = false;

	ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");
	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
	GLuint blank = LoadTexture("blank.png");

	Matrix projectionMatrix;
	Matrix modelMatrix;
	Matrix viewMatrix;
	projectionMatrix.setOrthoProjection(-1.7777f, 1.7777f, -1.0f, 1.0f, -1.0f, 1.0f);
	float portWidth = 640;
	float portHeight = 320;

	float lastFrameTicks = 0.0f;
	float ballPosx = .0f;
	float ballPosy = 0.0f;
	float ballAngle = 180.0f;
	float ballSpeed = 2.0f;
	float paddlePos1 = 0.0f;
	float paddlePos2 = 0.0f;
	float paddleSpeed = 0.0015f;
	float server = 0.0f;


	while (!done) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT || event.type == SDL_WINDOWEVENT_CLOSE) {
				done = true;
			}
		}
		const Uint8 *keys = SDL_GetKeyboardState(NULL); 
//player1 input
		if (keys[SDL_SCANCODE_W]){
			paddlePos1 += paddleSpeed;
			if (paddlePos1 + 0.2 >= 1)
				paddlePos1 = 1 - 0.2;
		}
		else if (keys[SDL_SCANCODE_S]){
			paddlePos1 += -1 * paddleSpeed;
			if (paddlePos1 - 0.2 <= -1)
			paddlePos1 = -1 + 0.2;
		}
		
//player2 input		
		if (keys[SDL_SCANCODE_O]){
			paddlePos2 += paddleSpeed;
			if (paddlePos2 + 0.2 >= 1)
				paddlePos2 = 1 - 0.2;
		}
		else if (keys[SDL_SCANCODE_L]){
			paddlePos2 += -1 * paddleSpeed;
			if (paddlePos2 - 0.2 <= -1)
				paddlePos2 = -1 + 0.2;
		}

//update
		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;

		if (abs(ballAngle) - 90 <= 20 && abs(ballAngle) -90 >= -20)
			ballSpeed = 4;
		else
			ballSpeed = 2;

		float dist = elapsed*ballSpeed;
		ballPosx += cos(ballAngle * PI / 180)*dist;
		ballPosy += sin(ballAngle * PI / 180)*dist;		



//collison test
		if (ballPosy >= 1){
			ballAngle = -1 * ballAngle;
			ballPosy = 1;
		}
		else if (ballPosy <= -1){
			ballAngle = -1 * ballAngle;
			ballPosy = -1;
		}

		if (ballPosx <= -1.5 && ballPosx >= -1.6 && ballPosy <= paddlePos1 + 0.2 && ballPosy >= paddlePos1 - 0.2){
			if (ballPosy > paddlePos1 + 0.1 || ballPosy < paddlePos1 - 0.1){
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle + 20;
				else
					ballAngle = -180 - ballAngle - 20;
			}
			else if (ballPosy > paddlePos1 + 0.175 || ballPosy < paddlePos1 - 0.175){
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle + 15;
				else
					ballAngle = -180 - ballAngle - 15;
			}
			else {
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle;
				else
					ballAngle = -180 - ballAngle;
			}
			ballPosx = -1.5;
		}
		else if (ballPosx >= 1.5 && ballPosx <= 1.6 && ballPosy <= paddlePos2 + 0.2 && ballPosy >= paddlePos2 - 0.2){
			if (ballPosy > paddlePos2 + 0.1 || ballPosy < paddlePos2 - 0.1){
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle - 20;
				else
					ballAngle = -180 - ballAngle + 20;
			}
			else if (ballPosy > paddlePos2 + 0.175 || ballPosy < paddlePos2 - 0.175){
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle - 15;
				else
					ballAngle = -180 - ballAngle + 15;
			}
			else {
				if (ballAngle > 0)
					ballAngle = 180 - ballAngle;
				else
					ballAngle = -180 - ballAngle;
			}
			ballPosx = 1.5;
		}

//victory condition test
		if (ballPosx <= -1.8){
			ballPosx = 0;
			ballPosy = 0;
			ballAngle = 0;
			paddlePos1 = 0;
			paddlePos2 = 0;
			server = 1;
		}
		else if (ballPosx >= 1.8){
			ballPosx = 0;
			ballPosy = 0;
			ballAngle = 180;
			paddlePos1 = 0;
			paddlePos2 = 0;
			server = -1;
		}


//render
		glViewport(0, 0, portWidth, portHeight);
		float verticesBall[] = { -0.03f, -0.03f, 
								0.03f, 0.03f, 
								-0.03f, 0.03f, 
								0.03f, 0.03f, 
								-0.03f, -0.03f, 
								0.03f, -0.03f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, verticesBall);
		glEnableVertexAttribArray(program.positionAttribute);

		float texCoordsBall[] = { 0.0, 1.0f, 
								1.0f, 0.0f, 
								0.0f, 0.0f, 
								1.0, 0.0, 
								0.0, 1.0, 
								1.0, 1.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoordsBall);
		glEnableVertexAttribArray(program.texCoordAttribute);

		glBindTexture(GL_TEXTURE_2D, blank);

		modelMatrix.identity();
		modelMatrix.Translate(ballPosx,ballPosy,0.0);
		program.setModelMatrix(modelMatrix);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);

		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		float verticesPad1[] = { -0.1f, -0.2f,
			0.0f, 0.2f,
			-0.1f, 0.2f,
			0.0f, 0.2f,
			-0.1f, -0.2f,
			0.0f, -0.2f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, verticesPad1);
		glEnableVertexAttribArray(program.positionAttribute);

		float texCoordsPad1[] = { 0.0, 1.0f,
			1.0f, 0.0f,
			0.0f, 0.0f,
			1.0, 0.0,
			0.0, 1.0,
			1.0, 1.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoordsPad1);
		glEnableVertexAttribArray(program.texCoordAttribute);


		modelMatrix.identity();
		modelMatrix.Translate(-1.5, paddlePos1, 0.0);
		program.setModelMatrix(modelMatrix);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);

		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		float verticesPad2[] = { 0.1f, -0.2f,
			0.0f, 0.2f,
			0.1f, 0.2f,
			0.0f, 0.2f,
			0.1f, -0.2f,
			0.0f, -0.2f };
		glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, verticesPad2);
		glEnableVertexAttribArray(program.positionAttribute);

		float texCoordsPad2[] = { 0.0, 1.0f,
			1.0f, 0.0f,
			0.0f, 0.0f,
			1.0, 0.0,
			0.0, 1.0,
			1.0, 1.0 };
		glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoordsPad2);
		glEnableVertexAttribArray(program.texCoordAttribute);
		

		modelMatrix.identity();
		modelMatrix.Translate(1.5, paddlePos2, 0.0);
		program.setModelMatrix(modelMatrix);
		program.setProjectionMatrix(projectionMatrix);
		program.setViewMatrix(viewMatrix);

		glDrawArrays(GL_TRIANGLES, 0, 6);
		glDisableVertexAttribArray(program.positionAttribute);
		glDisableVertexAttribArray(program.texCoordAttribute);

		if (server){
			float verticesfl[] = { -0.025f, 0.0f,
				0.025f, 0.1f,
				-0.025f, 0.1f,
				0.025f, 0.1f,
				-0.025f, 0.0f,
				0.0f, 0.0f };
			glVertexAttribPointer(program.positionAttribute, 2, GL_FLOAT, false, 0, verticesfl);
			glEnableVertexAttribArray(program.positionAttribute);

			float texCoordsfl[] = { 0.0, 1.0f,
				1.0f, 0.0f,
				0.0f, 0.0f,
				1.0, 0.0,
				0.0, 1.0,
				1.0, 1.0 };
			glVertexAttribPointer(program.texCoordAttribute, 2, GL_FLOAT, false, 0, texCoordsfl);
			glEnableVertexAttribArray(program.texCoordAttribute);


			modelMatrix.identity();
			modelMatrix.Translate(server, -1, 0.0);
			program.setModelMatrix(modelMatrix);
			program.setProjectionMatrix(projectionMatrix);
			program.setViewMatrix(viewMatrix);

			glDrawArrays(GL_TRIANGLES, 0, 6);
			glDisableVertexAttribArray(program.positionAttribute);
			glDisableVertexAttribArray(program.texCoordAttribute);
		}

		SDL_GL_SwapWindow(displayWindow);
		glClear(GL_COLOR_BUFFER_BIT);

	}


	/*Game app;
	while (!app.UpdateAndRender()) {}*/

	//SDL_Quit();
	return 0;
}
Example #30
0
#include "c.h"

static char rcsid[] = "$Name: v4_2 $($Id: main.c,v 1.1 2002/08/28 23:12:44 drh Exp $)";

static void typestab(Symbol, void *);

static void stabline(Coordinate *);
static void stabend(Coordinate *, Symbol, Coordinate **, Symbol *, Symbol *);
Interface *IR = NULL;

int Aflag;		/* >= 0 if -A specified */
int Pflag;		/* != 0 if -P specified */
int glevel;		/* == [0-9] if -g[0-9] specified */
int xref;		/* != 0 for cross-reference data */
Symbol YYnull;		/* _YYnull  symbol if -n or -nvalidate specified */
Symbol YYcheck;		/* _YYcheck symbol if -nvalidate,check specified */

static char *comment;
static Interface stabIR;
static char *currentfile;       /* current file name */
static int currentline;		/* current line number */
static FILE *srcfp;		/* stream for current file, if non-NULL */
static int srcpos;		/* position of srcfp, if srcfp is non-NULL */
int main(int argc, char *argv[]) {
	int i, j;
	for (i = argc - 1; i > 0; i--)
		if (strncmp(argv[i], "-target=", 8) == 0)
			break;
	if (i > 0) {
		char *s = strchr(argv[i], '\\');
		if (s != NULL)
			*s = '/';
		for (j = 0; bindings[j].name && bindings[j].ir; j++)
			if (strcmp(&argv[i][8], bindings[j].name) == 0) {
				IR = bindings[j].ir;
				break;
			}
		if (s != NULL)
			*s = '\\';
	}
	if (!IR) {
		fprint(stderr, "%s: unknown target", argv[0]);
		if (i > 0)
			fprint(stderr, " `%s'", &argv[i][8]);
		fprint(stderr, "; must specify one of\n");
		for (i = 0; bindings[i].name; i++)
			fprint(stderr, "\t-target=%s\n", bindings[i].name);
		exit(EXIT_FAILURE);
	}
	init(argc, argv);
	t = gettok();
	(*IR->progbeg)(argc, argv);
	for (i = 1; i < argc; i++)
		if (strcmp(argv[i], "-n") == 0) {
			if (!YYnull) {
				YYnull = install(string("_YYnull"), &globals, GLOBAL, PERM);
				YYnull->type = func(voidptype, NULL, 1);
				YYnull->sclass = EXTERN;
				(*IR->defsymbol)(YYnull);
			}
		} else if (strncmp(argv[i], "-n", 2) == 0) {	/* -nvalid[,check] */
			char *p = strchr(argv[i], ',');
			if (p) {
				YYcheck = install(string(p+1), &globals, GLOBAL, PERM);
				YYcheck->type = func(voidptype, NULL, 1);
				YYcheck->sclass = EXTERN;
				(*IR->defsymbol)(YYcheck);
				p = stringn(argv[i]+2, p - (argv[i]+2));
			} else
				p = string(argv[i]+2);
			YYnull = install(p, &globals, GLOBAL, PERM);
			YYnull->type = func(voidptype, NULL, 1);
			YYnull->sclass = EXTERN;
			(*IR->defsymbol)(YYnull);
		} else {
			profInit(argv[i]);
			traceInit(argv[i]);
		}
	if (glevel && IR->stabinit)
		(*IR->stabinit)(firstfile, argc, argv);
	program();
	if (events.end)
		apply(events.end, NULL, NULL);
	memset(&events, 0, sizeof events);
	if (glevel || xref) {
		Symbol symroot = NULL;
		Coordinate src;
		foreach(types,       GLOBAL, typestab, &symroot);
		foreach(identifiers, GLOBAL, typestab, &symroot);
		src.file = firstfile;
		src.x = 0;
		src.y = lineno;
		if ((glevel > 2 || xref) && IR->stabend)
			(*IR->stabend)(&src, symroot,
				ltov(&loci,    PERM),
				ltov(&symbols, PERM), NULL);
		else if (IR->stabend)
			(*IR->stabend)(&src, NULL, NULL, NULL, NULL);
	}
	finalize();
	(*IR->progend)();
	deallocate(PERM);
	return errcnt > 0;
}