Пример #1
0
void		init_lum_shadow(t_all *infos, t_object *object,
				t_pixel *pixel, t_eye *eye)
{
  t_spot	*tmp_spot;
  t_coord	pt_inter;
  t_coord	v_norm;
  t_eye		eye_tmp;
  double	shadow;

  init_struct(eye, &eye_tmp, &pt_inter, pixel);
  lum_shadow(infos, &pt_inter, object, pixel);
  tmp_spot = infos->spots;
  shadow = 0;
  while (tmp_spot != NULL)
    {
      new_eye_posi(&eye_tmp, tmp_spot, &pt_inter);
      if (calc_obj(infos->objects, object, &eye_tmp) > 0)
        shadow += ((double) WIN(tmp_spot->intensity, 0, 100)) / SHADOW_FACTOR;
      tmp_spot = tmp_spot->next;
    }
  set_shadows(pixel, &shadow);
  if (object->reflexion > 0 && ++infos->travels < TRAVEL_LIMIT)
    {
      calc_vector_n(object, &pt_inter, &v_norm);
      init_reflection(&eye_tmp, eye, &v_norm, &pt_inter);
      reflection(infos, object, pixel, &eye_tmp);
    }
}
Пример #2
0
Work::Work(const Device& device,
           const ComputeSize& computeSize,
           const SpirvBinary& spirv,
           const SpecConstInfo& additionalSpecConstInfo)
    : mComputeSize(computeSize), mDevice(device)
{
  vk::ShaderModule shaderModule = device.GetShaderModule(spirv);
  SPIRV::Reflection reflection(spirv);
  if (reflection.GetShaderStage() != vk::ShaderStageFlagBits::eCompute)
    throw std::runtime_error("only compute supported");

  mPipelineLayout = {{reflection}};
  auto layout = device.GetLayoutManager().GetPipelineLayout(mPipelineLayout);

  SpecConstInfo specConstInfo = additionalSpecConstInfo;

  assert(mComputeSize.LocalSize.x > 0 && mComputeSize.LocalSize.y > 0);
  if (mComputeSize.LocalSize.y != 1)
  {
    Detail::InsertSpecConst(specConstInfo,
                            SpecConstValue(1, mComputeSize.LocalSize.x),
                            SpecConstValue(2, mComputeSize.LocalSize.y));

    mPipeline =
        device.GetPipelineCache().CreateComputePipeline(shaderModule, layout, specConstInfo);
  }
  else
  {
    Detail::InsertSpecConst(specConstInfo, SpecConstValue(1, mComputeSize.LocalSize.x));

    mPipeline =
        device.GetPipelineCache().CreateComputePipeline(shaderModule, layout, specConstInfo);
  }
}
Пример #3
0
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QMainWindow::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: openFile(); break;
        case 1: applyChanges(); break;
        case 2: saveFile(); break;
        case 3: exit(); break;
        case 4: effects(); break;
        case 5: zoom(); break;
        case 6: resize(); break;
        case 7: crop(); break;
        case 8: rotateRight(); break;
        case 9: rotateLeft(); break;
        case 10: mirror(); break;
        case 11: reflection(); break;
        case 12: grayScale(); break;
        case 13: xray(); break;
        case 14: sepia(); break;
        default: ;
        }
        _id -= 15;
    }
    return _id;
}
int main(int argc, char** argv) {
  if(!parseOption(argc, argv)) {
    fprintf(stderr, "failed to parse option\n");
    return 1;
  }

  BCCScriptRef script;

  if((script = loadScript()) == NULL) {
    fprintf(stderr, "failed to load source\n");
    return 2;
  }

#if 0
  if(printTypeInformation && !reflection(script, stderr)) {
    fprintf(stderr, "failed to retrieve type information\n");
    return 3;
  }
#endif

  printPragma(script);

  if(printListing && !disassemble(script, stderr)) {
    fprintf(stderr, "failed to disassemble\n");
    return 5;
  }

  if(runResults && !runMain(script, argc, argv)) {
    fprintf(stderr, "failed to execute\n");
    return 6;
  }

  return 0;
}
Пример #5
0
Файл: main.cpp Проект: JoaoS/CG
void drawScene()
{
	
    
    reflection();


	//============================================Eixos
	if (noite)
		glColor4f(AMARELO);
	else
		glColor4f(BLACK);

    glColor4f(WHITE); //fazer reset as cores para o blend + texturas
    /*desenho da caixa*/

    duplicates();//mesmas funcoes que abaixo para meter os paineis a reflectir por  dentro
    //atras
     glPushMatrix();
        glColor4f(DEEPBLUE);
        glTranslatef(3, 0, 3);
        glRotatef(-90,1,0,0);  
        quad(2,0,0,0);
    glPopMatrix();

    //contrario a bola
     glPushMatrix();
        glColor4f(TORRADO);
        glTranslatef(3+multiplier*2, 0, 3+multiplier*2);
        glRotatef(180,0,1,0); //para a reflexao ficar na face exterior da caixa, senão ficava interior
        glRotatef(90,0,0,1); 
        quad(2,0,0,0);
    glPopMatrix();
    
    //em cima
   glPushMatrix();
        glColor4f(SBLUE);
        glTranslatef(3, multiplier*2, 3);   
        quad(2,0,0,0);
    glPopMatrix();

    //lado da bola
    glPushMatrix();
        glColor4f(TORRADO);
        glTranslatef(3, 0, 3);
        glRotatef(90,0,0,1); 
        quad(2,0,0,0);
    glPopMatrix();

    /* desenho do nivel */
    draw_level(level);
    /* desenho da bola */
    glPushMatrix();
        glColor4f(AMARELO);
        glTranslatef(posEsfera[0],posEsfera[1],posEsfera[2]);
        glutSolidSphere(raioEsfera, 256, 256);//radius , (slices(longitude), stacks(latitude))->malhas
    glPopMatrix();
   	glutPostRedisplay();
}
Пример #6
0
 void set_enum( const field_desc_type *fld, const std::string &v )
 {
     const enum_value_type* ed(fld->enum_type( )->FindValueByName(v));
     if( ed )
         reflection()->SetEnum(mess_, fld, ed);
     else
         throw std::runtime_error( "Bad enum value name" );
 }
