예제 #1
0
void Player::init(int _id) {
	char texture[64];

	angle = PI;
	power = 1.0;
	fire = false;
	id = _id;
	dead = 0;
	da = 0;
	full_shield = false;

	shield_angle = PI;

	velocity = vector_t(0.0f,0.0f);

	current_base_texture = TEXTURE_BASE;


	//Load textures:
	vector_t size = vector_t(PLAYER_W, PLAYER_H);

	shield = new Texture("gfx/shield.png",1); 

	//Base
	sprintf(texture,"gfx/player%i/base.png", id+1);
	textures[TEXTURE_BASE] = RenderObject(texture, 1, 25, size);

	//Dash
	sprintf(texture,"gfx/dash.png");
	textures[TEXTURE_DASH] = RenderObject(texture, 1, 25, size);

	//Fwd
	sprintf(texture,"gfx/fwd.png");
	textures[TEXTURE_FWD] = RenderObject(texture, 1, 25, size);

	//Left
	sprintf(texture,"gfx/left.png");
	textures[TEXTURE_LEFT] = RenderObject(texture, 1, 25, size);

	//Right
	sprintf(texture,"gfx/right.png");
	textures[TEXTURE_RIGHT] = RenderObject(texture, 1, 25, size);


	//Tail
	sprintf(texture,"gfx/tail.png");
	textures[TEXTURE_TAIL] = RenderObject(texture, 9, 25, size);

	//Dispencer
	sprintf(texture,"gfx/dispencer.png");
	textures[TEXTURE_DISPENCER] = RenderObject(texture, 6, 25, size);
	
}
예제 #2
0
void render_init(int w, int h, bool fullscreen) {

    msg="Loading...";

    /* create window */
    SDL_Init(SDL_INIT_VIDEO);
    int flags = SDL_OPENGL | SDL_DOUBLEBUF;
    if ( fullscreen ) flags |= SDL_FULLSCREEN;
    SDL_SetVideoMode(w, h, 0, flags);
    SDL_WM_SetCaption("OMGSPACEPONIES!","OMGSPACEPONIES!");

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();


    /* orthographic projection */
    glOrtho(0, w, 0, h, -1.0, 1.0);
    glScalef(1, -1, 1);
    glTranslated(0, -h, 0);

    window.w = w;
    window.h = h;

    /* setup opengl */
    glClearColor(1,1,0,0);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_BLEND);
    glEnable(GL_LINE_SMOOTH);
    glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
    glShadeModel(GL_FLAT);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    /* load textures */
    splash = RenderObject("gfx/splash.png", 1, 0,vector_t(1024,768));
    backdrop = RenderObject("gfx/space.jpg", 1, 0,vector_t(1600,1200));
    box = RenderObject("gfx/box.png", 1, 0,vector_t(64,64));

    /* load fonts */
    nick_font = new FTTextureFont("fonts/nick.ttf");
    nick_font->FaceSize(NICK_FONT_SIZE);
    announcement_font = new FTTextureFont("fonts/announcement.ttf");
    announcement_font->FaceSize(ANNOUNCEMENT_FONT_SIZE);
    console_font= new FTTextureFont("fonts/console.ttf");
    console_font->FaceSize(CONSOLE_LOG_FONT_SIZE);
    misc_font = new FTTextureFont("fonts/misc.ttf");
    misc_font->FaceSize(12.0f);
}
예제 #3
0
 bool init()
 {
     V_ = FromEigen(v);
     dd_ErrorType error = dd_NoError;
     /*dd_rowset redset,impl_linset;
     dd_rowindex newpos;
     dd_MatrixCanonicalize(&V_, &impl_linset, &redset, &newpos, &error);
     if(error != dd_NoError)
     {
         std::cout << ("can not reduce matrix") << std::endl;
     }
     fprintf(stdout, "\nRedundant rows: ");
     set_fwrite(stdout, redset);
     fprintf(stdout, "\n");
     set_free(redset);
     set_free(impl_linset);
     free(newpos);
     error = dd_NoError;*/
     H_= dd_DDMatrix2Poly(V_, &error);
     if(error != dd_NoError)
     {
         if(dd_debug)
             std::cout << ("numerical instability in cddlib. ill formed polytope") << std::endl;
     }
     else
     {
         init_= true;
         b_A = dd_CopyInequalities(H_);
         // get equalities and add them as complementary inequality constraints
         long elem;
         std::vector<long> eq_rows;
         for(elem=1;elem<=(long)(b_A->linset[0]);++elem)
         {
             if (set_member(elem,b_A->linset))
                eq_rows.push_back(elem);
         }
         int rowsize = (int)b_A->rowsize;
         A = matrix_t (rowsize + eq_rows.size(), (int)b_A->colsize-1);
         b = vector_t (rowsize + eq_rows.size());
         for(int i=0; i < rowsize; ++i)
         {
             b(i) = (value_type)(*(b_A->matrix[i][0]));
             for(int j=1; j < b_A->colsize; ++j)
             {
                 A(i, j-1) = -(value_type)(*(b_A->matrix[i][j]));
             }
         }
         int i = 0;
         for(std::vector<long int>::const_iterator cit = eq_rows.begin();
             cit != eq_rows.end(); ++cit, ++i)
         {
             b(rowsize + i) = -b((int)(*cit));
             A(rowsize + i) = -A((int)(*cit));
         }
     }
     return init_;
 }
