Example #1
0
Spectrum GridDensityMedium::Sample(const Ray &rWorld, Sampler &sampler,
                                   MemoryArena &arena,
                                   MediumInteraction *mi) const {
    Ray ray = WorldToMedium(
        Ray(rWorld.o, Normalize(rWorld.d), rWorld.tMax * rWorld.d.Length()));
    // Compute $[\tmin, \tmax]$ interval of _ray_'s overlap with medium bounds
    const Bounds3f b(Point3f(0, 0, 0), Point3f(1, 1, 1));
    Float tMin, tMax;
    if (!b.IntersectP(ray, &tMin, &tMax)) return Spectrum(1.f);

    // Run delta-tracking iterations to sample a medium interaction
    Float t = tMin;
    while (true) {
        t -= std::log(1 - sampler.Get1D()) * invMaxDensity;
        if (t >= tMax) break;
        if (Density(ray(t)) * invMaxDensity * sigma_t > sampler.Get1D()) {
            // Populate _mi_ with medium interaction information and return
            PhaseFunction *phase = ARENA_ALLOC(arena, HenyeyGreenstein)(g);
            *mi = MediumInteraction(rWorld(t), -rWorld.d, rWorld.time, this,
                                    phase);
            return sigma_s / sigma_t;
        }
    }
    return Spectrum(1.f);
}
Example #2
0
File: bauct.cpp Project: caomw/BBRL
double BAUCT::SimulateQ(uint state, QNODE& qnode, uint action)
{
    uint observation;
    double immediateReward, delayedReward = 0;

		uint ii = state*SA+action*S;
		Sampler* nextSSampler = SampFact.getTransitionSampler(pcounts+ii,state,action,S);
		observation =  nextSSampler->getNextStateSample();
		immediateReward = getReward(state,action,observation);
		delete nextSSampler;
		pcounts[state*SA+action*S+observation] += 1;
		bool terminal = false; //FIXME Assumes non-episodic tasks...

    History.Add(action, observation);
	    
		VNODE*& vnode = qnode.Child(observation);
    if (!vnode && !terminal && qnode.Value.GetCount() >= Params.ExpandCount)
        vnode = ExpandNode(); //&state);

    if (!terminal)
    {
        TreeDepth++;
        if (vnode)
            delayedReward = SimulateV(observation, vnode);
        else{
					delayedReward = Rollout(observation);
				}
        TreeDepth--;
    }

    double totalReward = immediateReward + Simulator.GetDiscount() * delayedReward;
    qnode.Value.Add(totalReward);
    return totalReward;
}
Example #3
0
 Value sample_value(
         const Shared & shared,
         rng_t & rng) const {
     Sampler sampler;
     sampler.init(shared, *this, rng);
     return sampler.eval(shared, rng);
 }
Example #4
0
Spectrum GridDensityMedium::Sample(const Ray &_ray, Sampler &sampler,
                                   MemoryArena &arena,
                                   MediumInteraction *mi) const {
    // Transform the ray into local coordinates and determine overlap interval
    // [_tMin, tMax_]
    const Bounds3f dataBounds(Point3f(0.f, 0.f, 0.f), Point3f(1.f, 1.f, 1.f));
    Ray ray = WorldToMedium(
        Ray(_ray.o, Normalize(_ray.d), _ray.tMax * _ray.d.Length()));
    Float tMin, tMax;
    if (!dataBounds.IntersectP(ray, &tMin, &tMax)) return Spectrum(1.f);
    tMin = std::max(tMin, (Float)0.f);
    tMax = std::min(tMax, ray.tMax);
    if (tMin >= tMax) return Spectrum(1.f);

    // Run Delta-Tracking iterations to sample a medium interaction
    Float t = tMin;
    while (true) {
        t -= std::log(1 - sampler.Get1D()) * invMaxDensity;
        if (t >= tMax) break;
        Float density = Density(ray(t));
        if (density * invMaxDensity * sigma_t > sampler.Get1D()) {
            // Populate _mi_ with medium interaction information and return
            PhaseFunction *phase = ARENA_ALLOC(arena, HenyeyGreenstein)(g);
            *mi = MediumInteraction(_ray(t), -_ray.d, _ray.time, this, phase);
            return sigma_s / sigma_t;
        }
    }
    return Spectrum(1.0f);
}
Example #5
0
    double integrate_sampling(
        const MDF&      mdf,
        const Sampler&  sampler,
        const size_t    sample_count)
    {
        double integral = 0.0;

        for (size_t i = 0; i < sample_count; ++i)
        {
            static const size_t Bases[] = { 2 };
            const Vector2d s = hammersley_sequence<double, 2>(Bases, i, sample_count);

            const Vector3d w = sampler.sample(s);
            const double pdf = sampler.pdf(w);
            const double cos_theta = w.y;

            const double value = mdf.evaluate(cos_theta);
            const double sample = value / pdf;

            integral += sample * cos_theta;
        }

        integral /= static_cast<double>(sample_count);

        return integral;
    }