Пример #7
0
bool TreeDrawer::reflection(GenomNode *node, QGraphicsView * treeView, int x, int y, std::multimap<int, GenomNode*> * treeMap, int levelCount)
{
    bool result = false;
    if (node->getLeftChild() != NULL) {
        if ( (x < (node->getNodeX() + node->genomBody->width())) && (x > (node->getNodeX())) && (y < (node->getNodeY() + node->genomBody->height())) && (y > (node->getNodeY() - 45))) {
            reflectBranch(node, treeView);
            setCoordAndDraw(treeMap,treeView,levelCount);
            result = true;
        } else {
            if (node->getLeftChild() != NULL) {
                if (!result) result = reflection(node->getLeftChild(), treeView, x, y, treeMap,levelCount);
                if (!result) result = reflection(node->getRightChild(), treeView, x, y, treeMap,levelCount);
            }
        }
    }
    return result;
}
Пример #8
0
		//-----------------------------------------------------------------------------	
		Matrix22& Matrix22::ReflectArbitraryAxis( const Vector2D& axis )
		{
			Matrix22 reflection(1.0f - (2.0f * (axis.x * axis.x)), 
								-2.0f * axis.x * axis.y,
								-2.0f * axis.x * axis.y,
								1.0f - (2.0f * (axis.y * axis.y)));

			*this *= reflection;

			return *this;
		}
Пример #9
0
		//-----------------------------------------------------------------------------	
		Matrix22 Matrix22::AsReflectArbitraryAxis( const Vector2D& axis )const
		{
			Matrix22 reflection(1.0f - (2.0f * (axis.x * axis.x)), 
								-2.0f * axis.x * axis.y,
								-2.0f * axis.x * axis.y,
								1.0f - (2.0f * (axis.y * axis.y)));

			Matrix22 m(reflection * (*this));

			return m;
		}
Пример #10
0
Ray Raytracer::make_reflection_ray(const Vector3d &normal,
                                 const Ray &ray,
                                 const Point3d &intersection)
{
    Ray reflection(intersection,
                   normalize(
                       vector_subtract(ray.direction(),
                           scalar_multiply(normal,
                               2 * dot_product(ray.direction(), normal)))));
     return reflection;
}
    typename DownhillSimplexMethod< DIM >::Converged DownhillSimplexMethod< DIM >::optimize( const ParamsT& initial )
    {
        assert( m_refl > 0.0 );
        assert( m_exp > 1.0 );
        assert( m_exp > m_refl );
        assert( 0 < m_contr && m_contr < 1 );
        assert( 0 < m_shri && m_shri < 1 );
        assert( m_initFactor > 0.0 );

        // Prepare optimization
        m_iterations = 0;
        createInitials( initial );

        Converged conv = CONVERGED_NO;
        Step next = STEP_START;
        while( next != STEP_EXIT )
        {
            switch( next )
            {
                case STEP_START:
                    order();
                    conv = converged();
                    if( conv != CONVERGED_NO )
                    {
                        next = STEP_EXIT;
                        break;
                    }
                    ++m_iterations;
                    centroid();
                    next = STEP_REFLECTION;
                    break;
                case STEP_REFLECTION:
                    next = reflection();
                    break;
                case STEP_EXPANSION:
                    next = expansion();
                    break;
                case STEP_CONTRACTION:
                    next = contraction();
                    break;
                case STEP_SHRINKAGE:
                    next = shrinkage();
                    break;
                default:
                    std::cerr << "Undefined control flow!";
                    next = STEP_EXIT;
                    break;
            }
        }

        return conv;
    }