예제 #4
0
void render_splash() {
    glClear(GL_COLOR_BUFFER_BIT);
    splash.render(0);

    misc_font->FaceSize(25.0f);
    render_text(msg.c_str(), misc_font, vector_t(2.0f,window.h-2.0f));

    SDL_GL_SwapBuffers();
}
예제 #5
0
//----------------------------------------------------------------------------
void robot_t::move_palets()
{
  vector_t C;
  vector_t F;
  double d;
  double v=(33./6.)*((double)tension_courroie)*(tension/12)*M_PI*0.022;
  double modif;
  object_t *clamp = ((union_obj_t*)objects[3])->objects[1];  
  palet_t *palet;
  vector< palet_t* > palets_in;
  palets_in.clear();
  
  for(unsigned int i=0;i<simul_info->palets.size();i++)
  {
    palet=((palet_t*)simul_info->palets[i]);
    if(palet->z-palet->hauteur/2. != 0.) continue;    
    C=(palet->position-position).rotate_spec(cosinus,-sinus)+G_init;
    if(C.y>-0.04 && C.y<0.04 && C.x<dimX/2. && C.x>(dimX/2.-longueur_recept))
    {
      palets_in.resize(palets_in.size()+1);
      palets_in[palets_in.size()-1] = palet;
    }
  }
    
  modif=(v<0?0.05 + 0.07*(palets_in.size()-1):0.);
  if(clamp->type==OBJ_PINCE_FERMEE && clamp->z-clamp->hauteur/2.-clamp_minZ<0.03)
    modif += 0.07;
    
  for(unsigned int i=0;i<palets_in.size();i++)
  {
    C=(palets_in[i]->position-position).rotate_spec(cosinus,-sinus)+G_init;
    if(C.y>-0.04 && C.y<0.04 && C.x<dimX/2. && C.x>(dimX/2.-longueur_recept+modif))
    {
    /*  s=((2.*(speed|N)+v)/2.-(palets_in[i]->speed|N))*palets_in[i]->masse/simul_info->dt;
      d=(v/(2.*palets_in[i]->rayon)+palets_in[i]->omega)*palets_in[i]->J/(palets_in[i]->rayon*simul_info->dt);
      C=T*palets_in[i]->rayon;
      F=N*(s+d)/2.;
      palets_in[i]->add_force(C,F);
      C=C+palets_in[i]->position-position;
      F=-F;
      add_force(C,F);           
      C=-T*palets_in[i]->rayon;
      F=N*(s-d)/2.;
      palets_in[i]->add_force(C,F);
      C=C+palets_in[i]->position-position;
      F=-F;
      add_force(C,F);  */  
      d = (speed|N) + v - (palets_in[i]->speed|N);
      C = vector_t(0., 0.);
      F = N * (d * palets_in[i]->masse/simul_info->dt);
      palets_in[i]->add_force(C,F);       
      F = -F;
      add_force(C,F);      
    }
  }
}
예제 #6
0
matrix vector(double x0, double x1, int n) {

    matrix v;

    v=vector_t(x0, x1, n);
    v.nc=v.nf;
    v.nf=1;

    return v;
}
예제 #7
0
 void config_t::global_to_relative( const config_t& root_config )
 {
     //Have an identity temporary orientaiton
     util::quaternion_t tmp_orient;
     tmp_orient.zero();
     //Then, set our position to be the relative position
     this->set_position( this->get_position() - root_config.get_position() );
     tmp_orient /= root_config.get_orientation();
     this->set_position(vector_t(tmp_orient.qv_rotation(this->get_position())));
     tmp_orient *= this->get_orientation();
     tmp_orient.normalize();
     PRX_ASSERT(tmp_orient.is_valid());
     this->set_orientation(tmp_orient);
 }