Example #6
0
    bool SamplerScript::set_stack(ScriptObject* self, ClassFactoryClass* cf, const Sample& sample, SampleObject* sam)
    {
        if (sample.stack.depth > 0)
        {
            Toplevel* toplevel = self->toplevel();
            AvmCore* core = toplevel->core();
            Sampler* s = core->get_sampler();

            StackFrameClass* sfcc = (StackFrameClass*)cf->get_StackFrameClass();
            ArrayObject* stack = toplevel->arrayClass()->newArray(sample.stack.depth);
            StackTrace::Element* e = (StackTrace::Element*)sample.stack.trace;
            for(uint32_t i=0; i < sample.stack.depth; i++, e++)
            {
                StackFrameObject* sf = sfcc->constructObject();

                // at every allocation the sample buffer could overflow and the samples could be deleted
                // the StackTrace::Element pointer is a raw pointer into that buffer so we need to check
                // that its still around before dereferencing e
                uint32_t num;
                if (s->getSamples(num) == NULL)
                    return false;

                sf->setconst_name(e->name()); // NOT e->info()->name() because e->name() can be a fake name
                sf->setconst_file(e->filename());
                sf->setconst_line(e->linenum());
                sf->setconst_scriptID(static_cast<double>(e->functionId()));

                stack->setUintProperty(i, sf->atom());
            }
            sam->setconst_stack(stack);
        }
        return true;
    }
    void MidiInputPort::DispatchProgramChange(uint8_t Program, uint MidiChannel) {
        if (!pDevice || !pDevice->pSampler) {
            std::cerr << "MidiInputPort: ERROR, no sampler instance to handle program change."
                      << "This is a bug, please report it!\n" << std::flush;
            return;
        }

        Sampler*        pSampler        = (Sampler*) pDevice->pSampler;
        SamplerChannel* pSamplerChannel = pSampler->GetSamplerChannel(Program);
        if (!pSamplerChannel) return;

        EngineChannel* pEngineChannel = pSamplerChannel->GetEngineChannel();
        if (!pEngineChannel) return;

        // disconnect from the engine channel which was connected by the last PC event
        if (pPreviousProgramChangeEngineChannel)
            Disconnect(pPreviousProgramChangeEngineChannel);

        // now connect to the new engine channel and remember it
        try {
            Connect(pEngineChannel, (midi_chan_t) MidiChannel);
            pPreviousProgramChangeEngineChannel = pEngineChannel;
        }
        catch (...) { /* NOOP */ }
    }
Example #8
0
  void SampleRenderer::render_tile(CtxG&, Recti tile_rect, 
      Recti tile_film_rect, Film& tile_film, Sampler& sampler) const
  {
    StatTimer t(TIMER_RENDER_TILE);
    Vec2 film_res(float(this->film->x_res), float(this->film->y_res));

    for(int32_t y = tile_rect.p_min.y; y < tile_rect.p_max.y; ++y) {
      for(int32_t x = tile_rect.p_min.x; x < tile_rect.p_max.x; ++x) {
        sampler.start_pixel();
        for(uint32_t s = 0; s < sampler.samples_per_pixel; ++s) {
          sampler.start_pixel_sample();

          Vec2 pixel_pos = sampler.get_sample_2d(this->pixel_pos_idx);
          Vec2 film_pos = Vec2(float(x), float(y)) + pixel_pos;
          Ray ray(this->scene->camera->cast_ray(film_res, film_pos));

          Spectrum radiance = this->get_radiance(*this->scene, ray, 0, sampler);
          assert(is_finite(radiance));
          assert(is_nonnegative(radiance));
          if(is_finite(radiance) && is_nonnegative(radiance)) {
            Vec2 tile_film_pos = film_pos -
              Vec2(float(tile_film_rect.p_min.x), float(tile_film_rect.p_min.y));
            tile_film.add_sample(tile_film_pos, radiance);
          }
        }
      }
    }
  }