FloatRect FEBoxReflect::mapRect(const FloatRect& rect, bool forward)
{
    SkMatrix flipMatrix = SkiaImageFilterBuilder().matrixForBoxReflectFilter(
        m_reflectionDirection, m_offset);
    if (!forward) {
        bool inverted = flipMatrix.invert(&flipMatrix);
        DCHECK(inverted) << "box reflect matrix must be invertible";
    }

    SkRect reflection(rect);
    flipMatrix.mapRect(&reflection);

    FloatRect result = rect;
    result.unite(reflection);
    return result;
}
Пример #13
0
void PrettyImage::paintEvent(QPaintEvent*) {
  // Draw at the bottom of our area
  QRect image_rect(QPoint(0, 0), image_size());
  image_rect.moveBottom(kImageHeight);

  QPainter p(this);

  // Draw the main image
  DrawThumbnail(&p, image_rect);

  // Draw the reflection
  // Figure out where to draw it
  QRect reflection_rect(image_rect);
  reflection_rect.moveTop(image_rect.bottom());

  // Create the reflected pixmap
  QImage reflection(reflection_rect.size(),
                    QImage::Format_ARGB32_Premultiplied);
  reflection.fill(palette().color(QPalette::Base).rgba());
  QPainter reflection_painter(&reflection);

  // Set up the transformation
  QTransform transform;
  transform.scale(1.0, -1.0);
  transform.translate(0.0, -reflection_rect.height());
  reflection_painter.setTransform(transform);

  QRect fade_rect(reflection.rect().bottomLeft() - QPoint(0, kReflectionHeight),
                  reflection.rect().bottomRight());

  // Draw the reflection into the buffer
  DrawThumbnail(&reflection_painter, reflection.rect());

  // Make it fade out towards the bottom
  QLinearGradient fade_gradient(fade_rect.topLeft(), fade_rect.bottomLeft());
  fade_gradient.setColorAt(0.0, QColor(0, 0, 0, 0));
  fade_gradient.setColorAt(1.0, QColor(0, 0, 0, 128));

  reflection_painter.setCompositionMode(
      QPainter::CompositionMode_DestinationIn);
  reflection_painter.fillRect(fade_rect, fade_gradient);

  reflection_painter.end();

  // Draw the reflection on the image
  p.drawImage(reflection_rect, reflection);
}
Пример #14
0
WelcomeItem::WelcomeItem(const QRectF &rect, QGraphicsItem *parent)
    : QGraphicsRectItem(rect, parent), d(new Private) {
  // TODO
  d->height = 128;
  d->width = 128;
  d->size = QSize(d->width, d->height);
  d->iconPixmap = QPixmap();
  d->opacity = 1.0f;
  d->timeline.setDuration(200);
  d->timeline.setFrameRange(0, 120);
  d->timeline.setCurveShape(QTimeLine::EaseInCurve);
  connect(&d->timeline, SIGNAL(frameChanged(int)), this, SLOT(zoom(int)));
  d->blured = false;
  d->refimg = QImage(d->size, QImage::Format_ARGB32_Premultiplied);
  d->refimg = reflection(d->refimg);
  setAcceptsHoverEvents(true);
}
Пример #15
0
void setup_sphere_shading(osg::ref_ptr<osg::StateSet> osg_state, boost::shared_ptr<shade::Texture> cube_map)
{
    boost::shared_ptr<shade::GLSLWrapper> state(new shade::osg::Wrapper(osg_state));

    boost::shared_ptr<shade::shaders::Surface> shader(new shade::shaders::Surface);
    boost::shared_ptr<shade::Program> program(new shade::Program(shader, state));

    boost::shared_ptr<Reflection> reflection(new Reflection());
    reflection->cube_map.set(cube_map);
    boost::shared_ptr<shade::shaders::ObjectSpace> object_space(new shade::shaders::ObjectSpace);
    reflection->coordinate_system = object_space;
    shader->material = reflection;

    program->compile();
    state->make_current();
    program->upload();
}
Пример #16
0
Spectrum DirectLightingIntegrator::Li(const Scene *scene,
                                      const Renderer *renderer, const RayDifferential &ray,
                                      const Intersection &isect, const Sample *sample, RNG &rng, MemoryArena &arena) const {
    Spectrum L(0.f);
    // Evaluate BSDF at hit point
    BSDF *bsdf = isect.GetBSDF(ray, arena);
    Vector wo = -ray.d;
    const Point &p = bsdf->dgShading.p;
    const Normal &n = bsdf->dgShading.nn;
    // Compute emitted light if ray hit an area light source
    L += isect.Le(wo);

    // Compute direct lighting for _DirectLightingIntegrator_ integrator
    if (scene->lights.size() > 0) {
        // Apply direct lighting strategy
        switch (strategy) {
        case SAMPLE_ALL_UNIFORM:
            L += UniformSampleAllLights(scene, renderer, arena, p, n, wo,
                                        isect.rayEpsilon, ray.time, bsdf, sample, rng,
                                        lightSampleOffsets, bsdfSampleOffsets);
            break;
        case SAMPLE_ONE_UNIFORM:
            L += UniformSampleOneLight(scene, renderer, arena, p, n, wo,
                                       isect.rayEpsilon, ray.time, bsdf, sample, rng,
                                       lightNumOffset, lightSampleOffsets, bsdfSampleOffsets);
            break;
        }
    }
    if (ray.depth + 1 < maxDepth) {
        Vector wi;
        // Trace rays for specular reflection and refraction
        Spectrum reflection(0.f);
        Spectrum refraction(0.f);
        reflection = SpecularReflect(ray, bsdf, rng, isect, renderer, scene,
                                     sample,arena);
        refraction = SpecularTransmit(ray, bsdf, rng, isect, renderer, scene,
                                      sample, arena);

        L += reflection;
        L += refraction;
    }
    //printf("Size %i \n", NaiadFoam::cur->FoamPlane().size());

    return L*bsdf->dgShading.mult;
}
Пример #17
0
void FreeSpaceBar::paintEvent(QPaintEvent*) {
  // Geometry
  QRect bar_rect(rect());
  bar_rect.setHeight(kBarHeight);

  QRect reflection_rect(bar_rect);
  reflection_rect.moveTop(reflection_rect.bottom());

  QRect labels_rect(rect());
  labels_rect.setTop(labels_rect.top() + kBarHeight + kLabelBoxPadding);

  // Draw the reflection
  // Create the reflected pixmap
  QImage reflection(reflection_rect.size(),
                    QImage::Format_ARGB32_Premultiplied);
  reflection.fill(palette().color(QPalette::Background).rgba());
  QPainter p(&reflection);

  // Set up the transformation
  QTransform transform;
  transform.scale(1.0, -1.0);
  transform.translate(0.0, -reflection.height());
  p.setTransform(transform);

  // Draw the bar
  DrawBar(&p, QRect(QPoint(0, 0), reflection.size()));

  // Make it fade out towards the bottom
  QLinearGradient fade_gradient(reflection.rect().topLeft(),
                                reflection.rect().bottomLeft());
  fade_gradient.setColorAt(0.0, QColor(0, 0, 0, 0));
  fade_gradient.setColorAt(1.0, QColor(0, 0, 0, 128));

  p.setCompositionMode(QPainter::CompositionMode_DestinationIn);
  p.fillRect(reflection.rect(), fade_gradient);

  p.end();

  // Draw on the widget
  p.begin(this);
  DrawBar(&p, bar_rect);
  p.drawImage(reflection_rect, reflection);
  DrawText(&p, labels_rect);
}
Пример #18
0
int combination(char before[][NO], char trans[][NO], char target[][NO], int n)
{
	char tmp[NO][NO];
	memset(tmp, 0, sizeof(tmp));

	reflection(before, trans, n);

	int i;
	for (i = 0; i < 3; ++i) {
		rotate_90(trans, tmp, n);
		/* why missing last parameter n is ok?
		if (!compare(trans, target))
		*/
		if (!compare(tmp, target, n))
			return 0;

		memcpy(trans, tmp, sizeof(tmp));
	}

	return 1;
}
Пример #19
0
void WelcomeItem::setIcon(const QPixmap &icon) {
  d->iconPixmap = QPixmap(icon);
  // FIXME
  // Optimize
  QImage Buffer = icon.toImage();
  d->refimg = d->refimg.scaled(boundingRect().width(), boundingRect().height());
  QPainter p(&d->refimg);

  p.setRenderHint(QPainter::Antialiasing);
  p.setRenderHint(QPainter::SmoothPixmapTransform);
  p.setCompositionMode(QPainter::CompositionMode_Source);
  p.fillRect(QRect(0, 0, boundingRect().width(), boundingRect().height()),
             Qt::transparent);

  Buffer = reflection(Buffer);
  Buffer = Blitz::blur(Buffer, 8);
  QTransform trans;
  // trans.translate(30,100);
  p.setTransform(trans);
  p.drawImage(QPoint(0, 0), Buffer);
  p.end();
}
Пример #20
0
Vec3f RayTracer::reflections(const Ray &ray, const Hit &hit, int bounce_count, double roughness) const
{
	if (bounce_count <= 0)
		return Vec3f(0, 0, 0);
	const Vec3f point = ray.pointAtParameter(hit.getT());

	/* Get mirror direction */
	const Vec3f orig_dir = ray.getDirection();
	Vec3f norm = hit.getNormal();
	norm.Normalize();
	const Vec3f new_dir = orig_dir - 2 * orig_dir.Dot3(norm) * norm;

	const Ray new_ray(point, new_dir);
	Vec3f rand_vec(0, 0, 0);
	double answerx = 0, answery = 0, answerz = 0;
	/* sphere projection, what if the center of the sphere misses the
	 * object?
	 */

	{
		for (int i = 0; i <= args->num_glossy_samples; ++i) {
			/* Getting gloss ray */
			Ray start_ray(new_ray.getOrigin(),
					new_ray.getDirection() + rand_vec);
			const Vec3f answer(reflection(start_ray, bounce_count - 1));

			answerx += answer.x();
			answery += answer.y();
			answerz += answer.z();
			rand_vec = Vec3f(roughness * (static_cast<double>(rand()) / RAND_MAX),
				roughness * (static_cast<double>(rand()) / RAND_MAX),
				roughness * (static_cast<double>(rand()) / RAND_MAX));
		}
	}
	Vec3f answer = Vec3f(answerx, answery, answerz);
	answer *= static_cast<double>(1)/(args->num_glossy_samples + 1);
	return answer;
}
Пример #21
0
int main()
{
	FILE *fin, *fout;
	int result = 0;
	
	fin = fopen("transform.in", "r");
	if (!fin) {
		perror("open file transform.in failed");
		return -1;
	}

	char before[NO][NO];
	char target[NO][NO];
	char tmp[NO][NO];

	memset(before, 0, sizeof(before));
	memset(target, 0, sizeof(target));
	memset(target, 0, sizeof(tmp));

	int n;
	fscanf(fin, "%d", &n);

	int i = 0, j;
	for ( ; i < n; ++i) {
		fscanf(fin, "%s", before[i]);
	}

	for ( i = 0; i < n; ++i) {
		fscanf(fin, "%s", target[i]);
	}

	do {
		rotate_90(before, tmp, n);
		if (!compare(tmp, target, n)) {
			result = 1;
			break;
		}

		rotate_180(before, tmp, n);
		if (!compare(tmp, target, n)) {
			result = 2;
			break;
		}

		rotate_270(before, tmp, n);
		if (!compare(tmp, target, n)) {
			result = 3;
			break;
		}

		reflection(before, tmp, n);
		if (!compare(tmp, target, n)) {
			result = 4;
			break;
		}

		if (!combination(before, tmp, target, n)) {
			result = 5;
			break;
		}

		if (!compare(before, target, n)) {
			result = 6;
			break;
		}

		result = 7;
	} while (0);

	fout = fopen("transform.out", "w");
	fprintf(fout, "%d\n", result);
	fclose(fout);
	fclose(fin);

	return 0;
}
Пример #22
0
 void enum_set_fields( std::vector<
                         const field_desc_type *
                         > &result ) const
 {
     reflection( )->ListFields( *mess_, &result );
 }