gboolean WnCourt::on_motion_notify_event_callback(GtkWidget * widget, GdkEventMotion * event , WnCourt *wncourt)
{
	if (event->state & GDK_BUTTON1_MASK) {
		if (wncourt->dragball) {
			vector_t dv((single)(event->x - wncourt->oldX), (single)(event->y - wncourt->oldY), 0);
			wncourt->dragball->getP().getP().add(dv);
			if (wncourt->overball) {
				wncourt->overball->set_highlight(false);
				wncourt->overball = NULL;
			}
		} else if (wncourt->resizing) {
			wncourt->widget_width = (gint)event->x;
			wncourt->widget_height = (gint)event->y;
			if (wncourt->widget_width < 20)
				wncourt->widget_width = 20;
			if (wncourt->widget_height < 20)
				wncourt->widget_height = 20;
			wncourt->CenterScene();
			gtk_widget_set_size_request (wncourt->drawing_area, wncourt->widget_width, wncourt->widget_height);
		} else if (wncourt->panning) {
			wncourt->_court->get_scene().pan(vector_t((single)(event->x - wncourt->oldX), (single)(event->y - wncourt->oldY), 0));
		}
		wncourt->oldX = (int)(event->x);
		wncourt->oldY = (int)(event->y);
	} else {
		wnobj * b;
		if (wncourt->_court->hit((int)event->x, (int)event->y, &b)) {
			if (wncourt->overball != b) {
				wncourt->overball = b;
				wncourt->overball->set_anchor(true);
				wncourt->overball->set_highlight(true);
				gtk_widget_queue_draw(wncourt->drawing_area);
				if (wncourt->overball->getT() & wnobj::et_ball) {
					ball_t *ball = static_cast<ball_t *>(wncourt->overball);
					char *text = g_markup_printf_escaped("<i>%s</i>\n%s", ball->get_type_str(), ball->get_text());
					wncourt->ShowPangoTips(wncourt->CurrentWord.c_str(), text);
					g_free(text);
				}
			}
		} else {
			if (wncourt->overball) {
				wncourt->overball->set_anchor(false);
				wncourt->overball->set_highlight(false);
				wncourt->overball = NULL;
			}
		}
	}
	return TRUE;
}
예제 #9
0
		// ProjectiveCamera Public Methods
		ProjectiveCamera(const transform_t &world2cam,
			const transform_t &proj, const scalar_t Screen[4],
			scalar_t hither, scalar_t yon,
			scalar_t sopen, scalar_t sclose,
			scalar_t lensr, scalar_t focald, film_ptr film)
			: parent_type(world2cam, hither, yon, sopen, sclose, film) {
				// Initialize depth of field parameters
				LensRadius = lensr;
				FocalDistance = focald;
				// Compute projective camera transformations
				CameraToScreen = proj;
				WorldToScreen = CameraToScreen * world2cam;
				// Compute projective camera screen transformations
				ScreenToRaster.identity();

				ScreenToRaster.scale(vector_t((scalar_t)film->xResolution(),scalar_t(film->yResolution()), 1.f)).scale
					(vector_t(1.f / (Screen[1] - Screen[0]),1.f / (Screen[2] - Screen[3]), 1.f)).translate
					(vector_t(-Screen[0], -Screen[3], 0.f));

				RasterToScreen = ScreenToRaster.inverse();
				transform_t tmp = CameraToScreen.inverse();
				RasterToCamera =
					CameraToScreen.inverse() * RasterToScreen;
		}
        void quaternion_t::interpolate( const quaternion_t& target, double f )
        {
            // TODO: don't use vector_t in this function.
            vector_t qv = vector_t(q[0],q[1],q[2],q[3]);

            vector_t other(target.q[0], target.q[1], target.q[2], target.q[3]);
            double lambda = qv.dot_product( other );
            double r, s;

            // fix the opposite
            if (lambda < 0.0)
            {
                other = -other;
                lambda *= -1.0;
            }
            // Calculate the interpolation factors
            // -> Linear
            if ( fabs(1-lambda) < 0.001)
            {
                r = 1 - f;
                s = f;
            }
            // -> Spherical linear
            else
            {
                double alpha = acos(lambda);
                double gamma = 1.0 / sin(alpha);
                r = sin((1.0-f)*alpha) * gamma;
                s = sin(f*alpha) * gamma;
            }
            // Set interpolated quaternion
            qv *= r;
            qv += other*s;
            qv.normalize();

            q[0] = qv[0];
            q[1] = qv[1];
            q[2] = qv[2];
            q[3] = qv[3];
        }
예제 #11
0
vector_t EigenUtil::ToVectorT(const vector_eig &mat) {
  return vector_t(mat.data(), mat.data() + mat.size());
}
 vector_t quaternion_t::get_the_vector()
 {
     return vector_t(q[0],q[1],q[2]);
 }
예제 #13
0
vector_t WnCourt::get_center_pos()
{
	return vector_t(widget_width/2, widget_height/2, 0);
}
예제 #14
0
void WnCourt::CenterScene()
{
	if (!_court->get_scene().get_center())
		return;
	_court->get_scene().center_to(vector_t(widget_width/2, widget_height/2, 0));
}
예제 #15
0
		edge_item get_start()
		{
			return edge_item( (std::numeric_limits<std::size_t>::max)(), m_start, vector_t(constants::infinity<coordinate_type>(), constants::zero<coordinate_type>() ), vector<coordinate_type,2>(constants::negative_infinity<coordinate_type>(), constants::zero<coordinate_type>() ) );
		}
