void set_val_sphere(t_env *env, float t, t_ray ray) { t_vector scaled; scaled = vector_scale(t, &ray.dir); OBJ.new_start = vector_add(&ray.start, &scaled); OBJ.normal = vector_sub(&OBJ.new_start, &SP_POS(OBJ.cur_sphere)); if (vector_dot(&OBJ.normal, &OBJ.normal) == 0) { env->br = 1; return ; } OBJ.normal = vector_scale(1.0f / ABSV(OBJ.normal), &OBJ.normal); OBJ.cur_mat = env->obj.mats[SPHERES[OBJ.cur_sphere].shape.material]; }
char *test_add_with_retain_policy() { vector_p vector = vector_create(sizeof(int)); vector_copy_elements(vector); int *original = test_data(1); vector_add(vector, original); int *got = (int*)vector_get(vector, 0); mu_assert(*got == 1, "expected same value"); mu_assert(got != original, "shouldn't get same data back"); vector_free(vector); return NULL; }
static void SampleFace(Vector outV, Vector xv, Vector yv, Vector zv, CosineBlurFilterContext *context, RenderFlags flags, FPMColor *colorAccum, float *weightAccum) { assert(colorAccum != NULL && weightAccum != NULL); FPMDimension size = context->size; float scaleBias = context->scaleBias; float scaleOffset = context->scaleOffset; float incr = 2.0f / size; FPMDimension x, y; for (y = 0; y < size; y++) { float fy = (float)y * incr - 1.0f; float fx = -1.0f; for (x = 0; x < size; x++, fx += incr) { Vector v = vector_add(vector_multiply_scalar(xv, fx), vector_add(vector_multiply_scalar(yv, fy), zv)); v = vector_normal(v); float weight = dot_product(v, outV); if (weight <= 0.0f) continue; FPMColor color = context->source(MakeCoordsVector(v), flags, context->sourceContext); if (!IsValidColor(color)) { continue; } float localWeight = (scaleBias + color.a * scaleOffset); color = FPMColorMultiply(color, weight * localWeight); *colorAccum = FPMColorAdd(*colorAccum, color); *weightAccum += weight; } } }
void set_val_tri(t_env *env, float t, t_ray ray) { t_vector scaled; scaled = vector_scale(t, &ray.dir); OBJ.new_start = vector_add(&ray.start, &scaled); OBJ.normal = TRI[OBJ.cur_tri].normal; if (vector_dot(&OBJ.normal, &OBJ.normal) == 0) { env->br = 1; return ; } OBJ.normal = vector_scale(1.0f / ABSV(OBJ.normal), &OBJ.normal); OBJ.cur_mat = env->obj.mats[TRI[OBJ.cur_tri].shape.material]; }
void CStaticSprite::render(Camera* camera) { Vector_ pos; go->pos(&pos); vector_add(&pos, &pos, &offset); Sprite sprite = GIGGLE->make_sprite(); sprite_fillfromentry(sprite, entry); sprite->displayX = pos.x; sprite->displayY = pos.y; sprite->originX = 0.5; sprite->originY = 0.5; sprite->angle = go->angle() + angle_offset; camera->addSprite(&camera->layers[layer], sprite); }
char *test_insert_at_beginning() { vector_p vector = vector_create(sizeof(int)); vector_add(vector, test_data(1)); int did_insert = vector_insert(vector, 0, test_data(0)); mu_assert(vector->length == 2, "should have a length of 2"); mu_assert(did_insert, "should have inserted"); mu_assert(*(int*)vector_get(vector, 0) == 0, "should have added item at start"); mu_assert(*(int*)vector_get(vector, 1) == 1, "should have moved other items"); vector_free(vector); return NULL; }
void rk (ODEFunc ode, float *xn, float *xn1, int dim, float time, float tdelt, float *scratch) { float *kv1, *kv2, *kv3, *kv4, *a, *s; kv1 = &scratch[dim * 0]; kv2 = &scratch[dim * 1]; kv3 = &scratch[dim * 2]; kv4 = &scratch[dim * 3]; a = &scratch[dim * 4]; s = &scratch[dim * 5]; k1 (ode, xn, kv1, time, tdelt); k2 (ode, xn, kv2, kv1, time, tdelt, dim, s); k3 (ode, xn, kv3, kv2, time, tdelt, dim, s); k4 (ode, xn, kv4, kv3, time, tdelt, dim, s); vector_scale (kv2, 2, kv2, dim); vector_scale (kv3, 2, kv3, dim); vector_add (kv1, kv2, a, dim); vector_add (a, kv3, a, dim); vector_add (a, kv4, a, dim); vector_scale (a, tdelt / 6.0, a, dim); vector_add (xn, a, xn1, dim); }
void calculate_forces(simulation_t* sim) { int i,j; for(i=0;i<sim->num_celestial_bodies;i++) { //Calculate forces between celestial_bodies for(j=i+1;j<sim->num_celestial_bodies;j++) { vector_t force=calculate_gravitation((object_t*)(&sim->celestial_bodies[j]),(object_t*)(&sim->celestial_bodies[i])); sim->celestial_bodies[i].base.force=vector_add(sim->celestial_bodies[i].base.force,force); sim->celestial_bodies[j].base.force=vector_subtract(sim->celestial_bodies[j].base.force,force); } } }
ENTRYPOINT void draw_jigglypuff(ModeInfo *mi) { jigglystruct *js = &jss[MI_SCREEN(mi)]; glXMakeCurrent(MI_DISPLAY(mi), MI_WINDOW(mi), *(js->glx_context)); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0,0,-10); glRotatef(js->angle, sin(js->axis), cos(js->axis), -sin(js->axis)); glTranslatef(0, 0, 5); if(!(js->button_down)) { if((js->angle += js->speed) >= 360.0f ) { js->angle -= 360.0f; } if((js->axis+=0.01f) >= 2*M_PI ) { js->axis -= 2*M_PI; } } /* Do it twice because we don't track the device's orientation. */ glRotatef( current_device_rotation(), 0, 0, 1); gltrackball_rotate(js->trackball); glRotatef(-current_device_rotation(), 0, 0, 1); if(js->color_style == COLOR_STYLE_CYCLE) { int i; vector_add(js->jiggly_color, js->color_dir, js->jiggly_color); for(i=0; i<3; i++) { if(js->jiggly_color[i] > 1.0 || js->jiggly_color[i] < 0.3) { js->color_dir[i] = (-js->color_dir[i]); js->jiggly_color[i] += js->color_dir[i]; } } glColor4fv(js->jiggly_color); } mi->polygon_count = jigglypuff_render(js); if(MI_IS_FPS(mi)) do_fps(mi); glFinish(); update_shape(js); glXSwapBuffers(MI_DISPLAY(mi), MI_WINDOW(mi)); }
char *test_add_elements_causing_expand() { vector_p vector = vector_create(sizeof(int)); for(int i = 0 ; i < 20 ;++i) { vector_add(vector, test_data(i)); } mu_assert(vector->capacity == 20, "expected capacity of 20"); mu_assert(*(int*)vector_get(vector, 0) == 0, "expected 0"); mu_assert(*(int*)vector_get(vector, 19) == 19, "expected 0"); vector_free(vector); return NULL; }
void spacecraft_collision(simulation_t* sim,spacecraft_t* spacecraft) { vector_t displacement=vector_subtract(spacecraft->base.position,spacecraft->orbit.primary->base.position); double distance=vector_magnitude(displacement); double penetration=spacecraft->orbit.primary->radius-distance; if(penetration>0) { displacement=vector_multiply((distance+penetration)/distance,displacement); spacecraft->base.position=vector_add(spacecraft->orbit.primary->base.position,displacement); spacecraft->base.velocity=spacecraft->orbit.primary->base.velocity; spacecraft->base.velocity.x+=spacecraft->orbit.primary->base.delta_rot*displacement.y; spacecraft->base.velocity.y+=-spacecraft->orbit.primary->base.delta_rot*displacement.x; spacecraft->base.rotation=atan2(-displacement.y,displacement.x)+M_PI/2; spacecraft->base.delta_rot=0; } }
rcl_status cl_create_program(struct client_state* state, char* source, program_t* program_id) { int32_t index; cl_int error; rcl_status status = RCL_HOST_RESOURCE; struct program_state* program_state; size_t size = strlen(source); log_print(log_notice, "Creating program"); program_state = malloc(sizeof(struct program_state)); if (!program_state) goto out_alloc; program_state->source = strdup(source); if (!program_state->source) goto out_alloc; program_state->flags = NULL; program_state->id = clCreateProgramWithSource(state->context, 1, (const char **)&source, (const size_t *)&size, &error); if (error != CL_SUCCESS) { log_print(log_error, "Error creating program: %s", clerror_name(error)); status = opencl_error(error); goto out_alloc; } index = vector_add(&state->programs, &program_state); if (index < 0) { status = RCL_HOST_RESOURCE; goto out_release; } *program_id = index; return RCL_OK; out_release: clReleaseProgram(program_state->id); out_alloc: if (program_state) free(program_state->source); free(program_state); return status; }
static int vector_vector_op(zend_uchar opcode, zval *result, zval *vec1, zval *vec2) /* {{{ */ { if (Z_OBJCE_P(vec1) != Z_OBJCE_P(vec2)) { zend_throw_exception(NULL, "Vectors must be of the same type", 0); return FAILURE; } switch(opcode) { case ZEND_ADD: return vector_add(result, vec1, vec2); case ZEND_SUB: return vector_sub(result, vec1, vec2); } zend_throw_exception(NULL, "Unsupported vector operation", 0); return FAILURE; }
void FUNC( smc_step, TYPE)( T* x, T* w, int N, int Dx, int Dy, T* y, T* scale_step, T* step, T* x_out, int t, T* args) { T* x_o; T* x_i; T* yt = vector_get(y, Dy, t); for (int i = 0; i < N; i++) { x_o = vector_get(x_out, Dx, i); x_i = vector_get(x, Dx, i); matrix_times(scale_step, x_i, x_o, Dx, Dx, Dx, 1); vector_add(vector_get(step, Dx, i), x_o, x_o, Dx); w[i] *= LIKELIHOOD_H(x_o, yt, args, Dx, Dy); } }
int sem_init(int start_val) { int init = -1; if(checkEmpty(&sem_stack)){ init = vector_add(&sem_list, &start_val); } else{ // use top stack value init = pop(&sem_stack); vector_set(&sem_list, init, &start_val); } return init; // I'm not sure where we should return the ENOMEM error val.. // ..probably in the vector.c file }
void CTestDisplay::render(Camera* camera) { Vector_ pos; go->pos(&pos); vector_add(&pos, &pos, &offset); ColoredRect rect = (ColoredRect)GIGGLE->renderer->alloc(sizeof(ColoredRect_)); rect->minx = pos.x - w/2; rect->maxx = pos.x + w/2; rect->miny = pos.y - h/2; rect->maxy = pos.y + h/2; rect->color[0] = color.r; rect->color[1] = color.g; rect->color[2] = color.b; rect->color[3] = color.a; camera->addRect(&camera->testRects[layer], rect); }
int main(int argc, char *argv[]){ if(argc !=2){ printf("Usage: %s filename", argv[0]); exit(EXIT_FAILURE); } FILE *file = fopen(argv[1],"r"); if(file ==NULL){ printf("could not open file\n"); exit(EXIT_FAILURE); } char * line = NULL; size_t len = 0; ssize_t read; TestData *tdata; vector v; vector_init(&v); /* * TestData struct not fit in * hold test data in vector * */ while ((read = getline(&line, &len,file))!=-1){ printf("Retrieved line of length %zu :\n", read); vector_add(&v,line); printf("%s", line); } fclose(file); /* * * * def struct to hold test data * */ int n; SRunner *sr; sr = srunner_create(make_add_suite2()); srunner_run_all(sr, CK_VERBOSE); n = srunner_ntests_failed(sr); srunner_free(sr); return (n==0)? EXIT_SUCCESS:EXIT_FAILURE; }
t_vector *arm_findalloptions(t_vector *arm) { int i; t_arm_argument *arg; t_vector *options; options = vector_new(VECTOR_DEFAULT_CAPACITY); i = 0; while (i < arm->total) { arg = vector_get(arm, i); if (arm_isoption(arg)) vector_add(options, arg); i++; } return (options); }
// FIXME this does not work as expected/desired for a multi-character delimiter // since it uses strtok under the hood LValue *l_func_str_split(LValue *args, LClosure *closure) { LValue *string = l_list_get(args, 0); LValue *delim = l_list_get(args, 1); l_assert_is(string, L_STR_TYPE, L_ERR_MISSING_STR, closure); l_assert_is(delim, L_STR_TYPE, L_ERR_MISSING_STR, closure); int i, size; char **strings = str_split(string->core.str->str, delim->core.str->str, &size); LValue *value = l_value_new(L_LIST_TYPE, closure); value->core.list = create_vector(); LValue *s; for(i=0; i<size; i++) { s = l_value_new(L_STR_TYPE, closure); s->core.str = make_stringbuf(strings[i]); vector_add(value->core.list, s, sizeof(s)); } return value; }
void spacecraft_position_docked(spacecraft_t* spacecraft) { int i; for(i=0;i<spacecraft->num_docks;i++) { dock_t* dock=spacecraft->docks+i; if(dock->docked_spacecraft!=NULL) { dock_t* docked_dock=&dock->docked_spacecraft->docks[dock->docked_dock]; vector_t dock_1_position=rotate_vector(dock->position,dock->orientation); vector_t dock_2_position=rotate_vector(docked_dock->position,docked_dock->orientation); dock->docked_spacecraft->base.position=vector_add(spacecraft->base.position,rotate_vector(vector_add(dock_1_position,dock_2_position),spacecraft->base.rotation)); dock->docked_spacecraft->base.rotation=spacecraft->base.rotation+dock->orientation+docked_dock->orientation+M_PI; } } }
void Sprite_PlayAnimation(SpriteObj* sprite, const std::string& name, Sprite::AnimationMode mode, float transitionTime) { // Get animation SpriteResource::Animation* animation = NULL; if (name == std::string()) animation = sprite->resource->defaultAnimation; else { std::map<std::string, SpriteResource::Animation>::iterator it = sprite->resource->animations.find(name); if (it == sprite->resource->animations.end()) { Log::Error(string_format("Animation %s not found in sprite %s", name.c_str(), sprite->resource->name.c_str())); return; } animation = &it->second; } // Check if not already played for (std::vector<SpriteObj::AnimationInstance>::iterator it = sprite->animationInstances.begin(); it != sprite->animationInstances.end(); ++it) if (it->animation == animation) return; // Fade out or kill all other animations const float weightChangeSpeed = transitionTime == 0.0f ? 0.0f : 1.0f / transitionTime; if (mode != Sprite::AnimationMode_OnceWhenDone && mode != Sprite::AnimationMode_LoopWhenDone) { if (transitionTime == 0.0f) sprite->animationInstances.clear(); else for (std::vector<SpriteObj::AnimationInstance>::iterator it = sprite->animationInstances.begin(); it != sprite->animationInstances.end(); ++it) it->weightChangeSpeed = -weightChangeSpeed; } // Create animation instance SpriteObj::AnimationInstance& animationInstance = vector_add(sprite->animationInstances); animationInstance.animation = animation; animationInstance.mode = mode; animationInstance.time = 0.0f; animationInstance.weight = transitionTime == 0.0f ? 1.0f : 0.0f; animationInstance.weightChangeSpeed = weightChangeSpeed; }
/* ================= line_recalculate ================= */ GNUC_NONNULL static void line_recalculate (const g_entity_t *ent) { const double zero[3] = { 0.0, 0.0, 1.0 }; ent_render_line_t *r = ent->render_data; double length, v[3], n[3]; if (!ent->render_valid) return; if (r->width < 0.1) { r->draw = false; return; } vector_sub(r->finish, ent->origin, v); length = vector_length(v); if (length < 0.1) { r->draw = false; return; } r->draw = true; vector_normal(v, zero, n); vector_normalize(n); vector_mul(n, r->width / 2.0, n); r->verts[0] = n[0]; r->verts[1] = n[1]; r->verts[2] = -n[0]; r->verts[3] = -n[1]; vector_add(r->finish, n, &r->verts[4]); vector_sub(&r->verts[4], ent->origin, &r->verts[4]); vector_sub(r->finish, n, &r->verts[6]); vector_sub(&r->verts[6], ent->origin, &r->verts[6]); r->texcoords[0] = 0.0; r->texcoords[1] = length / r->texture->w; r->texcoords[2] = 1.0; r->texcoords[3] = r->texcoords[1]; r->texcoords[4] = 0.0; r->texcoords[5] = 0.0; r->texcoords[6] = 1.0; r->texcoords[7] = 0.0; }
void CDrawTilemap::render(Camera* camera) { if(!map) return; if(map_dirty) { Vector_ pos; go->pos(&pos); vector_add(&pos, &pos, &offset); float w = map->width_IT * map->tile_width_IP; float h = map->height_IT * map->tile_height_IP; BaseSprite sprites = map->spritelist(NULL, 0, 0, w, h, &pos); camera->addRenderable(layer, renderer, sprites); map_dirty = 0; } else { camera->addRenderable(layer, renderer, NULL); } }
Vector *vector_with(const Vector *vector, void *value) { if(NULL == vector || NULL == value) { errno = EINVAL; return NULL; } Vector *result = vector_copy(vector); if(NULL == result) { return NULL; } vector_add(result, value); return result; }
/** * Render a single ray from a camera. * \param s Scene to render. * \param r Ray being cast. * \param wavelength * \param depth How deep are we in the recursion? * \return Energy of the ray. */ static float render_ray(const struct scene *s, struct ray *r, wavelength_t wavelength, int depth){ if(depth > MAX_DEPTH){ return 0; } struct object *obj = NULL; MEASUREMENTS_RAY_SCENE_INTERSECTION(); float distance = kd_tree_ray_intersection(&(s->tree), r, 0, INFINITY, &obj); if(isnan(distance)){ // If the ray didn't hit anything, it stays black. return 0; } vector_t pointInCameraSpace = vector_add(r->origin, vector_multiply(r->direction, distance)); vector_t pointInObjectSpace = vector_transform(pointInCameraSpace, &(obj->invTransform)); vector_t normalInObjectSpace = obj->get_normal(obj, pointInObjectSpace); vector_t normalInCameraSpace = vector_normalize(vector_transform_direction(normalInObjectSpace, &(obj->transform))); #if DOT_PRODUCT_SHADING (void)wavelength; return fabsf(vector_dot(normalInCameraSpace, r->direction)); #else float energy = 0; /// \todo Surface properties shouldn't be in camera space. if(object_is_light_source(obj)){ energy = (obj->light.energy)(pointInCameraSpace, wavelength, normalInCameraSpace, r->direction); } struct outgoing_direction sample = (obj->surface.sample)(pointInCameraSpace, wavelength, normalInCameraSpace, r->direction); struct ray newRay; ray_from_direction(&newRay, pointInCameraSpace, sample.direction); energy += sample.weight * render_ray(s, &newRay, wavelength, depth + 1); return energy; #endif }
void verlet(const data* dat, output_function output) { int i; const double dt = dat->eta * delta_t_factor; // konstant vector *a = (vector*) malloc((dat->N)*sizeof(vector)), *a_1 = (vector*) malloc((dat->N)*sizeof(vector)), *r_p = (vector*) malloc((dat->N)*sizeof(vector)), // r_(n-1), not initialized *r = init_r(dat), // r_(n) *r_n = (vector*) malloc((dat->N)*sizeof(vector)), // r_(n+1), not initialized *v = init_v(dat); // v_(n) double time = 0; output(time, dt, dat, r, v); // set initial data accelerations(dat, r, a); // a_0 adots(dat, r, v, a_1); for (i = 0; i < dat->N; i++) { // set r_(-1) r_p[i] = vector_add(r[i], vector_add(scalar_mult(dt, v[i]), scalar_mult(0.5 * dt * dt, a[i]))); // set r_1 r_n[i] = vector_add(scalar_mult(2, r[i]), vector_add(scalar_mult(-1, r_p[i]), scalar_mult(dt * dt, a[i]))); } //time += dt; // regular timesteps while (time < dat->t_max) { accelerations(dat, r_n, a); // a_n+1 (gets shifted to a_n) for (i = 0; i < dat->N; i++) { // shift indexes n+1 -> n r_p[i] = r[i]; r[i] = r_n[i]; r_n[i] = vector_add(scalar_mult(2, r[i]), vector_add(scalar_mult(-1, r_p[i]), scalar_mult(dt * dt, a[i]))); v[i] = scalar_mult(0.5 / dt, vector_diff(r_n[i], r_p[i])); } adots(dat, r, v, a_1); time += dt; output(time, dt, dat, r, v); } free(a); free(r_p); free(r); free(r_n); free(v); }
Bool line_triangle_solve( float A[3], float B[3], float C[3], float D[3], float E[3], float X[3], double *t) { /* sets X to the intersection of line AB with triangle CDE */ float m[3][3]; double d, d1; if(vector_eq(A,B)) { printf("intersection of AB with CDE not found: A=B !!!\n"); return False; } if(vector_eq(C,D) ||vector_eq(C,E) || vector_eq(D,E) ) { printf("intersection of AB with CDE not found: CDE is not a triangle !!!\n"); return False; } vector_sub(D,C, m[0]); vector_sub(E,C, m[1]); vector_sub(A,B, m[2]); d=matrix3_det(m); if(d==0) { printf("intersection of AB with CDE not found: AB and CDE are parallel !!!\n"); return False; } vectorcpy(X, m[2]); vector_sub(A,C, m[2]); d1=matrix3_det(m); *t=d1/d; vector_scale(-d1/d, X); vector_add(A,X, X); return True; }
/* * Calculate reflection color */ color refColor(const intersection *inter, const ray *srcRay) { color cR = BLACK; if (srcRay->depth == MAX_DEPTH) return cR; intersection refInter; vec3 refVec = vector_reflect(srcRay->dir, inter->normal); ray refRay; // Ray from object to other object ray_init(&refRay, inter->position, refVec, EPSILON, 1000, srcRay->depth + 1); int bounceFound = 0; for (int k = 0; k < object_count; ++k) { bounceFound += intersect(&refRay, &(scene[k]), &refInter); } color refCoef = reflectCoef(inter->mat.reflect_coef, inter->normal, srcRay->dir); if (bounceFound) cR = vector_vec_mul(refCoef, vector_add(refColor(&refInter, &refRay), lightColor(&refInter, &refRay))); else cR = vector_vec_mul(refCoef, SKY_COLOR); return cR; }
// App message in recieved handler for schedule void schedule_in_received_handler(DictionaryIterator *iter) { hide_loading_icon(); Tuple *schedule_time_tuple = dict_find(iter, SCHEDULE_TIME); Tuple *index_tuple = dict_find(iter, INDEX); Tuple *name_tuple = dict_find(iter, NAME); if (index_tuple && schedule_time_tuple && name_tuple) { entertainment_name = name_tuple->value->cstring; EntertainmentTime *time = (EntertainmentTime *)malloc(sizeof(EntertainmentTime)); strncpy(time->time, schedule_time_tuple->value->cstring, sizeof(time->time)); time->index = index_tuple->value->int16; if (times.data != NULL) { vector_add(×, time); layer_mark_dirty(menu_layer_get_layer(s_menulayer_1)); menu_layer_reload_data(s_menulayer_1); } } else { } }
char *test_remove_and_resize() { vector_p vector = vector_create(sizeof(int)); for(int i = 0 ; i < 80 ; ++i) { vector_add(vector, test_data(i)); } for(int i = 0 ; i < 60 ; ++i) { vector_remove(vector, 0); } mu_assert(vector->capacity == 20, "should have reduced capacity"); vector_free(vector); return NULL; }