Пример #23
0
static unsigned int ray_color(const point3 e, double t,
                              const point3 d,
                              idx_stack *stk,
                              const rectangular_node rectangulars,
                              const sphere_node spheres,
                              const light_node lights,
                              color object_color, int bounces_left)
{
    rectangular_node hit_rec = NULL, light_hit_rec = NULL;
    sphere_node hit_sphere = NULL, light_hit_sphere = NULL;
    double diffuse, specular;
    point3 l, _l, r, rr;
    object_fill fill;

    color reflection_part;
    color refraction_part;
    /* might be a reflection ray, so check how many times we've bounced */
    if (bounces_left == 0) {
        SET_COLOR(object_color, 0.0, 0.0, 0.0);
        return 0;
    }

    /* check for intersection with a sphere or a rectangular */
    intersection ip= ray_hit_object(e, d, t, MAX_DISTANCE, rectangulars,
                                    &hit_rec, spheres, &hit_sphere);
    if (!hit_rec && !hit_sphere)
        return 0;

    /* pick the fill of the object that was hit */
    fill = hit_rec ?
           hit_rec->element.rectangular_fill :
           hit_sphere->element.sphere_fill;

    void *hit_obj = hit_rec ? (void *) hit_rec : (void *) hit_sphere;

    /* assume it is a shadow */
    SET_COLOR(object_color, 0.0, 0.0, 0.0);

    for (light_node light = lights; light; light = light->next) {
        /* calculate the intersection vector pointing at the light */
        subtract_vector(ip.point, light->element.position, l);
        multiply_vector(l, -1, _l);
        normalize(_l);
        /* check for intersection with an object. use ignore_me
         * because we don't care about this normal
        */
        ray_hit_object(ip.point, _l, MIN_DISTANCE, length(l),
                       rectangulars, &light_hit_rec,
                       spheres, &light_hit_sphere);
        /* the light was not block by itself(lit object) */
        if (light_hit_rec || light_hit_sphere)
            continue;

        compute_specular_diffuse(&diffuse, &specular, d, l,
                                 ip.normal, fill.phong_power);

        localColor(object_color, light->element.light_color,
                   diffuse, specular, &fill);
    }

    reflection(r, d, ip.normal);
    double idx = idx_stack_top(stk).idx, idx_pass = fill.index_of_refraction;
    if (idx_stack_top(stk).obj == hit_obj) {
        idx_stack_pop(stk);
        idx_pass = idx_stack_top(stk).idx;
    } else {
        idx_stack_element e = { .obj = hit_obj,
                                .idx = fill.index_of_refraction
                              };
        idx_stack_push(stk, e);
    }

    refraction(rr, d, ip.normal, idx, idx_pass);
    double R = (fill.T > 0.1) ?
               fresnel(d, rr, ip.normal, idx, idx_pass) :
               1.0;

    /* totalColor = localColor +
                    mix((1-fill.Kd) * fill.R * reflection, T * refraction, R)
     */
    if (fill.R > 0) {
        /* if we hit something, add the color */
        int old_top = stk->top;
        if (ray_color(ip.point, MIN_DISTANCE, r, stk, rectangulars, spheres,
                      lights, reflection_part,
                      bounces_left - 1)) {
            multiply_vector(reflection_part, R * (1.0 - fill.Kd) * fill.R,
                            reflection_part);
            add_vector(object_color, reflection_part,
                       object_color);
        }
        stk->top = old_top;
    }
    /* calculate refraction ray */
    if ((length(rr) > 0.0) && (fill.T > 0.0) &&
            (fill.index_of_refraction > 0.0)) {
        normalize(rr);
        if (ray_color(ip.point, MIN_DISTANCE, rr, stk,rectangulars, spheres,
                      lights, refraction_part,
                      bounces_left - 1)) {
            multiply_vector(refraction_part, (1 - R) * fill.T,
                            refraction_part);
            add_vector(object_color, refraction_part,
                       object_color);
        }
    }

    protect_color_overflow(object_color);
    return 1;
}