예제 #16
0
파일: sdl.cpp 프로젝트: AdamdbUT/mac-gyver
//------------------------------------------------------------------------------
void SDL_Draw_Robot()
{
  vector_t N,T,u,v;
  point_t point[4];

  position_t pos,dest;
  
  while(true)
  {
    Draw_SDL_Background();  
    // Draw
    pos = cine_get_position();
    dest = pp_get_dest();

    // Robot supposé
    N.x=cos(pos.a);
    N.y=sin(pos.a);
    T.x=-sin(pos.a);
    T.y=cos(pos.a);
    v=vector_t(_ROUE_X,0.).rotate(pos.a);
    point[0].x=((int)((pos.x+N.x*_LONGUEUR_ROBOT/2.+T.x*_LARGEUR_ROBOT/2.-v.x)*_SCALE_SDL));     
    point[0].y=((int)((pos.y+N.y*_LONGUEUR_ROBOT/2.+T.y*_LARGEUR_ROBOT/2.-v.y)*_SCALE_SDL));
    point[1].x=((int)((pos.x+N.x*_LONGUEUR_ROBOT/2.-T.x*_LARGEUR_ROBOT/2.-v.x)*_SCALE_SDL));
    point[1].y=((int)((pos.y+N.y*_LONGUEUR_ROBOT/2.-T.y*_LARGEUR_ROBOT/2.-v.y)*_SCALE_SDL));
    point[2].x=((int)((pos.x-N.x*_LONGUEUR_ROBOT/2.-T.x*_LARGEUR_ROBOT/2.-v.x)*_SCALE_SDL));
    point[2].y=((int)((pos.y-N.y*_LONGUEUR_ROBOT/2.-T.y*_LARGEUR_ROBOT/2.-v.y)*_SCALE_SDL));
    point[3].x=((int)((pos.x-N.x*_LONGUEUR_ROBOT/2.+T.x*_LARGEUR_ROBOT/2.-v.x)*_SCALE_SDL));
    point[3].y=((int)((pos.y-N.y*_LONGUEUR_ROBOT/2.+T.y*_LARGEUR_ROBOT/2.-v.y)*_SCALE_SDL)); 
    PolylineSDL(point, 4, getColorSDL(clWhite));
    LigneSDL(point[2].x, point[2].y, ((int)(pos.x*_SCALE_SDL)), ((int)(pos.y*_SCALE_SDL)), getColorSDL(clWhite)); 
    LigneSDL(point[3].x, point[3].y, ((int)(pos.x*_SCALE_SDL)), ((int)(pos.y*_SCALE_SDL)), getColorSDL(clWhite));

    // Destination
    N.x=cos(dest.a);
    N.y=sin(dest.a);
    T.x=-sin(dest.a)*0.03;
    T.y=cos(dest.a)*0.03; 
    LigneSDL(((int)(_SCALE_SDL*dest.x)), ((int)(_SCALE_SDL*dest.y)), 
             ((int)(_SCALE_SDL*(dest.x+N.x*0.1))), ((int)(_SCALE_SDL*(dest.y+N.y*0.1))), getColorSDL(clBlack));
    LigneSDL(((int)(_SCALE_SDL*(dest.x+N.x*0.1))), ((int)(_SCALE_SDL*(dest.y+N.y*0.1))), 
             ((int)(_SCALE_SDL*(dest.x+N.x*0.07+T.x))), ((int)(_SCALE_SDL*(dest.y+N.y*0.07+T.y))), getColorSDL(clBlack));
    LigneSDL(((int)(_SCALE_SDL*(dest.x+N.x*0.1))), ((int)(_SCALE_SDL*(dest.y+N.y*0.1))), 
             ((int)(_SCALE_SDL*(dest.x+N.x*0.07-T.x))), ((int)(_SCALE_SDL*(dest.y+N.y*0.07-T.y))), getColorSDL(clBlack));    
    
    // Captors
    for(int i=0;i<4;i++)
    {
      vector_t pos = captor_get_position(i);
      Uint32 color;
      switch(captor_get_status(i))
      {
        case 0: color = getColorSDL(clBlack); break;
        case 1: color = SDL_MapRGB(affichage->format, 255, 0, 180);  break;
        case 2: color = SDL_MapRGB(affichage->format, 255, 0, 0);  break;
        case 3: color = SDL_MapRGB(affichage->format, 60, 60, 60);  break;
      }
      DisqueSDL(((int)(_SCALE_SDL*pos.x)),
                ((int)(_SCALE_SDL*pos.y)),
                ((int)(_SCALE_SDL*0.01)),color);        
    }  
    RefreshSDL();             
    usleep(40000);
  }
}
예제 #17
0
파일: reg.c 프로젝트: diegopso/opencl
int main(int argc, char *argv[])
{
    int i;
    
    int n = 5;
	int outSize = 7;
    /* A, B, C, D, E */
    float p0[n], p1[n];
    int np[n];
    float out[outSize];

    if (argc != 21) {
        fprintf(stderr, "Usage: %s M0 H0 T0 TAU A0 A1 NA B0 B1 NB "
            "C0 C1 NC D0 D1 ND E0 E1 NE INPUT\n", argv[0]);
        exit(1);
    }


    float m0 = atof(argv[1]);
    float h0 = atof(argv[2]);
    float t0 = atof(argv[3]);
    float tau = strtof(argv[4], NULL);

    /* p0 is where the search starts, p1 is where the search ends and np is the 
     * number of points in between p0 and p1 to do the search */   
    for (i = 0; i < 5; i++) {
        p0[i] = atof(argv[5 + 3*i]);
        p1[i] = atof(argv[5 + 3*i + 1]);
        np[i] = atoi(argv[5 + 3*i + 2]);
    }

    /* Load the traces from the file */

    char *path = argv[20];
    FILE *fp = fopen(path, "r");

    if (!fp) {
        fprintf(stderr, "Failed to open prestack file '%s'!\n", path);
        return 1;
    }

    su_trace_t tr;
    vector_t(su_trace_t) traces;
    vector_init(traces);

    while (su_fgettr(fp, &tr)) {
        vector_push(traces, tr);
    }

    /* Construct the aperture structure from the traces, which is a vector
     * containing pointers to traces */

    aperture_t ap;
    ap.ap_m = 0;
    ap.ap_h = 0;
    ap.ap_t = tau;
    vector_init(ap.traces);
    for (int i = 0; i < traces.len; i++)
        vector_push(ap.traces, &vector_get(traces, i));

    my_aperture_t my_ap = transform(ap);
	//puts("fim transform\n");

    /*-------------------------------------------------------------------------*/

    char *kernelSource = (char *) malloc(MAXSOURCE * sizeof(char));
    
    FILE * file = fopen("kernel.cl", "r");
    if(file == NULL) {
        printf("Error: open the kernel file (kernel.cl)\n");
        exit(1);
    }
    
    // Read kernel code
    size_t source_size = fread(kernelSource, 1, MAXSOURCE, file);
    
    //Device input buffers
    cl_mem d_my_ap;
    cl_mem d_p0, d_p1, d_np, d_aopt, d_bopt, d_copt, d_dopt, d_eopt, d_stack, d_smax;
    //Device output buffer
    cl_mem  d_out;
    
    cl_int err;

    char deviceName[MAX_DEVICE_NAME_SIZE];
    cl_platform_id cpPlatform;
    cl_device_id device_id;
    cl_context context;
    cl_command_queue queue;
    cl_program program;
    cl_kernel kernel;
    cl_platform_id *platforms;
    cl_uint platformCount;
    
    //Tamanho em bytes de cada vetor
    size_t bytes_my_ap = sizeof(my_aperture_t);
    size_t bytes_p0 = sizeof(float) * n;
    size_t bytes_p1 = sizeof(float) * n;
    size_t bytes_np = sizeof(int) * n;
    size_t bytes_opt = sizeof(float) * np[0];
	size_t bytes_out = sizeof(float) * outSize;
    

	//Numero de workitems em cada local work group (local size)
//    size_t localSize[3] = {LOCALSIZE, LOCALSIZE, LOCALSIZE};
//
//    size_t globalSize[3] = {
//        ceil((float)np[0] / (float)localSize[0]),
//        ceil((float)np[1] / (float)localSize[1]),
//        ceil((float)np[2] / (float)localSize[2])
//    };

    size_t localSize[3] = {2,2,2};

    size_t globalSize[3] = {20,20,20};
    

    // Bind to platforms
	clGetPlatformIDs(0, NULL, &platformCount);
	if (platformCount == 0) {
		printf("Error, cound not find any OpenCL platforms on the system.\n");
		exit (2);
	}
	
	platforms = (cl_platform_id*) malloc(sizeof(cl_platform_id) * platformCount);
	clGetPlatformIDs(platformCount,platforms, NULL);
	
	// Find first device that works
	err = 1;
	for (i = 0; i < platformCount && err !=CL_SUCCESS; i++) {
		// Get ID for the device (CL_DEVICE_TYPE_ALL, CL_DEVICE_TYPE_GPU, ...)
		err = clGetDeviceIDs(platforms[i], CL_DEVICE_TYPE_CPU, 1, &device_id, NULL);

	}
	
	checkError(err, "get device");

	if (err !=CL_SUCCESS) {
		printf("Error, could not find a valid device.");
		exit (3);
	}
	
	err = clGetDeviceInfo(device_id, CL_DEVICE_NAME,MAX_DEVICE_NAME_SIZE, deviceName, NULL);
	printf("Device: %s \n",deviceName);
	
	if (err !=CL_SUCCESS) {
		printf("Error, could not read the info for device.");
		exit (4);
	}
	
	// Create a context
	context = clCreateContext(0, 1, &device_id, NULL, NULL, &err);
	
	if (err !=CL_SUCCESS) {
		printf("Error, could not create the context.");
		exit (5);
	}
	
	// Create a command queue
	queue = clCreateCommandQueueWithProperties(context, device_id, 0, &err);
	
	// Create the compute program from the source buffer
	program = clCreateProgramWithSource(context, 1,
			(const char **) & kernelSource,(const size_t *) &source_size, &err);
			
	if (err !=CL_SUCCESS) {
		printf("Error, could not create program with source.");
		exit (6);
	}
			
	// Build the program executable " --disable-multilib "
	err = clBuildProgram(program, 0,NULL, NULL, NULL, NULL);
	if (err == CL_BUILD_PROGRAM_FAILURE) {
		cl_int logStatus;
		char* buildLog = NULL;
		size_t buildLogSize = 0;
		logStatus = clGetProgramBuildInfo (program, device_id, CL_PROGRAM_BUILD_LOG, buildLogSize, NULL, &buildLogSize);
		buildLog = (char*)malloc(buildLogSize);
		memset(buildLog, 0, buildLogSize);
		logStatus = clGetProgramBuildInfo (program, device_id, CL_PROGRAM_BUILD_LOG, buildLogSize, buildLog, NULL);
		printf("ERROR %d (logsz = %d): [[%s]]\n", err, buildLogSize, buildLog);
		free(buildLog);
		return err;
	} else if (err!=0) {
		printf("Error, could not build program.\n");
		exit (7);
	}
	
	// Create the compute kernel in the program we wish to run
	
	kernel = clCreateKernel(program, "calculate", &err);
	
	if (err !=CL_SUCCESS) {
		printf("Error, could not create the kernel.");
		exit (6);
	}
	

	float smax[np[0]];
	for(int i = 0; i < np[0]; i++){
		smax[i] = -1.0;
	}
	size_t bytes_smax = sizeof(float) * np[0];

	// Create the input and output arrays in device memory for our calculation
	d_my_ap = clCreateBuffer(context, CL_MEM_READ_ONLY, bytes_my_ap, NULL, NULL);
	d_p0 = clCreateBuffer(context, CL_MEM_READ_ONLY, bytes_p0, NULL, NULL);
	d_p1 = clCreateBuffer(context, CL_MEM_READ_ONLY, bytes_p1, NULL, NULL);
	d_np = clCreateBuffer(context, CL_MEM_READ_ONLY, bytes_np, NULL, NULL);
	d_out = clCreateBuffer(context, CL_MEM_WRITE_ONLY, bytes_out, NULL, NULL);

	d_aopt = clCreateBuffer(context, CL_MEM_READ_WRITE , bytes_smax, NULL, NULL);
	d_bopt = clCreateBuffer(context, CL_MEM_READ_WRITE, bytes_smax, NULL, NULL);
	d_copt = clCreateBuffer(context, CL_MEM_READ_WRITE, bytes_smax, NULL, NULL);
	d_dopt = clCreateBuffer(context, CL_MEM_READ_WRITE, bytes_smax, NULL, NULL);
	d_eopt = clCreateBuffer(context, CL_MEM_READ_WRITE, bytes_smax, NULL, NULL);
	d_stack = clCreateBuffer(context, CL_MEM_READ_WRITE, bytes_smax, NULL, NULL);
	d_smax = clCreateBuffer(context, CL_MEM_READ_ONLY, bytes_smax, NULL, NULL);

	// Write our data set into the input array in device memory

	err = clEnqueueWriteBuffer(queue, d_my_ap, CL_TRUE, 0, bytes_my_ap, (const void*)&my_ap, 0, NULL, NULL);
	err |= clEnqueueWriteBuffer(queue, d_p0, CL_TRUE, 0, bytes_p0, p0, 0, NULL, NULL);
	err |= clEnqueueWriteBuffer(queue, d_p1, CL_TRUE, 0, bytes_p1, p1, 0, NULL, NULL);
	err |= clEnqueueWriteBuffer(queue, d_np, CL_TRUE, 0, bytes_np, np, 0, NULL, NULL);
	err |= clEnqueueWriteBuffer(queue, d_smax, CL_TRUE, 0, bytes_smax, smax, 0, NULL, NULL);

	// Set the arguments to our compute kernel
	err |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &d_my_ap);
	err |= clSetKernelArg(kernel, 1, sizeof(float), &m0);
	err |= clSetKernelArg(kernel, 2, sizeof(float), &h0);
	err |= clSetKernelArg(kernel, 3, sizeof(float), &t0);
	err |= clSetKernelArg(kernel, 4, sizeof(cl_mem), &d_p0);
	err |= clSetKernelArg(kernel, 5, sizeof(cl_mem), &d_p1);
	err |= clSetKernelArg(kernel, 6, sizeof(cl_mem), &d_np);
	err |= clSetKernelArg(kernel, 7, sizeof(cl_mem), &d_out);
	err |= clSetKernelArg(kernel, 8, np[0] * sizeof(cl_float), &d_aopt);//_Aopt
	err |= clSetKernelArg(kernel, 9, np[0] * sizeof(cl_float), &d_bopt);//_Bopt
	err |= clSetKernelArg(kernel, 10, np[0] * sizeof(cl_float), &d_copt);//_Copt
	err |= clSetKernelArg(kernel, 11, np[0] * sizeof(cl_float), &d_dopt);//_Dopt
	err |= clSetKernelArg(kernel, 12, np[0] * sizeof(cl_float), &d_eopt);//_Eopt
	err |= clSetKernelArg(kernel, 13, np[0] * sizeof(cl_float), &d_stack);//_stack
	err |= clSetKernelArg(kernel, 14, np[0] * sizeof(cl_float), &d_smax);//smax
	

	
	if (err !=CL_SUCCESS) {
		printf("Error, could not set kernel args.");
		exit (7);
	}
	
	err = clEnqueueNDRangeKernel(queue, kernel, 3, NULL, (const size_t *)globalSize,  (const size_t *)localSize, 0, NULL, NULL);
	// Execute the kernel over the entire range of the data set
	
	if (err !=CL_SUCCESS) {
		printf("Error, could not enqueue commands. %d\n", err);
		exit (8);
	}
	
	// Wait for the command queue to get serviced before reading back results
	clFinish(queue);
	
	// Read the results from the device
	clEnqueueReadBuffer(queue, d_out, CL_TRUE, 0, bytes_out, out, 0, NULL, NULL );

	/*-------------------------------------------------------------------------*/

    printf("A=%g\n", out[0]);
    printf("B=%g\n", out[1]);
    printf("C=%g\n", out[2]);
    printf("D=%g\n", out[3]);
    printf("E=%g\n", out[4]);
    printf("Stack=%g\n", out[5]);
    printf("Semblance=%g\n", out[6]);
    printf("\n");

    return 0;
}
예제 #18
0
파일: stroker.hpp 프로젝트: jamboree/niji
 void degenerated_dot()
 {
     _cap(base::_outer, base::_prev_pt, vector_t(base::_r, 0), true);
     _cap(base::_outer, base::_prev_pt, vector_t(-base::_r, 0), true);
 }