Example #9
0
// Integrator Utility Functions
Spectrum UniformSampleAllLights(const Interaction &it, const Scene &scene,
                                MemoryArena &arena, Sampler &sampler,
                                const std::vector<int> &nLightSamples,
                                bool handleMedia) {
    ProfilePhase p(Prof::DirectLighting);
    Spectrum L(0.f);
    for (size_t j = 0; j < scene.lights.size(); ++j) {
        // Accumulate contribution of _j_th light to _L_
        const std::shared_ptr<Light> &light = scene.lights[j];
        int nSamples = nLightSamples[j];
        const Point2f *uLightArray = sampler.Get2DArray(nSamples);
        const Point2f *uScatteringArray = sampler.Get2DArray(nSamples);
        if (!uLightArray || !uScatteringArray) {
            // Use a single sample for illumination from _light_
            Point2f uLight = sampler.Get2D();
            Point2f uScattering = sampler.Get2D();
            L += EstimateDirect(it, uScattering, *light, uLight, scene, sampler,
                                arena, handleMedia);
        } else {
            // Estimate direct lighting using sample arrays
            Spectrum Ld(0.f);
            for (int k = 0; k < nSamples; ++k)
                Ld += EstimateDirect(it, uScatteringArray[k], *light,
                                     uLightArray[k], scene, sampler, arena,
                                     handleMedia);
            L += Ld / nSamples;
        }
    }
    return L;
}
Example #10
0
int main(int argc, char** argv)
{
	CommandLineOptions options(argc, argv);
	Data::get_instance().load(options.get_data_file().c_str());
	Sampler<MyModel> sampler = setup<MyModel>(options);
	sampler.run();
	return 0;
}
Example #11
0
void ResourceManager::checkSamplerAllocation(GLuint sampler)
{
    if (sampler != 0 && !getSampler(sampler))
    {
        Sampler *samplerObject = new Sampler(sampler);
        mSamplerMap[sampler] = samplerObject;
        samplerObject->addRef();
    }
}
Example #12
0
int main(int argc, char** argv)
{
	Data::get_instance().load("data.txt");

	Sampler<MyModel> sampler = setup<MyModel>(argc, argv);
	sampler.run();

	return 0;
}
Example #13
0
unsigned int App::addSampler()
{
    samplers_.push_back(std::tr1::shared_ptr<Sampler>(new Sampler()));

    unsigned int index = samplers_.size() - 1;
    Sampler *sampler = samplers_[index].get();
    clutter_container_add_actor(CLUTTER_CONTAINER(stage_), sampler->getGenerator()->getRoot());
    return samplers_.size() - 1;
}
Example #14
0
void App::updateSpeed()
{
    std::vector<std::tr1::shared_ptr<Sampler> >::iterator iter;
    for (iter = samplers_.begin(); iter < samplers_.end(); ++iter)
    {
        Sampler *sampler = (*iter).get();
        sampler->getPlayer()->setSpeed(speed_);
    }
}
//--------------------------------------------------------------------------------------------------
/// 
//--------------------------------------------------------------------------------------------------
TEST(SamplerTest, Defaults)
{
    Sampler s;

    EXPECT_EQ(Sampler::REPEAT,                s.wrapModeS());
    EXPECT_EQ(Sampler::REPEAT,                s.wrapModeT());
    EXPECT_EQ(Sampler::NEAREST_MIPMAP_LINEAR, s.minFilter());
    EXPECT_EQ(Sampler::LINEAR,                s.magFilter());
}
void testSampler(){
	Sampler s;
	//s.testGenerator();
	for(int i = 0; i < 100; i++){
		float xyz[3];
		s.HemisphereSample( xyz );
		cout << "Hemisphere Sample: ";
		cout << xyz[0] << " " << xyz[1] << " " << xyz[2] << endl;
	}
}
Example #17
0
bool App::clearLast()
{
    // XXX if you edit this, also edit clearAll
    if (samplers_.size() == 0)
        return false;
    Sampler *sampler = samplers_[samplers_.size() - 1].get();
    clutter_container_remove_actor(CLUTTER_CONTAINER(stage_), sampler->getGenerator()->getRoot());
    samplers_.erase(samplers_.end() - 1);
    return true;
}
Example #18
0
int main(int argc, char** argv)
{
	Data::get_instance().load("Data/test_metadata.txt",
				"Data/test_image.txt", "Data/test_sigma.txt");

	Sampler<MyModel> sampler = setup<MyModel>(argc, argv);
	sampler.run();

	return 0;
}
Example #19
0
void ResourceManager::checkSamplerAllocation(GLuint sampler)
{
    if (sampler != 0 && !getSampler(sampler))
    {
        Sampler *samplerObject = new Sampler(sampler);
        mSamplerMap[sampler] = samplerObject;
        samplerObject->addRef();
        // Samplers cannot be created via Bind
    }
}
void rsi_ContextBindSampler(Context *rsc, uint32_t slot, RsSampler vs) {
    Sampler *s = static_cast<Sampler *>(vs);

    if (slot > RS_MAX_SAMPLER_SLOT) {
        ALOGE("Invalid sampler slot");
        return;
    }

    s->bindToContext(&rsc->mStateSampler, slot);
}
Example #21
0
//------------------------------------------------------------------------------
//!
Sampler*
SamplerList::getSampler( const ConstString& name )
{
   for( uint i = 0; i < _samplers.size(); ++i )
   {
      Sampler* s = _samplers[i].ptr();
      if( s->name() == name ) return s;
   }
   return NULL;
}
// RPFSamplerRendererTask Definitions
void RPFSamplerRendererTask::Run() {
    PBRT_STARTED_RENDERTASK(taskNum);
    // Get sub-_Sampler_ for _RPFSamplerRendererTask_
    Sampler *sampler = mainSampler->GetSubSampler(taskNum, taskCount);
    if (!sampler)
    {
        reporter.Update();
        PBRT_FINISHED_RENDERTASK(taskNum);
        return;
    }

    // Declare local variables used for rendering loop
    MemoryArena arena;
    RNG rng(taskNum);

    // Allocate space for samples and intersections
    int maxSamples = sampler->MaximumSampleCount();
    Sample *samples = origSample->Duplicate(maxSamples);
    RayDifferential *rays = new RayDifferential[maxSamples];
    Spectrum *Ls = new Spectrum[maxSamples];
    Spectrum *Ts = new Spectrum[maxSamples];
    Intersection *isects = new Intersection[maxSamples];

    // Get samples from _Sampler_ and update image
    int sampleCount;
    while ((sampleCount = sampler->GetMoreSamples(samples, rng)) > 0) {
        // Generate camera rays and compute radiance along rays
        for (int i = 0; i < sampleCount; ++i) {
            // Find camera ray for _sample[i]_
            PBRT_STARTED_GENERATING_CAMERA_RAY(&samples[i]);
            float rayWeight = camera->GenerateRayDifferential(samples[i], &rays[i]);
            rays[i].ScaleDifferentials(1.f / sqrtf(sampler->samplesPerPixel));
            PBRT_FINISHED_GENERATING_CAMERA_RAY(&samples[i], &rays[i], rayWeight);

            // Evaluate radiance along camera ray
            PBRT_STARTED_CAMERA_RAY_INTEGRATION(&rays[i], &samples[i]);
            if (visualizeObjectIds) {
                if (rayWeight > 0.f && scene->Intersect(rays[i], &isects[i])) {
                    // random shading based on shape id...
                	/* This renderer can optionally ignore the surface and volume integrators
					and randomly shade objects based on their shape and primitive id
					values.  This can be useful to visualize the tessellation of
					complex objects and search for problems in geometric models.*/
                    uint32_t ids[2] = { isects[i].shapeId, isects[i].primitiveId };
                    uint32_t h = hash((char *)ids, sizeof(ids));
                    float rgb[3] = { (h & 0xff), (h >> 8) & 0xff, (h >> 16) & 0xff };
                    Ls[i] = Spectrum::FromRGB(rgb);
                    Ls[i] /= 255.f;
                }
                else
                    Ls[i] = 0.f;
            }
            else {
            	//Normal shading based on rendering equation
				if (rayWeight > 0.f)
Example #23
0
Sampler* Material::createSampler(const string& id)
{
    Sampler* sampler = new Sampler(id.c_str());
    sampler->set("mipmap", "true");
    sampler->set("wrapS", CLAMP);
    sampler->set("wrapT", CLAMP);
    sampler->set(MIN_FILTER, LINEAR_MIPMAP_LINEAR);
    sampler->set(MAG_FILTER, LINEAR);
    _samplers.push_back(sampler);
    return sampler;
}
Example #24
0
    void SamplerScript::pauseSampling(ScriptObject* self)
    {
#ifdef DEBUGGER
        Sampler* s = self->core()->get_sampler();
        if (!s || !trusted(self))
            return;
        s->pauseSampling();
#else
        (void)self;
#endif
    }
Example #25
0
int main()
{
    // Prevent zombie processes
    struct sigaction sigchld_action;
    sigchld_action.sa_handler = SIG_DFL;
    sigchld_action.sa_flags = SA_NOCLDWAIT;
    sigaction(SIGCHLD, &sigchld_action, NULL);
    Sampler s;
    s.init();
    return 0;
}
void CommandBuffer::set_sampler(unsigned set, unsigned binding, const Sampler &sampler)
{
	VK_ASSERT(set < VULKAN_NUM_DESCRIPTOR_SETS);
	VK_ASSERT(binding < VULKAN_NUM_BINDINGS);
	if (sampler.get_cookie() == secondary_cookies[set][binding])
		return;

	auto &b = bindings[set][binding];
	b.image.sampler = sampler.get_sampler();
	dirty_sets |= 1u << set;
	secondary_cookies[set][binding] = sampler.get_cookie();
}
Example #27
0
void SamplerCollector::run() {
    butil::LinkNode<Sampler> root;
    int consecutive_nosleep = 0;
#ifndef UNIT_TEST
    PassiveStatus<double> cumulated_time(get_cumulated_time, this);
    bvar::PerSecond<bvar::PassiveStatus<double> > usage(
            "bvar_sampler_collector_usage", &cumulated_time, 10);
#endif
    while (!_stop) {
        int64_t abstime = butil::gettimeofday_us();
        Sampler* s = this->reset();
        if (s) {
            s->InsertBeforeAsList(&root);
        }
        int nremoved = 0;
        int nsampled = 0;
        for (butil::LinkNode<Sampler>* p = root.next(); p != &root;) {
            // We may remove p from the list, save next first.
            butil::LinkNode<Sampler>* saved_next = p->next();
            Sampler* s = p->value();
            s->_mutex.lock();
            if (!s->_used) {
                s->_mutex.unlock();
                p->RemoveFromList();
                delete s;
                ++nremoved;
            } else {
                s->take_sample();
                s->_mutex.unlock();
                ++nsampled;
            }
            p = saved_next;
        }
        bool slept = false;
        int64_t now = butil::gettimeofday_us();
        _cumulated_time_us += now - abstime;
        abstime += 1000000L;
        while (abstime > now) {
            ::usleep(abstime - now);
            slept = true;
            now = butil::gettimeofday_us();
        }
        if (slept) {
            consecutive_nosleep = 0;
        } else {            
            if (++consecutive_nosleep >= WARN_NOSLEEP_THRESHOLD) {
                consecutive_nosleep = 0;
                LOG(WARNING) << "bvar is busy at sampling for "
                             << WARN_NOSLEEP_THRESHOLD << " seconds!";
            }
        }
    }
}
Example #28
0
Sampler* Material::getSampler(const string& id) const
{
    for (vector<Sampler*>::const_iterator it = _samplers.begin(); it != _samplers.end(); ++it)
    {
        Sampler* sampler = *it;
        if (sampler->getId() == id)
        {
            return sampler;
        }
    }
    return NULL;
}
Example #29
0
/* Stop the sampler if we were currently sampling, do nothing otherwise or 
 * if sampler.stop == NULL */
static void samplerStop(MeasTaskState *measState)
{
	Sampler *sampler = &measState->sampler;
	StreamState *streamState = &measState->streamState;

	if (sampler->stop == NULL  ||  measState->measStatus != SAMPLING)
		return;

	switchStdout(streamState); /* Switch stdout to file */
	sampler->stop(&measState->samplerData, measState->samplerState);
	switchStdout(streamState); /* Switch stdout back */
}
Example #30
0
void App::clearAll()
{
    // XXX if you edit this, also edit clearLast
    std::vector<std::tr1::shared_ptr<Sampler> >::iterator iter;
    for (iter = samplers_.begin(); iter < samplers_.end(); ++iter)
    {
        Sampler *sampler = (*iter).get();
        // deletes the ClutterActors
        clutter_container_remove_actor(CLUTTER_CONTAINER(stage_), sampler->getGenerator()->getRoot());
    }
    samplers_.clear();
}