/* @param background_color this is not ambient light */
void raytracing(void* args)
{
    arg *data = (arg*) args;
    point3 u, v, w, d;
    color object_color = { 0.0, 0.0, 0.0 };

    const viewpoint *view = (*data).View;
    color back = { 0.0 , 0.1 , 0.1 };
    uint8_t *pixels = data->pixels;
    int start_j,end_j;

    /*	Separate to count the pixels  */
    if(pthread_equal(pthread_self(),THREAD[0])) {
        start_j = 0;
        end_j = 128;
    } else if(pthread_equal(pthread_self(),THREAD[1])) {
        start_j = 128;
        end_j = 256;
    } else if(pthread_equal(pthread_self(),THREAD[2])) {
        start_j = 256;
        end_j = 384;
    } else if(pthread_equal(pthread_self(),THREAD[3])) {
        start_j = 384;
        end_j = 512;
    }

    /* calculate u, v, w */
    calculateBasisVectors(u, v, w, view);

    idx_stack stk;

    int factor = sqrt(SAMPLES);

    #pragma omp parallel for num_threads(64)	\
    private(stk), private(d),	\
    private(object_color)
    for (int j = start_j ; j < end_j; j++) {
        for (int i = 0 ; i < (*data).row; i++) {
            double r = 0, g = 0, b = 0;
            /* MSAA */
            for (int s = 0; s < SAMPLES; s++) {
                idx_stack_init(&stk);
                rayConstruction(d, u, v, w,
                                i * factor + s / factor,
                                j * factor + s % factor,
                                view,
                                (*data).row * factor, (*data).col * factor);
                if (ray_color(view->vrp, 0.0, d, &stk,(*data).rectangulars,
                              (*data).spheres, (*data).lights, object_color,
                              MAX_REFLECTION_BOUNCES)) {
                    r += object_color[0];
                    g += object_color[1];
                    b += object_color[2];
                } else {
                    r += back[0];
                    g += back[1];
                    b += back[2];
                }
                pixels[((i + (j * (*data).row)) * 3) + 0] = r * 255 / SAMPLES;
                pixels[((i + (j * (*data).row)) * 3) + 1] = g * 255 / SAMPLES;
                pixels[((i + (j * (*data).row)) * 3) + 2] = b * 255 / SAMPLES;
            }
        }
    }
}
Пример #24
0
//
// メインプログラム
//
int main()
{
    // GLFW を初期化する
    if (glfwInit() == GL_FALSE)
    {
        // 初期化に失敗した
        std::cerr << "Can't initialize GLFW" << std::endl;
        return 1;
    }

    // プログラム終了時の処理を登録する
    atexit(cleanup);

    // ウィンドウを作成する
    Window window("Irradiance Mapping", 960, 540);

    // OpenGL の初期設定
    glClearColor(0.3f, 0.5f, 0.8f, 0.0f);
    glEnable(GL_NORMALIZE);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_MULTISAMPLE);

    // 陰影付けを無効にする
    glDisable(GL_LIGHTING);

    // テクスチャ
    GLuint imap[mapcount], emap[mapcount];
    glGenTextures(mapcount, imap);
    glGenTextures(mapcount, emap);

    // テクスチャの読み込み
    for (size_t i = 0; i < mapcount; ++i)
    {
#if USEMAP
        loadMap(irrmaps[i], envmaps[i], imap[i], emap[i]);
#else
        createMap(skymaps[i], skysize, imap[i], imapsize, isamples, emap[i], emapsize, esamples, ambient, shininess);
#endif
    }

    // 放射照度マップのかさ上げに使うテクスチャユニットの設定
    glActiveTexture(GL_TEXTURE0);
    glEnable(GL_TEXTURE_2D);
    irradiance();

    // 放射照度マップのかさ上げに使うテクスチャユニットの設定
    glActiveTexture(GL_TEXTURE1);
    glEnable(GL_TEXTURE_2D);
    diffuse();

    // 環境マップの加算に使うテクスチャユニットの設定
    glActiveTexture(GL_TEXTURE2);
    glEnable(GL_TEXTURE_2D);
    reflection();

    // 材質データ
    GLuint ng;
    GLuint (*group)[2];
    GLfloat (*amb)[4], (*diff)[4], (*spec)[4], *shi;

    // 形状データ
    GLuint nv;
    GLfloat (*pos)[3], (*norm)[3];

    // 形状データの読み込み
    ggLoadObj(filename, ng, group, amb, diff, spec, shi, nv, pos, norm, false);

    // ウィンドウが開いている間繰り返す
    while (window.shouldClose() == GL_FALSE)
    {
        // ウィンドウを消去する
        window.clear();

        // テクスチャの選択
        const int select(window.getSelection() % mapcount);

        // 明るさ
        GLfloat brightness[4];
        window.getBrightness(brightness);

        // 放射照度マップのかさ上げ
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, imap[select]);
        glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, brightness);

        // 拡散反射光強度の算出
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, imap[select]);

        // 環境マッピング
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, emap[select]);

        // モデルビュー変換行列の設定
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        // 視点の移動
        glTranslatef(window.getPosition()[0], window.getPosition()[1], window.getPosition()[2]);

        // トラックボール処理による回転
        glMultMatrixf(window.getTb());

        // シーンの描画
        scene(ng, group, diff, spec, nv, pos, norm);

        // 床の描画
        floor(5, -1.0f);

        // カラーバッファを入れ替えてイベントを取り出す
        window.swapBuffers();
    }
}
Пример #25
0
 bool is_set( const field_desc_type *fld ) const
 {
     return reflection( )->HasField( *mess_, fld );
 }