예제 #19
0
double baseline_svdxx(Dataset const & dataset)
{    

	// init

	size_t const n_users = dataset.n_users; size_t const m = n_users;
	size_t const n_items = dataset.n_items; size_t const n = n_items;
	size_t const f = std::min(n_users, n_items);  //f is the svd rank. min(users, items) is full SVD	
	// size_t const f = 2; // FOR SPEED

	std::cout << "dimension = " << f << std::endl;

    double total_cossim = 0.0;
    double total_cossim_c = 0.0;
    index_t total_unignored_users = 0;

	std::vector<vector_ll_t> R; // the `index' in the sparse matrix of ratings (compressed)

	for(unsigned long long u = 0; u < n_users; u++)
		R.emplace_back(const_cast<index_t*>(dataset.ratings.index() + dataset.ratings.starts()[u]),
			nnz_row(u, dataset.ratings.starts()));
	
	index_t *ind=nullptr,*strt=nullptr,nnz;
	double *vals=nullptr;
	csr2csc(
	    dataset.ratings.dim1(),dataset.ratings.dim2(),
	    dataset.ratings.nnz(),dataset.ratings.values(),dataset.ratings.starts(),dataset.ratings.index(),
	    nnz, vals, strt, ind);

    
	std::vector<vector_ll_t> I; // the `index' in the sparse matrix of ratings transposed (compressed)
	for(unsigned long long i = 0; i < n_items; i++)
		I.emplace_back(ind + strt[i],  nnz_row(i, strt));

    delete[] strt;
    delete[] vals;
	

	constexpr double HIGH_CONFIDENCE = 40; // we make all our confidence values 40 for known items and 1 for unknown items

    std::vector</*const */ diag_t> Cu;
    std::vector</*const */ vector_t> pu;
    for(unsigned long long u = 0; u < n_users; u++)
    {
		Cu.emplace_back(diag_t(indicator_vector(n_items, R[u], HIGH_CONFIDENCE, 1))); 
		pu.emplace_back(vector_t(indicator_vector(n_items, R[u], 1, 0))); // i.e. p is the uncompressed ratings matrix and pu is the row at user u
	}  

 	std::vector</*const */ diag_t> Ci;
    std::vector</*const */ vector_t> pi;
    for(unsigned long long i = 0; i < n_items; i++)
    {
		Ci.emplace_back(diag_t(indicator_vector(n_users, I[i], 40, 1))); 
		pi.emplace_back(vector_t(indicator_vector(n_users, I[i], 1, 0))); // pi[i] is uncompressed I[i]
	}  

	//////////////


    for(unsigned long long user = 0; user < dataset.n_users; user++) 
    {
    	std::cout << "user " << user << std::endl; 
    	/*initial value of Y can't be zero! or it will make everything zero !*/ 
    	matrix_t X{m,f,0.1};  // user-factors
		matrix_t Y{n,f,0.1};  // item-factors
		std::cout << "X, Y" << std::endl << X << Y;

		{
			double lambda = 0.0005; // TODO set it to what ?

			// _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
    		// _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);

			// iterate until they stabilize, or we hit 1000 iterations
			for(long iterations = 0; iterations < 2; iterations ++)
			{	
				// std::cout << "iteration " << iterations << "/10" << std::endl;
				// std::cout << "users" << std::endl;
				// IMPL OF Collaborative Filtering for Implicit Feedback Datasets (AKA weighted-alternating least squares)
				double total_diff = 0;
				double total_diff_c = 0;
 
				auto fn =
				[lambda,f,&total_diff,&total_diff_c](matrix_t ZTZ, matrix_t Z, vector_t b, vector_ll_t ind, vector_t out_sol) 
				{
					auto left = ZTZ.clone(); 
					{
						double value = HIGH_CONFIDENCE-1; 
						sparse_diag_t spdg(vector_t{&value,Z.get_rows(),0}, ind); 
						spdg.triple_product(Z.tr_shallow(), Z, left); 
					}

					matrix_t disposable_b{b.get_len(),1}; 
					disposable_b.get_col(0).set(b); 
					auto A = left + lambda * identity(f);
					vector_t new_sol = (A).solve(disposable_b).get_col(0); // cholesky decompotion can it be of help?

					std::cout << "Ax = b" << std::endl << A << new_sol << b;
					
					{
						stack::fe_asserter dummy{};
						for(unsigned long long i = 0; i < new_sol.get_len(); i ++)
						{
							stack::fe_asserter dummy{};
							double a = new_sol[i];
							double b = out_sol[i];
							double diff = std::log(1 + std::abs(a - b));  // 1+ to be positive
							kahan_accumulate(total_diff, total_diff_c, diff);
						}
					}
					out_sol.set(new_sol);  
				};
				
				auto YTY = Y.tr_shallow() * Y; 
				for(size_t u = 0; u < n_users; u++) 
					// if(u != user) // <<<<<< IGNORE CURRENT USER (!! not enough because Y wil pick it up, have to use online SVD)
					fn(YTY, Y, Y.tr_shallow() * Cu[u] * pu[u], R[u], X[u]);
					
				std::cout << "X" << std::endl << X;

				auto XTX = X.tr_shallow() * X; 
				for(size_t i = 0; i < n_items; i++) 
					fn(XTX, X, X.tr_shallow() * Ci[i] * pi[i], I[i], Y[i]);

				std::cout << "Y" << std::endl << Y;

				std::cout << "total diff = " << total_diff << " at iteration " << iterations << std::endl;
				if(total_diff < 0.01)
					break;
			}
			// _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_OFF);
    		// _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_OFF);
        }

        matrix_t const P=X; 
        matrix_t const Q=Y; 

        unsigned long long n_user_items = nnz_row(user, dataset.ratings.starts());      
        if(0 == n_user_items)
        {
            std::cerr << "skipped" << std::endl; 
            continue;
        }
        total_unignored_users ++; 

        vector_t hint = svd_hint_from_most_similar(user, dataset.sim_dense, P, Q); 

        // // sort items according to SVD hint
        vector_ll_t reconstructed = reconstruct(hint, n_user_items); 
        vector_ll_t original_profile{n_user_items}; 
        for(unsigned long long i = 0; i < n_user_items; i++)
        	original_profile[i] = dataset.ratings.index()[dataset.ratings.starts()[user] + i];   
        kahan_accumulate(total_cossim, total_cossim_c, evaluate(reconstructed, original_profile) 
            / static_cast<double>(n_user_items));
        
        std::cout << "avg cossim so far (users = " << total_unignored_users << ") = " << 
        total_cossim / total_unignored_users << std::endl;
        
        // std::cerr << "done" << std::endl;
    }

    return total_cossim / total_unignored_users;
}
예제 #20
0
 void config_t::relative_to_global(const config_t& root_config)
 {
     set_position(vector_t(root_config.get_orientation().qv_rotation(position)));
     *this = root_config + *this;
 }
예제 #21
0
		cube_t::cube_t(float size, point_t origin): 
			primitive_t(object::kCube),
			halfSize(size/2.0f),
			planes({
				plane_t {vector_t(0, 1, 0), origin + vector_t(0, 1, 0) * halfSize},
				plane_t {vector_t(0, -1, 0), origin + vector_t(0, -1, 0) * halfSize},
				plane_t {vector_t(-1, 0, 0), origin + vector_t(-1, 0, 0) * halfSize},
				plane_t {vector_t(1, 0, 0), origin + vector_t(1, 0, 0) * halfSize},
				plane_t {vector_t(0, 0, 1), origin + vector_t(0, 0, 1) * halfSize},
				plane_t {vector_t(0, 0, -1), origin + vector_t(0, 0, -1) * halfSize}
			}) {

			// compute bounds
			const std::vector< std::vector<int> > diffs = { {-1, -1}, {-1, 1}, {1, -1}, {1, 1} };
			for (int i = 0; i < kNumFaceIds; ++i) {
				const glm::vec2 tpt = vecBound(face_id(i), planes[i].point);
				for (auto sc: diffs) {
					glm::vec2 bound = tpt + glm::vec2(sc[0] * halfSize, sc[1] * halfSize);
					bounds[i].update({ bound.x, bound.y });
				}
			}
		}