Пример #26
0
bool reflectionTerm(param_tPtr eps)

{
	unsigned long   i = 1, layers = 1;
	double          thickness = 0.0, accuThickness = 0.0;
	char		Final[BUFSIZ],
			LayerProfil[BUFSIZ];
	FILE		*final,
			*layerprofil;
#ifndef PVM
	int		getpid(void);
			

 	sprintf(Final,		"%s%s%d.%s%ld", eps->Suffix, PTHSEP, getpid(),
		"FinalReflection_", eps->TotExp);
	sprintf(LayerProfil,	"%s%s%d.%s%ld", eps->Suffix, PTHSEP, getpid(),
		"LayerProfil_", eps->TotExp);
	sprintf(SpectralProfil,	"%s%s%d.%s%ld", eps->Suffix, PTHSEP, getpid(),
		"SpectralProfil_", eps->TotExp);
#else
 	sprintf(Final,		"%s%s%d.%s%ld", eps->Suffix, PTHSEP,
		eps->inst, "FinalReflection_", eps->TotExp);
	sprintf(LayerProfil,	"%s%s%d.%s%ld", eps->Suffix, PTHSEP,
		eps->inst, "LayerProfil_", eps->TotExp);
	sprintf(SpectralProfil,	"%s%s%d.%s%ld", eps->Suffix, PTHSEP,
		eps->inst, "SpectralProfil_", eps->TotExp);
#endif

	SpectralFlag = TRUE;

	if((final = fopen(Final, "w")) == NULL)
	    panic(A_FATAL, "reflectionTerm",
		  "Couldn't open logfile (%s) : %s : %d",
		  Final, __FILE__, __LINE__);
	if((layerprofil = fopen(LayerProfil, "w")) == NULL)
	    panic(A_FATAL, "reflectionTerm",
		  "Couldn't open logfile (%s) : %s : %d",
		  LayerProfil, __FILE__, __LINE__);
	if((spectralprofil = fopen(SpectralProfil, "w")) == NULL)
	    panic(A_FATAL, "reflectionTerm",
		  "Couldn't open logfile (%s) : %s : %d",
		  Final, __FILE__, __LINE__);

	fprintf(spectralprofil, "\n\n# Merit = %g",
		reflection(inGetX(eps->BstInd), inGetD(eps->BstInd)));
	

	fprintf(final, "Layer\tIndex\tGeometrical(nm)\t\tOptical(mikrom)\n");
	fprintf(final, "\n%ld\t%.4g\t",
		layers, RefInd[inGetDComponent(1, eps->BstInd)]);
	thickness = inGetXComponent(1, eps->BstInd);

	fprintf(layerprofil, "#thickness (mikrom)\tindex\n\n");
	fprintf(layerprofil, "%.10e\t%.4g\n", 0.0, 0.0);
	fprintf(layerprofil, "%.10e\t%.4g\n",
		0.0, RefInd[inGetDComponent(1, eps->BstInd)]);

	for(i = 1; i < inGetXLength(eps->BstInd); i++) {
		if(inGetDComponent(i,eps->BstInd) !=
		   inGetDComponent(i+1, eps->BstInd)) {
			fprintf(final, "%.10e\t%.10e\n",
				thickness,
				thickness /1000.0 *
				RefInd[inGetDComponent(i,eps->BstInd)]);
			accuThickness += thickness;
			fprintf(layerprofil, "%.10e\t%.4g\n",
				accuThickness/1000.0,
				RefInd[inGetDComponent(i+1, eps->BstInd)]);
			thickness = 0;
			layers++;
			fprintf(final, "%ld\t%.4g\t",
				layers,
				RefInd[inGetDComponent(i+1, eps->BstInd)]);
		}
		thickness += inGetXComponent(i+1,eps->BstInd);
	}
Пример #27
0
 int get_repeated_size( const field_desc_type *fld ) const
 {
     return reflection( )->FieldSize( *mess_, fld );
 }
Пример #28
0
 void add_string( const field_desc_type *fld, const std::string &v )
 {
     (reflection( )->*(type_info_string::add()))( mess_, fld, v );
 }
Пример #29
0
/** Does the convolution process for all pixels using the given mask. */
PNM* Convolution::convolute(math::matrix<float> mask, Mode mode = RepeatEdge)
{
    int width  = image->width(),
        height = image->height();

    PNM* newImage = new PNM(width, height, image->format());

    double weight = sum(mask);
    if (image->format() == QImage::Format_Indexed8){
        for (int x = 0; x < width; x++){
            for (int y = 0; y < height; y++){
                math::matrix<float> okno = getWindow(x, y, mask.rowno(), LChannel, mode);
                math::matrix<float> akumulator = join(okno, reflection(mask));
                float sum_aku = sum(akumulator);
                if (weight != 0){
                    sum_aku = sum_aku / weight;
                }
                if (sum_aku > 255){
                    sum_aku = 255;
                }
                if (sum_aku < 0){
                    sum_aku = 0;
                }
                newImage->setPixel(x, y, (int)floor(sum_aku));
            }
        }
    } else if (image->format() == QImage::Format_RGB32){
        for (int x = 0; x < width; x++){
            for (int y = 0; y < height; y++){
                math::matrix<float> okno = getWindow(x, y, mask.rowno(), RChannel, mode);
                math::matrix<float> akumulator = join(okno, reflection(mask));
                float sum_aku_red = sum(akumulator);
                okno = getWindow(x, y, mask.rowno(), GChannel, mode);
                akumulator = join(okno, reflection(mask));
                float sum_aku_green = sum(akumulator);

                okno = getWindow(x, y, mask.rowno(), BChannel, mode);
                akumulator = join(okno, reflection(mask));
                float sum_aku_blue = sum(akumulator);
                if (weight != 0)
                {
                    sum_aku_red = sum_aku_red / weight;
                    sum_aku_green = sum_aku_green / weight;
                    sum_aku_blue = sum_aku_blue / weight;
                }
                if (sum_aku_red > 255) {
                    sum_aku_red = 255;
                }
                if (sum_aku_red < 0){
                    sum_aku_red = 0;
                }
                if (sum_aku_green > 255) {
                    sum_aku_green = 255;
                }
                if (sum_aku_green < 0){
                    sum_aku_green = 0;
                }
                if (sum_aku_blue > 255) {
                    sum_aku_blue = 255;
                }
                if (sum_aku_blue < 0){
                    sum_aku_blue = 0;
                }
                QColor new_value = QColor((int)floor(sum_aku_red), (int)floor(sum_aku_green), (int)floor(sum_aku_blue));
                newImage->setPixel(x, y, new_value.rgb());
            }
        }
    }
    return newImage;
}
Пример #30
0
// simplex routine
// f is n dimensional function to be minimised, lower and upper are bounds of coordinates for initial vertices
// simplex_goal_size is tolerance for convergene and W is workspace for simplex routine of dimension n
// out termination the vector W->ce will contain coordinates for lowest vertex
int simplex(double f(gsl_vector* x),double lower, double upper, double simplex_goal_size, simplex_workspace* W)
{
	int steps = 0;
	double fp1, fp2, flo, fhi;
	// initialize system by generating vertices and
	// finding their function values
	simplex_generate(lower,upper,W);
	simplex_initialize(f,W);
	do
	{
		// make an update for higher, lower and centroid
		simplex_update(W);
		fhi = gsl_vector_get(W->fp,W->hi);
		flo = gsl_vector_get(W->fp,W->lo);
		// make reflection
		reflection(W);
		fp1 = f(W->p1);
		if (fp1 < flo)
		{
			// if f(reflected) < f(lower) attempt expansion
			expansion(W);
			fp2 = f(W->p2);
			if (fp2 < fp1)
			{
				// if f(expanded) < f(reflecred) accept expansion
				gsl_matrix_set_row(W->simplex,W->hi,W->p2);
				gsl_vector_set(W->fp,W->hi,fp2);
			}
			else
			{
				// if not, accept reflection
				gsl_matrix_set_row(W->simplex,W->hi,W->p1);
				gsl_vector_set(W->fp,W->hi,fp1);
			}
		}
		else
		{
			if (fp1 < fhi)
			{
				// if f(reflected) < f(higher) accept reflection
				gsl_matrix_set_row(W->simplex,W->hi,W->p1);
				gsl_vector_set(W->fp,W->hi,fp1);			
			}
			else
			{
				// if not, attempt contraction
				contraction(W);
				fp2 = f(W->p2);
				if (fp2 < fhi)
				{
					// if f(contracted) < f(higher), accept contraction
					gsl_matrix_set_row(W->simplex,W->hi,W->p2);
					gsl_vector_set(W->fp,W->hi,fp2);
				}
				else
				{
					// if not, we must be in a valley, perform reduction
					reduction(f,W);
				}
			}
		}
	steps++;
	// if simplex has reduced sufficiently, that is size(simplex) < simplex_goal_size
	// convergence is achieved. Return number of steps before convergence.
	} while (simplex_size(W) > simplex_goal_size);
	// copy lowest vertex to centroid vector
	gsl_matrix_get_row(W->ce,W->simplex,W->lo);
	return steps;
}