예제 #22
0
void Client::incoming_network() {
	if(data_available(_sockfd,0,0)) {
		addr_t addr;
		frame_t f = read_frame(_sockfd,_vars, &addr);
		if(ready) {
			Player * p;
			switch(f.cmd) {
				case NW_CMD_INVALID:
					fprintf(stderr, "Recived invalid package\n");
					break;
				case NW_CMD_QUIT:
					printf("Start erase\n");
					printf("Delete user %i:%s\n", _vars[0].i, players[_vars[0].i]->nick.c_str());
					players.erase(_vars[0].i);
					break;
				case NW_CMD_MOVE:
					p = players[_vars[0].i];
					//Save data to player:
					p->pos.x = _vars[1].f;
					p->pos.y = _vars[2].f;
					p->angle = _vars[3].f;
					p->current_base_texture = (texture_t)_vars[4].i;
					p->velocity.x = _vars[5].f;
					p->velocity.y = _vars[6].f;
					break;
				case NW_CMD_ROTATE:
					p = players[_vars[0].i];
					p->angle = _vars[1].f;
					break;
				case NW_CMD_FIRE:
					p = players[_vars[0].i];
					p->fire = (bool)_vars[1].c;
					break;
				case NW_CMD_SHIELD:
					p = players[_vars[0].i];
					p->shield_angle = _vars[1].f;
					p->full_shield = _vars[2].c;
					break;
				case NW_CMD_JOIN:
					p = new Player(_vars[1].str, _vars[2].i);
					p->id = _vars[0].i;
					players[p->id] = p;
					p->dead = _vars[3].c;
					p->pos.x = _vars[4].f;
					p->pos.y = _vars[5].f;
					p->angle = _vars[6].f;
					printf("Added player %i:%s\n", p->id, p->nick.c_str());
					break;
				case NW_CMD_SPAWN:
					p = players[_vars[0].i];
					printf("Spawn player %s\n", p->nick.c_str());
					p->spawn_remote(vector_t(_vars[1].f, _vars[2].f));
					break;
				case NW_CMD_POWER:
					me->power = _vars[0].f;	
					printf("Server changed our power: %f\n", me->power);
					break;
				case NW_CMD_KILL:
					{
						Player * killer = players[_vars[0].i];
						Player * killed = players[_vars[1].i];

						killed->dead = 1;
						log_message(killer->nick+" killed "+killed->nick);
						char buffer[64];
						if(killed->id == me->id) {
							queue_announcement(std::string("KILLED BY ")+killer->nick);
						} else if(killer->id == me->id && killed->team != me->team) {
							sprintf(buffer, "KILLED %s +%ip", killed->nick.c_str(), KILL_SCORE);
							queue_announcement(std::string(buffer));
						} else if(killer->id == me->id)  {
							sprintf(buffer, "TEAMKILL! %ip", TEAM_KILL_SCORE);
							queue_announcement(std::string(buffer));
						}
					}
					break;
				case NW_CMD_SCORE:
					{
						me->score = _vars[0].i;
						char buffer[128];
						sprintf(buffer,"Your score: %i", me->score);
						log_message(std::string(buffer));
					}
				case NW_CMD_ERROR:
					fprintf(stderr, "Server reported error: %s\n", _vars[0].str);
					break;
			}	
		} else {
			switch(f.cmd) {
				case NW_CMD_INVALID:
					fprintf(stderr, "Recived invalid package\n");
					break;
				case NW_CMD_ACCEPT:
					me->id=_vars[0].i;
					printf("Accepted, player id: %i\n", me->id);
					players[me->id] = me;
					ready = true;
					break;
				default:
					printf("Ignore message (cmd: %i)\n", f.cmd);
					break;
		}
	}
}
}