<commit_before>#include "memstorage.h"
#include "utils.h"
#include "compression.h"
#include <limits>
#include <algorithm>
#include <map>

using namespace memseries;
using namespace memseries::compression;
using namespace memseries::storage;
using memseries::utils::Range;

struct Chunk
{
    std::vector<uint8_t> _buffer_t;
	std::vector<uint8_t> _buffer_f;
	std::vector<uint8_t> _buffer_v;
    Range times;
    Range flags;
    Range values;
    CopmressedWriter c_writer;
    size_t count;
    Meas first;

    Time minTime,maxTime;

    Chunk(size_t size, Meas first_m):
        count(0),
        first(first_m)
    {
        minTime=std::numeric_limits<Time>::max();
        maxTime=std::numeric_limits<Time>::min();

		_buffer_t.resize(size);	std::fill(_buffer_t.begin(), _buffer_t.end(),0);
		_buffer_f.resize(size);	std::fill(_buffer_f.begin(), _buffer_f.end(), 0);
		_buffer_v.resize(size);	std::fill(_buffer_v.begin(), _buffer_v.end(), 0);

		times = Range{ _buffer_t.data(),_buffer_t.data() + sizeof(uint8_t)*size };
		flags = Range{ _buffer_f.data(),_buffer_f.data() + sizeof(uint8_t)*size };
		values = Range{ _buffer_v.data(),_buffer_v.data() + sizeof(uint8_t)*size };

        using compression::BinaryBuffer;
        c_writer = compression::CopmressedWriter( BinaryBuffer(times),
                                                  BinaryBuffer(values),
                                                  BinaryBuffer(flags));
        c_writer.append(first);
        minTime=std::min(minTime,first_m.time);
        maxTime=std::max(maxTime,first_m.time);
    }

    ~Chunk(){

    }
    bool append(const Meas&m)
    {
        auto t_f = this->c_writer.append(m);

        if (!t_f) {
            return false;
        }else{
            count++;

            minTime=std::min(minTime,m.time);
            maxTime=std::max(maxTime,m.time);
            return true;
        }
    }

    bool is_full()const { return c_writer.is_full(); }
};

typedef std::shared_ptr<Chunk>    Chunk_Ptr;
typedef std::list<Chunk_Ptr>      ChuncksList;
typedef std::map<Id, ChuncksList> ChunkMap;

class InnerReader: public Reader{
public:
    struct ReadChunk
    {
        size_t    count;
        Chunk_Ptr chunk;
        ReadChunk()=default;
        ReadChunk(const ReadChunk&other){
            count=other.count;
            chunk=other.chunk;
        }
        ReadChunk&operator=(const ReadChunk&other){
            if(this!=&other){
                count=other.count;
                chunk=other.chunk;
            }
            return *this;
        }
    };
    InnerReader(memseries::Flag flag, memseries::Time from, memseries::Time to):
        _chunks{},
        _flag(flag),
        _from(from),
        _to(to),
        _tp_readed(false)
    {
        is_time_point_reader = false;
        end=false;
    }

    void add(Chunk_Ptr c, size_t count){
        ReadChunk rc;
        rc.chunk = c;
        rc.count = count;
        this->_chunks[c->first.id].push_back(rc);
    }

    void add_tp(Chunk_Ptr c, size_t count){
        ReadChunk rc;
        rc.chunk = c;
        rc.count = count;
        this->_tp_chunks[c->first.id].push_back(rc);
    }

    bool isEnd() const override{
        return this->end && this->_tp_readed;
        //TODO replace
        //return this->_chunks.size() == 0 && this->_tp_chunks.size() == 0;
    }

    void readNext(storage::ReaderClb*clb) override {
        if (!_tp_readed) {
            this->readTimePoint(clb);
        }

        for (auto ch : _chunks) {
            for (size_t i = 0; i < ch.second.size(); i++) {
                auto cur_ch=ch.second[i].chunk;
                CopmressedReader crr(BinaryBuffer(cur_ch->times),
                                     BinaryBuffer(cur_ch->values),
                                     BinaryBuffer(cur_ch->flags),
                                     cur_ch->first);

                if (check_meas(ch.second[i].chunk->first)) {
                    auto sub=ch.second[i].chunk->first;
                    clb->call(sub);
                }

                for (size_t j = 0; j < ch.second[i].count; j++) {
                    auto sub = crr.read();
                    sub.id = ch.second[i].chunk->first.id;
                    if (check_meas(sub)) {
                        clb->call(sub);
                    }
                }

            }

        }
        end=true;
        //TODO replace
        //_chunks.clear();
    }

    void readTimePoint(storage::ReaderClb*clb){

        std::list<InnerReader::ReadChunk> to_read_chunks{};
        for (auto ch : _tp_chunks) {
            auto candidate = ch.second.front();

            for (size_t i = 0; i < ch.second.size(); i++) {
                auto cur_chunk=ch.second[i].chunk;
                if (candidate.chunk->first.time < cur_chunk->first.time){
                    candidate = ch.second[i];
                }
            }
            to_read_chunks.push_back(candidate);
        }

        for (auto ch : to_read_chunks) {
            CopmressedReader crr(BinaryBuffer(ch.chunk->times),
                                 BinaryBuffer(ch.chunk->values),
                                 BinaryBuffer(ch.chunk->flags),
                                 ch.chunk->first);

            Meas candidate;
            candidate = ch.chunk->first;
            for (size_t i = 0; i < ch.count; i++) {
                auto sub = crr.read();
                sub.id = ch.chunk->first.id;
                if ((sub.time <= _from) && (sub.time >= candidate.time)) {
                    candidate = sub;
                }
            }
            if (candidate.time <= _from) {
                clb->call(candidate);
            }
        }
        _tp_readed = true;
        //TODO replace
        //        _tp_chunks.clear();
    }

    bool is_time_point_reader;

    bool check_meas(const Meas&m)const{
        using utils::inInterval;

        if ((in_filter(_flag, m.flag))&&(inInterval(_from, _to, m.time))) {
            return true;
        }
        return false;
    }

    typedef std::vector<ReadChunk> ReadChuncksVector;
    typedef std::map<Id, ReadChuncksVector> ReadChunkMap;

    ReadChunkMap _chunks;
    ReadChunkMap _tp_chunks;
    memseries::Flag _flag;
    memseries::Time _from;
    memseries::Time _to;
    bool _tp_readed;
    //TODO remove end var
    bool end;
};

class MemoryStorage::Private
{
public:
    Private(size_t size):
        _size(size),
        _min_time(std::numeric_limits<memseries::Time>::max()),
        _max_time(std::numeric_limits<memseries::Time>::min())
    {}

    ~Private(){
        _chuncks.clear();
    }

    Time minTime(){return _min_time;}
    Time maxTime(){return _max_time;}

    Chunk_Ptr getFreeChunk(memseries::Id id){
        Chunk_Ptr resulted_chunk=nullptr;
        auto ch_iter=_chuncks.find(id);
        if (ch_iter != _chuncks.end()) {
            for (auto &v:ch_iter->second) {
                if (!v->is_full()) {
                    resulted_chunk = v;
                    break;
                }
            }
        }else {
            this->_chuncks[id] = ChuncksList{};
        }
        return resulted_chunk;
    }

    append_result append(const Meas& value){
        Chunk_Ptr chunk=this->getFreeChunk(value.id);

        bool need_sort = false;

        if (chunk == nullptr) {
            chunk = std::make_shared<Chunk>(_size, value);
            this->_chuncks[value.id].push_back(chunk);
            need_sort = true;
        }
        else {
            if (!chunk->append(value)) {
                chunk = std::make_shared<Chunk>(_size, value);
                this->_chuncks[value.id].push_back(chunk);
                need_sort = true;
            }
        }

        if (need_sort){
			this->_chuncks[value.id].sort(
				[](const Chunk_Ptr &l, const Chunk_Ptr &r) {
				return l->first.time < r->first.time;
			});
        }

        _min_time = std::min(_min_time, value.time);
        _max_time = std::max(_max_time, value.time);
        return memseries::append_result(1, 0);
    }

    append_result append(const Meas::PMeas begin, const size_t size){
        memseries::append_result result{};
        for (size_t i = 0; i < size; i++) {
            result = result + append(begin[i]);
        }
        return result;

    }

    std::shared_ptr<InnerReader> readInterval(const IdArray &ids, Flag flag, Time from, Time to){
        auto res= this->readInTimePoint(ids,flag,from);
        res->_from=from;
        res->_to=to;
        res->_flag=flag;
        for (auto ch : _chuncks) {
            if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) {
                continue;
            }
            for (auto &v:ch.second) {
                Chunk_Ptr cur_chunk = v;
                if ((utils::inInterval(from,to,cur_chunk->minTime))||
                        (utils::inInterval(from,to,cur_chunk->maxTime))){
                    res->add(cur_chunk, cur_chunk->count);
                }
            }

        }
        res->is_time_point_reader=false;
        return res;
    }

    std::shared_ptr<InnerReader> readInTimePoint(const IdArray &ids, Flag flag, Time time_point){
        auto res = std::make_shared<InnerReader>(flag, time_point, 0);
        for (auto ch : _chuncks) {
            if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) {
                continue;
            }
            for (auto&v: ch.second) {
                Chunk_Ptr cur_chunk = v;
                if(cur_chunk->minTime<time_point){
                    res->add_tp(cur_chunk, cur_chunk->count);
                }
            }

        }
        res->is_time_point_reader = true;
        return res;
    }

    size_t size()const { return _size; }
    size_t chunks_size()const { return _chuncks.size(); }
protected:
    size_t _size;

    ChunkMap _chuncks;
    Time _min_time,_max_time;
};

MemoryStorage::MemoryStorage(size_t size)
    :_Impl(new MemoryStorage::Private(size)){
}

MemoryStorage::~MemoryStorage(){
}

Time MemoryStorage::minTime(){
    return _Impl->minTime();
}

Time MemoryStorage::maxTime(){
    return _Impl->maxTime();
}

append_result MemoryStorage::append(const memseries::Meas &value){
    return _Impl->append(value);
}

append_result MemoryStorage::append(const memseries::Meas::PMeas begin, const size_t size){
    return _Impl->append(begin,size);
}

Reader_ptr MemoryStorage::readInterval(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time from, memseries::Time to){
    return _Impl->readInterval(ids,flag,from,to);
}

Reader_ptr  MemoryStorage::readInTimePoint(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time time_point){
    return _Impl->readInTimePoint(ids,flag,time_point);
}

size_t  MemoryStorage::size()const {
    return _Impl->size();
}

size_t  MemoryStorage::chunks_size()const {
    return _Impl->chunks_size();
}

<commit_msg>refact.<commit_after>#include "memstorage.h"
#include "utils.h"
#include "compression.h"
#include <limits>
#include <algorithm>
#include <map>

using namespace memseries;
using namespace memseries::compression;
using namespace memseries::storage;
using memseries::utils::Range;

struct Chunk
{
    std::vector<uint8_t> _buffer_t;
	std::vector<uint8_t> _buffer_f;
	std::vector<uint8_t> _buffer_v;
    Range times;
    Range flags;
    Range values;
    CopmressedWriter c_writer;
    size_t count;
    Meas first;

    Time minTime,maxTime;

    Chunk(size_t size, Meas first_m):
        count(0),
        first(first_m)
    {
        minTime=std::numeric_limits<Time>::max();
        maxTime=std::numeric_limits<Time>::min();

		_buffer_t.resize(size);	std::fill(_buffer_t.begin(), _buffer_t.end(),0);
		_buffer_f.resize(size);	std::fill(_buffer_f.begin(), _buffer_f.end(), 0);
		_buffer_v.resize(size);	std::fill(_buffer_v.begin(), _buffer_v.end(), 0);

		times = Range{ _buffer_t.data(),_buffer_t.data() + sizeof(uint8_t)*size };
		flags = Range{ _buffer_f.data(),_buffer_f.data() + sizeof(uint8_t)*size };
		values = Range{ _buffer_v.data(),_buffer_v.data() + sizeof(uint8_t)*size };

        using compression::BinaryBuffer;
        c_writer = compression::CopmressedWriter( BinaryBuffer(times),
                                                  BinaryBuffer(values),
                                                  BinaryBuffer(flags));
        c_writer.append(first);
        minTime=std::min(minTime,first_m.time);
        maxTime=std::max(maxTime,first_m.time);
    }

    ~Chunk(){

    }
    bool append(const Meas&m)
    {
        auto t_f = this->c_writer.append(m);

        if (!t_f) {
            return false;
        }else{
            count++;

            minTime=std::min(minTime,m.time);
            maxTime=std::max(maxTime,m.time);
            return true;
        }
    }

    bool is_full()const { return c_writer.is_full(); }
};

typedef std::shared_ptr<Chunk>    Chunk_Ptr;
typedef std::list<Chunk_Ptr>      ChuncksList;
typedef std::map<Id, ChuncksList> ChunkMap;

class InnerReader: public Reader{
public:
    struct ReadChunk
    {
        size_t    count;
        Chunk_Ptr chunk;
        ReadChunk()=default;
        ReadChunk(const ReadChunk&other){
            count=other.count;
            chunk=other.chunk;
        }
        ReadChunk&operator=(const ReadChunk&other){
            if(this!=&other){
                count=other.count;
                chunk=other.chunk;
            }
            return *this;
        }
    };
    InnerReader(memseries::Flag flag, memseries::Time from, memseries::Time to):
        _chunks{},
        _flag(flag),
        _from(from),
        _to(to),
        _tp_readed(false)
    {
        is_time_point_reader = false;
        end=false;
    }

    void add(Chunk_Ptr c, size_t count){
        ReadChunk rc;
        rc.chunk = c;
        rc.count = count;
        this->_chunks[c->first.id].push_back(rc);
    }

    void add_tp(Chunk_Ptr c, size_t count){
        ReadChunk rc;
        rc.chunk = c;
        rc.count = count;
        this->_tp_chunks[c->first.id].push_back(rc);
    }

    bool isEnd() const override{
        return this->end && this->_tp_readed;
        //TODO replace
        //return this->_chunks.size() == 0 && this->_tp_chunks.size() == 0;
    }

    void readNext(storage::ReaderClb*clb) override {
        if (!_tp_readed) {
            this->readTimePoint(clb);
        }

        for (auto ch : _chunks) {
            for (size_t i = 0; i < ch.second.size(); i++) {
                auto cur_ch=ch.second[i].chunk;
                CopmressedReader crr(BinaryBuffer(cur_ch->times),
                                     BinaryBuffer(cur_ch->values),
                                     BinaryBuffer(cur_ch->flags),
                                     cur_ch->first);

                if (check_meas(ch.second[i].chunk->first)) {
                    auto sub=ch.second[i].chunk->first;
                    clb->call(sub);
                }

                for (size_t j = 0; j < ch.second[i].count; j++) {
                    auto sub = crr.read();
                    sub.id = ch.second[i].chunk->first.id;
                    if (check_meas(sub)) {
                        clb->call(sub);
                    }
                }

            }

        }
        end=true;
        //TODO replace
        //_chunks.clear();
    }

    void readTimePoint(storage::ReaderClb*clb){

        std::list<InnerReader::ReadChunk> to_read_chunks{};
        for (auto ch : _tp_chunks) {
            auto candidate = ch.second.front();

            for (size_t i = 0; i < ch.second.size(); i++) {
                auto cur_chunk=ch.second[i].chunk;
                if (candidate.chunk->first.time < cur_chunk->first.time){
                    candidate = ch.second[i];
                }
            }
            to_read_chunks.push_back(candidate);
        }

        for (auto ch : to_read_chunks) {
            CopmressedReader crr(BinaryBuffer(ch.chunk->times),
                                 BinaryBuffer(ch.chunk->values),
                                 BinaryBuffer(ch.chunk->flags),
                                 ch.chunk->first);

            Meas candidate;
            candidate = ch.chunk->first;
            for (size_t i = 0; i < ch.count; i++) {
                auto sub = crr.read();
                sub.id = ch.chunk->first.id;
                if ((sub.time <= _from) && (sub.time >= candidate.time)) {
                    candidate = sub;
                }
            }
            if (candidate.time <= _from) {
                clb->call(candidate);
            }
        }
        _tp_readed = true;
        //TODO replace
        //        _tp_chunks.clear();
    }

    bool is_time_point_reader;

    bool check_meas(const Meas&m)const{
        using utils::inInterval;

        if ((in_filter(_flag, m.flag))&&(inInterval(_from, _to, m.time))) {
            return true;
        }
        return false;
    }

    typedef std::vector<ReadChunk> ReadChuncksVector;
    typedef std::map<Id, ReadChuncksVector> ReadChunkMap;

    ReadChunkMap _chunks;
    ReadChunkMap _tp_chunks;
    memseries::Flag _flag;
    memseries::Time _from;
    memseries::Time _to;
    bool _tp_readed;
    //TODO remove end var
    bool end;
};

class MemoryStorage::Private
{
public:
    Private(size_t size):
        _size(size),
        _min_time(std::numeric_limits<memseries::Time>::max()),
        _max_time(std::numeric_limits<memseries::Time>::min())
    {}

    ~Private(){
        _chuncks.clear();
    }

    Time minTime(){return _min_time;}
    Time maxTime(){return _max_time;}

    Chunk_Ptr getFreeChunk(memseries::Id id){
        Chunk_Ptr resulted_chunk=nullptr;
        auto ch_iter=_chuncks.find(id);
        if (ch_iter != _chuncks.end()) {
            for (auto &v:ch_iter->second) {
                if (!v->is_full()) {
                    resulted_chunk = v;
                    break;
                }
            }
        }else {
            this->_chuncks[id] = ChuncksList{};
        }
        return resulted_chunk;
    }

    append_result append(const Meas& value){
        Chunk_Ptr chunk=this->getFreeChunk(value.id);

        bool need_sort = false;

        if (chunk == nullptr) {
            chunk = std::make_shared<Chunk>(_size, value);
            this->_chuncks[value.id].push_back(chunk);
            need_sort = true;
        }
        else {
            if (!chunk->append(value)) {
                chunk = std::make_shared<Chunk>(_size, value);
                this->_chuncks[value.id].push_back(chunk);
                need_sort = true;
            }
        }

        if (need_sort){
			this->_chuncks[value.id].sort(
				[](const Chunk_Ptr &l, const Chunk_Ptr &r) {
				return l->first.time < r->first.time;
			});
        }

        _min_time = std::min(_min_time, value.time);
        _max_time = std::max(_max_time, value.time);
        return memseries::append_result(1, 0);
    }

    append_result append(const Meas::PMeas begin, const size_t size){
        memseries::append_result result{};
        for (size_t i = 0; i < size; i++) {
            result = result + append(begin[i]);
        }
        return result;

    }

    std::shared_ptr<InnerReader> readInterval(const IdArray &ids, Flag flag, Time from, Time to){
        auto res= this->readInTimePoint(ids,flag,from);
        res->_from=from;
        res->_to=to;
        res->_flag=flag;
        for (auto ch : _chuncks) {
            if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) {
                continue;
            }
			for (auto &cur_chunk : ch.second) {
				if ((utils::inInterval(from, to, cur_chunk->minTime)) ||
					(utils::inInterval(from, to, cur_chunk->maxTime))) {
					res->add(cur_chunk, cur_chunk->count);
				}
			}

        }
        res->is_time_point_reader=false;
        return res;
    }

    std::shared_ptr<InnerReader> readInTimePoint(const IdArray &ids, Flag flag, Time time_point){
        auto res = std::make_shared<InnerReader>(flag, time_point, 0);
        for (auto ch : _chuncks) {
            if ((ids.size() != 0) && (std::find(ids.begin(), ids.end(), ch.first) == ids.end())) {
                continue;
            }
            for (auto&cur_chunk : ch.second) {
                if(cur_chunk->minTime<time_point){
                    res->add_tp(cur_chunk, cur_chunk->count);
                }
            }

        }
        res->is_time_point_reader = true;
        return res;
    }

    size_t size()const { return _size; }
    size_t chunks_size()const { return _chuncks.size(); }
protected:
    size_t _size;

    ChunkMap _chuncks;
    Time _min_time,_max_time;
};

MemoryStorage::MemoryStorage(size_t size)
    :_Impl(new MemoryStorage::Private(size)){
}

MemoryStorage::~MemoryStorage(){
}

Time MemoryStorage::minTime(){
    return _Impl->minTime();
}

Time MemoryStorage::maxTime(){
    return _Impl->maxTime();
}

append_result MemoryStorage::append(const memseries::Meas &value){
    return _Impl->append(value);
}

append_result MemoryStorage::append(const memseries::Meas::PMeas begin, const size_t size){
    return _Impl->append(begin,size);
}

Reader_ptr MemoryStorage::readInterval(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time from, memseries::Time to){
    return _Impl->readInterval(ids,flag,from,to);
}

Reader_ptr  MemoryStorage::readInTimePoint(const memseries::IdArray &ids, memseries::Flag flag, memseries::Time time_point){
    return _Impl->readInTimePoint(ids,flag,time_point);
}

size_t  MemoryStorage::size()const {
    return _Impl->size();
}

size_t  MemoryStorage::chunks_size()const {
    return _Impl->chunks_size();
}

<|endoftext|>


<commit_before>#include <test/unit/math/test_ad.hpp>

TEST(MathMixMatFun, logSoftmax) {
  auto f = [](const auto& x) { return stan::math::log_softmax(x); };
  Eigen::VectorXd x0(0);  // error case
  stan::test::expect_ad(f, x0);

  Eigen::VectorXd x1(1);
  x1 << 0;
  stan::test::expect_ad(f, x1);

  Eigen::VectorXd x2(2);
  x2 << -1, 1;
  stan::test::expect_ad(f, x2);

  Eigen::VectorXd x3(3);
  x3 << -1, 1, 10;
  stan::test::expect_ad(f, x3);

  Eigen::VectorXd x3b(3);
  x3 << 0, 1, 2;
  stan::test::expect_ad(f, x3b);

  Eigen::VectorXd x3c(3);
  x3 << 2, 1, 1;
  stan::test::expect_ad(f, x3c);
}
<commit_msg>fixed inits in log_softmax test<commit_after>#include <test/unit/math/test_ad.hpp>

TEST(MathMixMatFun, logSoftmax) {
  auto f = [](const auto& x) { return stan::math::log_softmax(x); };
  Eigen::VectorXd x0(0);  // error case
  stan::test::expect_ad(f, x0);

  Eigen::VectorXd x1(1);
  x1 << 0;
  stan::test::expect_ad(f, x1);

  Eigen::VectorXd x2(2);
  x2 << -1, 1;
  stan::test::expect_ad(f, x2);

  Eigen::VectorXd x3(3);
  x3 << -1, 1, 10;
  stan::test::expect_ad(f, x3);

  Eigen::VectorXd x3b(3);
  x3b << 0, 1, 2;
  stan::test::expect_ad(f, x3b);

  Eigen::VectorXd x3c(3);
  x3c << 2, 1, 1;
  stan::test::expect_ad(f, x3c);
}
<|endoftext|>


<commit_before>#include "catch.hpp"

#include <mapnik/memory_datasource.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/map.hpp>
#include <mapnik/params.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/geometry/geometry_type.hpp>
#include <mapnik/agg_renderer.hpp>

class test_datasource : public mapnik::memory_datasource
{
public:
    test_datasource(mapnik::box2d<double> const& expected_query_bbox)
        : expected_query_bbox_(expected_query_bbox),
          mapnik::memory_datasource(prepare_params())
    {
    }

    virtual mapnik::featureset_ptr features(mapnik::query const& q) const
    {
        mapnik::box2d<double> const& actual_bbox = q.get_bbox();
        REQUIRE(actual_bbox.minx() == Approx(expected_query_bbox_.minx()));
        REQUIRE(actual_bbox.miny() == Approx(expected_query_bbox_.miny()));
        REQUIRE(actual_bbox.maxx() == Approx(expected_query_bbox_.maxx()));
        REQUIRE(actual_bbox.maxy() == Approx(expected_query_bbox_.maxy()));
        return mapnik::memory_datasource::features(q);
    }

private:
    mapnik::parameters prepare_params() const
    {
        mapnik::parameters params;
        params["type"] = "memory";
        return params;
    }

    mapnik::box2d<double> expected_query_bbox_;
};

TEST_CASE("feature_style_processor: buffer-size with scale-factor") {

SECTION("query extent with buffer-size should not be affected by scale-factor") {

    const mapnik::box2d<double> expected_query_bbox(-0.5, -0.5, 1.5, 1.5);

    using datasource_ptr = std::shared_ptr<test_datasource>;
    datasource_ptr datasource = std::make_shared<test_datasource>(
        expected_query_bbox);
    mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
    {
        mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx, 2));
        mapnik::geometry::line_string<double> path;
        path.emplace_back(-10, -10);
        path.emplace_back(10, 10);
        feature->set_geometry(std::move(path));
        datasource->push(feature);
    }

    mapnik::Map map(256, 256);
    map.set_buffer_size(128);

    mapnik::feature_type_style lines_style;
    mapnik::rule rule;
    mapnik::line_symbolizer line_sym;
    rule.append(std::move(line_sym));
    lines_style.add_rule(std::move(rule));
    map.insert_style("lines", std::move(lines_style));

    mapnik::layer lyr("layer");
    lyr.set_datasource(datasource);
    lyr.add_style("lines");
    map.add_layer(lyr);

    const mapnik::box2d<double> map_extent(0, 0, 1, 1);
    map.zoom_to_box(map_extent);

    {
        mapnik::image_rgba8 image(map.width(), map.height());
        mapnik::agg_renderer<mapnik::image_rgba8> ren(map, image);
        ren.apply();
    }

    {
        // Rendering with scale-factor 2.0 should query data
        // with the same extent as with scale-factor 1.0.
        map.resize(map.width() * 2, map.height() * 2);
        mapnik::image_rgba8 image(map.width(), map.height());
        mapnik::agg_renderer<mapnik::image_rgba8> ren(map, image, 2.0);
        ren.apply();
    }
}

}

<commit_msg>fix compiler warning (warning: field 'expected_query_bbox_' will be initialized after base 'mapnik::memory_datasource' [-Wreorder])<commit_after>#include "catch.hpp"

#include <mapnik/memory_datasource.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/feature_factory.hpp>
#include <mapnik/map.hpp>
#include <mapnik/params.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/feature_type_style.hpp>
#include <mapnik/symbolizer.hpp>
#include <mapnik/geometry/geometry_type.hpp>
#include <mapnik/agg_renderer.hpp>

class test_datasource : public mapnik::memory_datasource
{
public:
    test_datasource(mapnik::box2d<double> const& expected_query_bbox)
        : mapnik::memory_datasource(prepare_params()),
          expected_query_bbox_(expected_query_bbox)
    {
    }

    virtual mapnik::featureset_ptr features(mapnik::query const& q) const
    {
        mapnik::box2d<double> const& actual_bbox = q.get_bbox();
        REQUIRE(actual_bbox.minx() == Approx(expected_query_bbox_.minx()));
        REQUIRE(actual_bbox.miny() == Approx(expected_query_bbox_.miny()));
        REQUIRE(actual_bbox.maxx() == Approx(expected_query_bbox_.maxx()));
        REQUIRE(actual_bbox.maxy() == Approx(expected_query_bbox_.maxy()));
        return mapnik::memory_datasource::features(q);
    }

private:
    mapnik::parameters prepare_params() const
    {
        mapnik::parameters params;
        params["type"] = "memory";
        return params;
    }

    mapnik::box2d<double> expected_query_bbox_;
};

TEST_CASE("feature_style_processor: buffer-size with scale-factor") {

SECTION("query extent with buffer-size should not be affected by scale-factor") {

    const mapnik::box2d<double> expected_query_bbox(-0.5, -0.5, 1.5, 1.5);

    using datasource_ptr = std::shared_ptr<test_datasource>;
    datasource_ptr datasource = std::make_shared<test_datasource>(
        expected_query_bbox);
    mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>();
    {
        mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx, 2));
        mapnik::geometry::line_string<double> path;
        path.emplace_back(-10, -10);
        path.emplace_back(10, 10);
        feature->set_geometry(std::move(path));
        datasource->push(feature);
    }

    mapnik::Map map(256, 256);
    map.set_buffer_size(128);

    mapnik::feature_type_style lines_style;
    mapnik::rule rule;
    mapnik::line_symbolizer line_sym;
    rule.append(std::move(line_sym));
    lines_style.add_rule(std::move(rule));
    map.insert_style("lines", std::move(lines_style));

    mapnik::layer lyr("layer");
    lyr.set_datasource(datasource);
    lyr.add_style("lines");
    map.add_layer(lyr);

    const mapnik::box2d<double> map_extent(0, 0, 1, 1);
    map.zoom_to_box(map_extent);

    {
        mapnik::image_rgba8 image(map.width(), map.height());
        mapnik::agg_renderer<mapnik::image_rgba8> ren(map, image);
        ren.apply();
    }

    {
        // Rendering with scale-factor 2.0 should query data
        // with the same extent as with scale-factor 1.0.
        map.resize(map.width() * 2, map.height() * 2);
        mapnik::image_rgba8 image(map.width(), map.height());
        mapnik::agg_renderer<mapnik::image_rgba8> ren(map, image, 2.0);
        ren.apply();
    }
}

}
<|endoftext|>


<commit_before>//
// Created by horacio on 3/12/17.
//
#include "stdafx.h"
#include "Crypto.h"
#include "DotIO.h"
#include "DotIOInventory.h"
#include "Matematicas.h"

DotIO::DotIO(int UserIndex, const std::string &Name, eRaza UserRaza, eGenero UserSexo,
                               eClass UserClase,
                               const std::string &UserEmail,
                               eCiudad Hogar, int Head) {
    this->UserIndex = UserIndex;
    this->Name = Name;
    this->UserRaza = UserRaza;
    this->UserSexo = UserSexo;
    this->UserClase = UserClase;
    this->UserEmail = UserEmail;
    this->Hogar = Hogar;
    this->Head = Head;
}

void DotIO::setupUser() {
    loadUserIni();
    loadUserReputacion();
    loadUserFlags();

    loadUserStats();

    loadUserInventoryItems(); // << ITEMS

    loadUserInventory();

    loadUserHechizos();

    updateUserPosition();
    updateUserLevel();

    int i;
}

void DotIO::addSpell(int number) {
    int lastSlot = 16;
    while (UserList[UserIndex].Stats.UserHechizos[lastSlot] != 0) {
        lastSlot--;
    }
    UserList[UserIndex].Stats.UserHechizos[lastSlot] = number;
}

void DotIO::loadUserHechizos() {

    if (UserClase == eClass_Thief || UserClase == eClass_Warrior || UserClase == eClass_Hunter){
        return;
    }
    addSpell(10); // remover paralisis
    addSpell(24); // inmovilizar
    if (UserClase == eClass_Cleric || UserClase == eClass_Mage || UserClase == eClass_Bard || UserClase == eClass_Druid){
        addSpell(25); // apocalipsis
    }
    addSpell(23); // descargar electrica
    addSpell(15); // tormenta
    addSpell(8); // misil magico
    //addSpell(14); // invisibilidad
    addSpell(5); // curar heridas graves
    addSpell(18); // celeridad
    addSpell(20); // fuerza

}

void DotIO::loadUserReputacion() {
    UserList[UserIndex].Reputacion.AsesinoRep = 0;
    UserList[UserIndex].Reputacion.BandidoRep = 0;
    UserList[UserIndex].Reputacion.BurguesRep = 0;
    UserList[UserIndex].Reputacion.LadronesRep = 0;
    UserList[UserIndex].Reputacion.NobleRep = 1000;
    UserList[UserIndex].Reputacion.PlebeRep = 30;
    UserList[UserIndex].Reputacion.Promedio = 30 / 6;
}

void DotIO::loadUserFlags() {
    UserList[UserIndex].flags.Muerto = 0;
    UserList[UserIndex].flags.Escondido = 0;
    UserList[UserIndex].flags.Hambre = 0;
    UserList[UserIndex].flags.Sed = 0;
    UserList[UserIndex].flags.Desnudo = 0;
    UserList[UserIndex].flags.Navegando = 0;
    UserList[UserIndex].flags.Envenenado = 0;
    UserList[UserIndex].flags.Paralizado = 0;
    UserList[UserIndex].flags.lastMap = 0;
}

void DotIO::loadUserIni() {
    int LoopC;

    UserList[UserIndex].Name = Name;
    UserList[UserIndex].clase = UserClase;
    UserList[UserIndex].raza = UserRaza;
    UserList[UserIndex].Genero = UserSexo;
    UserList[UserIndex].email = UserEmail;
    UserList[UserIndex].Hogar = Hogar;

    UserList[UserIndex].Char.heading = eHeading_SOUTH;

    DarCuerpo(UserIndex); // <-- !!!
    UserList[UserIndex].Char.Head = Head;

    UserList[UserIndex].OrigChar = UserList[UserIndex].Char;

    UserList[UserIndex].LogOnTime = vb6::Now();
    UserList[UserIndex].UpTime = 0;
    UserList[UserIndex].desc = "";

    UserList[UserIndex].Faccion.ArmadaReal = 0;
    UserList[UserIndex].Faccion.CiudadanosMatados = 0;
    UserList[UserIndex].Faccion.CriminalesMatados = 0;
    UserList[UserIndex].Faccion.FuerzasCaos = 0;
    UserList[UserIndex].Faccion.FechaIngreso = "No ingresó a ninguna Facción";
    UserList[UserIndex].Faccion.RecibioArmaduraCaos = 0;
    UserList[UserIndex].Faccion.RecibioArmaduraReal = 0;
    UserList[UserIndex].Faccion.RecibioExpInicialCaos = 0;
    UserList[UserIndex].Faccion.RecibioExpInicialReal = 0;
    UserList[UserIndex].Faccion.RecompensasCaos = 0;
    UserList[UserIndex].Faccion.RecompensasReal = 0;
    UserList[UserIndex].Faccion.Reenlistadas = 0;
    UserList[UserIndex].Faccion.NivelIngreso = 0;
    UserList[UserIndex].Faccion.MatadosIngreso = 0;
    UserList[UserIndex].Faccion.NextRecompensa = 0;

    UserList[UserIndex].Counters.Pena = 0;
    UserList[UserIndex].Counters.AsignedSkills = 0;

    UserList[UserIndex].GuildIndex = 0;

    UserList[UserIndex].NroMascotas = 0;
    for (LoopC = (1); LoopC <= (MAXMASCOTAS); LoopC++) {
        UserList[UserIndex].MascotasType[LoopC] = 0;
    }
}

void DotIO::loadUserStats() {
    int i, LoopC;
    UserList[UserIndex].Stats.UserAtributos[eAtributos_Fuerza] =
            18 + ModRaza[UserRaza].Fuerza;
    UserList[UserIndex].Stats.UserAtributos[eAtributos_Agilidad] =
            18 + ModRaza[UserRaza].Agilidad;
    UserList[UserIndex].Stats.UserAtributos[eAtributos_Inteligencia] =
            18 + ModRaza[UserRaza].Inteligencia;
    UserList[UserIndex].Stats.UserAtributos[eAtributos_Carisma] =
            18 + ModRaza[UserRaza].Carisma;
    UserList[UserIndex].Stats.UserAtributos[eAtributos_Constitucion] =
            18 + ModRaza[UserRaza].Constitucion;

    for (i = (1); i <= (NUMATRIBUTOS); i++) {
        UserList[UserIndex].Stats.UserAtributosBackUP[i] = UserList[UserIndex].Stats.UserAtributos[i];
    }

    for (i = (1); i <= (NUMSKILLS); i++) {
        UserList[UserIndex].Stats.UserSkills[i] = 100;
        UserList[UserIndex].Stats.EluSkills[i] = 0;
        UserList[UserIndex].Stats.ExpSkills[i] = 0;
    }
    UserList[UserIndex].Stats.SkillPts = 0;

    int MiInt;
    MiInt = RandomNumber(1, UserList[UserIndex].Stats.UserAtributos[eAtributos_Constitucion] / 3);

    UserList[UserIndex].Stats.MaxHp = 15 + MiInt;
    UserList[UserIndex].Stats.MinHp = 15 + MiInt;

    MiInt = RandomNumber(1, UserList[UserIndex].Stats.UserAtributos[eAtributos_Agilidad] / 6);
    if (MiInt == 1) {
        MiInt = 2;
    }

    UserList[UserIndex].Stats.MaxSta = 20 * MiInt;
    UserList[UserIndex].Stats.MinSta = 20 * MiInt;

    UserList[UserIndex].Stats.MaxAGU = 100;
    UserList[UserIndex].Stats.MinAGU = 100;

    UserList[UserIndex].Stats.MaxHam = 100;
    UserList[UserIndex].Stats.MinHam = 100;

    if (UserClase == eClass_Mage) {
        MiInt = UserList[UserIndex].Stats.UserAtributos[eAtributos_Inteligencia] * 3;
        UserList[UserIndex].Stats.MaxMAN = MiInt;
        UserList[UserIndex].Stats.MinMAN = MiInt;
    } else if (UserClase == eClass_Cleric || UserClase == eClass_Druid || UserClase == eClass_Bard
               || UserClase == eClass_Assasin) {
        UserList[UserIndex].Stats.MaxMAN = 50;
        UserList[UserIndex].Stats.MinMAN = 50;
        /* 'Mana Inicial del Bandido (ToxicWaste) */
    } else if (UserClase == eClass_Bandit) {
        UserList[UserIndex].Stats.MaxMAN = 50;
        UserList[UserIndex].Stats.MinMAN = 50;
    } else {
        UserList[UserIndex].Stats.MaxMAN = 0;
        UserList[UserIndex].Stats.MinMAN = 0;
    }

    UserList[UserIndex].Stats.MaxHIT = 2;
    UserList[UserIndex].Stats.MinHIT = 1;

    UserList[UserIndex].Stats.GLD = 0;
    UserList[UserIndex].Stats.Banco = 0;

    UserList[UserIndex].Stats.Exp = 0;
    UserList[UserIndex].Stats.ELU = 300;
    UserList[UserIndex].Stats.ELV = 1;

    UserList[UserIndex].Stats.UsuariosMatados = 0;
    UserList[UserIndex].Stats.NPCsMuertos = 0;
}

void DotIO::loadUserInventoryItems() {
    DotIOInventory inventory(UserIndex, Name, UserRaza, UserSexo, UserClase, UserEmail, Hogar, Head);
    inventory.initializeInventory();
}

void DotIO::loadUserInventory() {
    int i, LoopC;
    struct ObjData Obj;

    /* 'Obtiene el indice-objeto del arma */
    if (UserList[UserIndex].Invent.WeaponEqpSlot > 0) {
        UserList[UserIndex].Invent.WeaponEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.WeaponEqpSlot].ObjIndex;
        UserList[UserIndex].Char.WeaponAnim = GetWeaponAnim(UserIndex,
                                                            UserList[UserIndex].Invent.WeaponEqpObjIndex);
    }

    /* 'Obtiene el indice-objeto del armadura */
    if (UserList[UserIndex].Invent.ArmourEqpSlot > 0) {
        Obj = ObjData[UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.ArmourEqpSlot].ObjIndex];
        UserList[UserIndex].Char.body = Obj.Ropaje;

        UserList[UserIndex].Invent.ArmourEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.ArmourEqpSlot].ObjIndex;
        UserList[UserIndex].flags.Desnudo = 0;
    } else {
        UserList[UserIndex].flags.Desnudo = 1;
    }

    /* 'Obtiene el indice-objeto del escudo */
    if (UserList[UserIndex].Invent.EscudoEqpSlot > 0) {
        UserList[UserIndex].Invent.EscudoEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.EscudoEqpSlot].ObjIndex;

        Obj = ObjData[UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.EscudoEqpSlot].ObjIndex];
        UserList[UserIndex].Char.ShieldAnim = Obj.ShieldAnim;
    }

    /* 'Obtiene el indice-objeto del casco */
    if (UserList[UserIndex].Invent.CascoEqpSlot > 0) {
        UserList[UserIndex].Invent.CascoEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.CascoEqpSlot].ObjIndex;

        Obj = ObjData[UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.CascoEqpSlot].ObjIndex];
        UserList[UserIndex].Char.CascoAnim = Obj.CascoAnim;
    }

    /* 'Obtiene el indice-objeto barco */
    if (UserList[UserIndex].Invent.BarcoSlot > 0) {
        UserList[UserIndex].Invent.BarcoObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.BarcoSlot].ObjIndex;
    }

    /* 'Obtiene el indice-objeto municion */
    if (UserList[UserIndex].Invent.MunicionEqpSlot > 0) {
        UserList[UserIndex].Invent.MunicionEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.MunicionEqpSlot].ObjIndex;
    }

    /* '[Alejo] */
    /* 'Obtiene el indice-objeto anilo */
    if (UserList[UserIndex].Invent.AnilloEqpSlot > 0) {
        UserList[UserIndex].Invent.AnilloEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.AnilloEqpSlot].ObjIndex;
    }

    if (UserList[UserIndex].Invent.MochilaEqpSlot > 0) {
        UserList[UserIndex].Invent.MochilaEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.MochilaEqpSlot].ObjIndex;
    }

    UserList[UserIndex].BancoInvent.NroItems = 0;
    /* 'Lista de objetos del banco */
    for (LoopC = (1); LoopC <= (MAX_BANCOINVENTORY_SLOTS); LoopC++) {
        UserList[UserIndex].BancoInvent.Object[LoopC].ObjIndex = 0;
        UserList[UserIndex].BancoInvent.Object[LoopC].Amount = 0;
    }
}

void DotIO::updateUserPosition() {
    int map = 272;
    int y;
    int entrada = RandomNumber(0,2);
    if (entrada == 0){
        y  = RandomNumber(66,70);
    }
    else if (entrada == 1){
        y  = RandomNumber(45,49);
    }
    else if (entrada == 2){
        y  = RandomNumber(24,28);
    }
    int x = RandomNumber(72,82);
    UserList[UserIndex].Pos.Map = map;
    UserList[UserIndex].Pos.X = x;
    UserList[UserIndex].Pos.Y = y;
}

void DotIO::updateUserLevel() {
    UserList[UserIndex].Stats.Exp = 5679050;
    CheckUserLevel(UserIndex, false);
    UserList[UserIndex].Stats.MinMAN = UserList[UserIndex].Stats.MaxMAN;
    UserList[UserIndex].Stats.MinSta = UserList[UserIndex].Stats.MaxSta;
}<commit_msg>start as pk<commit_after>//
// Created by horacio on 3/12/17.
//
#include "stdafx.h"
#include "Crypto.h"
#include "DotIO.h"
#include "DotIOInventory.h"
#include "Matematicas.h"

DotIO::DotIO(int UserIndex, const std::string &Name, eRaza UserRaza, eGenero UserSexo,
                               eClass UserClase,
                               const std::string &UserEmail,
                               eCiudad Hogar, int Head) {
    this->UserIndex = UserIndex;
    this->Name = Name;
    this->UserRaza = UserRaza;
    this->UserSexo = UserSexo;
    this->UserClase = UserClase;
    this->UserEmail = UserEmail;
    this->Hogar = Hogar;
    this->Head = Head;
}

void DotIO::setupUser() {
    loadUserIni();
    loadUserReputacion();
    loadUserFlags();

    loadUserStats();

    loadUserInventoryItems(); // << ITEMS

    loadUserInventory();

    loadUserHechizos();

    updateUserPosition();
    updateUserLevel();

    int i;
}

void DotIO::addSpell(int number) {
    int lastSlot = 16;
    while (UserList[UserIndex].Stats.UserHechizos[lastSlot] != 0) {
        lastSlot--;
    }
    UserList[UserIndex].Stats.UserHechizos[lastSlot] = number;
}

void DotIO::loadUserHechizos() {

    if (UserClase == eClass_Thief || UserClase == eClass_Warrior || UserClase == eClass_Hunter){
        return;
    }
    addSpell(10); // remover paralisis
    addSpell(24); // inmovilizar
    if (UserClase == eClass_Cleric || UserClase == eClass_Mage || UserClase == eClass_Bard || UserClase == eClass_Druid){
        addSpell(25); // apocalipsis
    }
    addSpell(23); // descargar electrica
    addSpell(15); // tormenta
    addSpell(8); // misil magico
    //addSpell(14); // invisibilidad
    addSpell(5); // curar heridas graves
    addSpell(18); // celeridad
    addSpell(20); // fuerza

}

void DotIO::loadUserReputacion() {
    UserList[UserIndex].Reputacion.AsesinoRep = 2000;
    UserList[UserIndex].Reputacion.BandidoRep = 0;
    UserList[UserIndex].Reputacion.BurguesRep = 0;
    UserList[UserIndex].Reputacion.LadronesRep = 0;
    UserList[UserIndex].Reputacion.NobleRep = 1000;
    UserList[UserIndex].Reputacion.PlebeRep = 30;
    UserList[UserIndex].Reputacion.Promedio = 30 / 6;
}

void DotIO::loadUserFlags() {
    UserList[UserIndex].flags.Muerto = 0;
    UserList[UserIndex].flags.Escondido = 0;
    UserList[UserIndex].flags.Hambre = 0;
    UserList[UserIndex].flags.Sed = 0;
    UserList[UserIndex].flags.Desnudo = 0;
    UserList[UserIndex].flags.Navegando = 0;
    UserList[UserIndex].flags.Envenenado = 0;
    UserList[UserIndex].flags.Paralizado = 0;
    UserList[UserIndex].flags.lastMap = 0;
}

void DotIO::loadUserIni() {
    int LoopC;

    UserList[UserIndex].Name = Name;
    UserList[UserIndex].clase = UserClase;
    UserList[UserIndex].raza = UserRaza;
    UserList[UserIndex].Genero = UserSexo;
    UserList[UserIndex].email = UserEmail;
    UserList[UserIndex].Hogar = Hogar;

    UserList[UserIndex].Char.heading = eHeading_SOUTH;

    DarCuerpo(UserIndex); // <-- !!!
    UserList[UserIndex].Char.Head = Head;

    UserList[UserIndex].OrigChar = UserList[UserIndex].Char;

    UserList[UserIndex].LogOnTime = vb6::Now();
    UserList[UserIndex].UpTime = 0;
    UserList[UserIndex].desc = "";

    UserList[UserIndex].Faccion.ArmadaReal = 0;
    UserList[UserIndex].Faccion.CiudadanosMatados = 0;
    UserList[UserIndex].Faccion.CriminalesMatados = 0;
    UserList[UserIndex].Faccion.FuerzasCaos = 0;
    UserList[UserIndex].Faccion.FechaIngreso = "No ingresó a ninguna Facción";
    UserList[UserIndex].Faccion.RecibioArmaduraCaos = 0;
    UserList[UserIndex].Faccion.RecibioArmaduraReal = 0;
    UserList[UserIndex].Faccion.RecibioExpInicialCaos = 0;
    UserList[UserIndex].Faccion.RecibioExpInicialReal = 0;
    UserList[UserIndex].Faccion.RecompensasCaos = 0;
    UserList[UserIndex].Faccion.RecompensasReal = 0;
    UserList[UserIndex].Faccion.Reenlistadas = 0;
    UserList[UserIndex].Faccion.NivelIngreso = 0;
    UserList[UserIndex].Faccion.MatadosIngreso = 0;
    UserList[UserIndex].Faccion.NextRecompensa = 0;

    UserList[UserIndex].Counters.Pena = 0;
    UserList[UserIndex].Counters.AsignedSkills = 0;

    UserList[UserIndex].GuildIndex = 0;

    UserList[UserIndex].NroMascotas = 0;
    for (LoopC = (1); LoopC <= (MAXMASCOTAS); LoopC++) {
        UserList[UserIndex].MascotasType[LoopC] = 0;
    }
}

void DotIO::loadUserStats() {
    int i, LoopC;
    UserList[UserIndex].Stats.UserAtributos[eAtributos_Fuerza] =
            18 + ModRaza[UserRaza].Fuerza;
    UserList[UserIndex].Stats.UserAtributos[eAtributos_Agilidad] =
            18 + ModRaza[UserRaza].Agilidad;
    UserList[UserIndex].Stats.UserAtributos[eAtributos_Inteligencia] =
            18 + ModRaza[UserRaza].Inteligencia;
    UserList[UserIndex].Stats.UserAtributos[eAtributos_Carisma] =
            18 + ModRaza[UserRaza].Carisma;
    UserList[UserIndex].Stats.UserAtributos[eAtributos_Constitucion] =
            18 + ModRaza[UserRaza].Constitucion;

    for (i = (1); i <= (NUMATRIBUTOS); i++) {
        UserList[UserIndex].Stats.UserAtributosBackUP[i] = UserList[UserIndex].Stats.UserAtributos[i];
    }

    for (i = (1); i <= (NUMSKILLS); i++) {
        UserList[UserIndex].Stats.UserSkills[i] = 100;
        UserList[UserIndex].Stats.EluSkills[i] = 0;
        UserList[UserIndex].Stats.ExpSkills[i] = 0;
    }
    UserList[UserIndex].Stats.SkillPts = 0;

    int MiInt;
    MiInt = RandomNumber(1, UserList[UserIndex].Stats.UserAtributos[eAtributos_Constitucion] / 3);

    UserList[UserIndex].Stats.MaxHp = 15 + MiInt;
    UserList[UserIndex].Stats.MinHp = 15 + MiInt;

    MiInt = RandomNumber(1, UserList[UserIndex].Stats.UserAtributos[eAtributos_Agilidad] / 6);
    if (MiInt == 1) {
        MiInt = 2;
    }

    UserList[UserIndex].Stats.MaxSta = 20 * MiInt;
    UserList[UserIndex].Stats.MinSta = 20 * MiInt;

    UserList[UserIndex].Stats.MaxAGU = 100;
    UserList[UserIndex].Stats.MinAGU = 100;

    UserList[UserIndex].Stats.MaxHam = 100;
    UserList[UserIndex].Stats.MinHam = 100;

    if (UserClase == eClass_Mage) {
        MiInt = UserList[UserIndex].Stats.UserAtributos[eAtributos_Inteligencia] * 3;
        UserList[UserIndex].Stats.MaxMAN = MiInt;
        UserList[UserIndex].Stats.MinMAN = MiInt;
    } else if (UserClase == eClass_Cleric || UserClase == eClass_Druid || UserClase == eClass_Bard
               || UserClase == eClass_Assasin) {
        UserList[UserIndex].Stats.MaxMAN = 50;
        UserList[UserIndex].Stats.MinMAN = 50;
        /* 'Mana Inicial del Bandido (ToxicWaste) */
    } else if (UserClase == eClass_Bandit) {
        UserList[UserIndex].Stats.MaxMAN = 50;
        UserList[UserIndex].Stats.MinMAN = 50;
    } else {
        UserList[UserIndex].Stats.MaxMAN = 0;
        UserList[UserIndex].Stats.MinMAN = 0;
    }

    UserList[UserIndex].Stats.MaxHIT = 2;
    UserList[UserIndex].Stats.MinHIT = 1;

    UserList[UserIndex].Stats.GLD = 0;
    UserList[UserIndex].Stats.Banco = 0;

    UserList[UserIndex].Stats.Exp = 0;
    UserList[UserIndex].Stats.ELU = 300;
    UserList[UserIndex].Stats.ELV = 1;

    UserList[UserIndex].Stats.UsuariosMatados = 0;
    UserList[UserIndex].Stats.NPCsMuertos = 0;
}

void DotIO::loadUserInventoryItems() {
    DotIOInventory inventory(UserIndex, Name, UserRaza, UserSexo, UserClase, UserEmail, Hogar, Head);
    inventory.initializeInventory();
}

void DotIO::loadUserInventory() {
    int i, LoopC;
    struct ObjData Obj;

    /* 'Obtiene el indice-objeto del arma */
    if (UserList[UserIndex].Invent.WeaponEqpSlot > 0) {
        UserList[UserIndex].Invent.WeaponEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.WeaponEqpSlot].ObjIndex;
        UserList[UserIndex].Char.WeaponAnim = GetWeaponAnim(UserIndex,
                                                            UserList[UserIndex].Invent.WeaponEqpObjIndex);
    }

    /* 'Obtiene el indice-objeto del armadura */
    if (UserList[UserIndex].Invent.ArmourEqpSlot > 0) {
        Obj = ObjData[UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.ArmourEqpSlot].ObjIndex];
        UserList[UserIndex].Char.body = Obj.Ropaje;

        UserList[UserIndex].Invent.ArmourEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.ArmourEqpSlot].ObjIndex;
        UserList[UserIndex].flags.Desnudo = 0;
    } else {
        UserList[UserIndex].flags.Desnudo = 1;
    }

    /* 'Obtiene el indice-objeto del escudo */
    if (UserList[UserIndex].Invent.EscudoEqpSlot > 0) {
        UserList[UserIndex].Invent.EscudoEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.EscudoEqpSlot].ObjIndex;

        Obj = ObjData[UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.EscudoEqpSlot].ObjIndex];
        UserList[UserIndex].Char.ShieldAnim = Obj.ShieldAnim;
    }

    /* 'Obtiene el indice-objeto del casco */
    if (UserList[UserIndex].Invent.CascoEqpSlot > 0) {
        UserList[UserIndex].Invent.CascoEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.CascoEqpSlot].ObjIndex;

        Obj = ObjData[UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.CascoEqpSlot].ObjIndex];
        UserList[UserIndex].Char.CascoAnim = Obj.CascoAnim;
    }

    /* 'Obtiene el indice-objeto barco */
    if (UserList[UserIndex].Invent.BarcoSlot > 0) {
        UserList[UserIndex].Invent.BarcoObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.BarcoSlot].ObjIndex;
    }

    /* 'Obtiene el indice-objeto municion */
    if (UserList[UserIndex].Invent.MunicionEqpSlot > 0) {
        UserList[UserIndex].Invent.MunicionEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.MunicionEqpSlot].ObjIndex;
    }

    /* '[Alejo] */
    /* 'Obtiene el indice-objeto anilo */
    if (UserList[UserIndex].Invent.AnilloEqpSlot > 0) {
        UserList[UserIndex].Invent.AnilloEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.AnilloEqpSlot].ObjIndex;
    }

    if (UserList[UserIndex].Invent.MochilaEqpSlot > 0) {
        UserList[UserIndex].Invent.MochilaEqpObjIndex =
                UserList[UserIndex].Invent.Object[UserList[UserIndex].Invent.MochilaEqpSlot].ObjIndex;
    }

    UserList[UserIndex].BancoInvent.NroItems = 0;
    /* 'Lista de objetos del banco */
    for (LoopC = (1); LoopC <= (MAX_BANCOINVENTORY_SLOTS); LoopC++) {
        UserList[UserIndex].BancoInvent.Object[LoopC].ObjIndex = 0;
        UserList[UserIndex].BancoInvent.Object[LoopC].Amount = 0;
    }
}

void DotIO::updateUserPosition() {
    int map = 272;
    int y;
    int entrada = RandomNumber(0,2);
    if (entrada == 0){
        y  = RandomNumber(66,70);
    }
    else if (entrada == 1){
        y  = RandomNumber(45,49);
    }
    else if (entrada == 2){
        y  = RandomNumber(24,28);
    }
    int x = RandomNumber(72,82);
    UserList[UserIndex].Pos.Map = map;
    UserList[UserIndex].Pos.X = x;
    UserList[UserIndex].Pos.Y = y;
}

void DotIO::updateUserLevel() {
    UserList[UserIndex].Stats.Exp = 5679050;
    CheckUserLevel(UserIndex, false);
    UserList[UserIndex].Stats.MinMAN = UserList[UserIndex].Stats.MaxMAN;
    UserList[UserIndex].Stats.MinSta = UserList[UserIndex].Stats.MaxSta;
}<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexPS.cxx
 ** Lexer for PostScript
 **
 ** Written by Nigel Hathaway <nigel@bprj.co.uk>.
 ** The License.txt file describes the conditions under which this software may be distributed.
 **/

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>

#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"

#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static inline bool IsASelfDelimitingChar(const int ch) {
    return (ch == '[' || ch == ']' || ch == '{' || ch == '}' ||
            ch == '/' || ch == '<' || ch == '>' ||
            ch == '(' || ch == ')' || ch == '%');
}

static inline bool IsAWhitespaceChar(const int ch) {
    return (ch == ' '  || ch == '\t' || ch == '\r' ||
            ch == '\n' || ch == '\f' || ch == '\0');
}

static bool IsABaseNDigit(const int ch, const int base) {
    int maxdig = '9';
    int letterext = -1;

    if (base <= 10)
        maxdig = '0' + base - 1;
    else
        letterext = base - 11;

    return ((ch >= '0' && ch <= maxdig) ||
            (ch >= 'A' && ch <= ('A' + letterext)) ||
            (ch >= 'a' && ch <= ('a' + letterext)));
}

static inline bool IsABase85Char(const int ch) {
    return ((ch >= '!' && ch <= 'u') || ch == 'z');
}

static void ColourisePSDoc(
    unsigned int startPos,
    int length,
    int initStyle,
    WordList *keywordlists[],
    Accessor &styler) {

    WordList &keywords1 = *keywordlists[0];
    WordList &keywords2 = *keywordlists[1];
    WordList &keywords3 = *keywordlists[2];
    WordList &keywords4 = *keywordlists[3];
    WordList &keywords5 = *keywordlists[4];

    StyleContext sc(startPos, length, initStyle, styler);

    bool tokenizing = styler.GetPropertyInt("ps.tokenize") != 0;
    int pslevel = styler.GetPropertyInt("ps.level", 3);
    int lineCurrent = styler.GetLine(startPos);
    int nestTextCurrent = 0;
    if (lineCurrent > 0 && initStyle == SCE_PS_TEXT)
        nestTextCurrent = styler.GetLineState(lineCurrent - 1);
    int numRadix = 0;
    bool numHasPoint = false;
    bool numHasExponent = false;
    bool numHasSign = false;

    // Clear out existing tokenization
    if (tokenizing && length > 0) {
        styler.StartAt(startPos, static_cast<char>(INDIC2_MASK));
        styler.ColourTo(startPos + length-1, 0);
        styler.Flush();
        styler.StartAt(startPos);
        styler.StartSegment(startPos);
    }

    for (; sc.More(); sc.Forward()) {
        if (sc.atLineStart)
            lineCurrent = styler.GetLine(sc.currentPos);

        // Determine if the current state should terminate.
        if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) {
            if (sc.atLineEnd) {
                sc.SetState(SCE_C_DEFAULT);
            }
        } else if (sc.state == SCE_PS_DSC_COMMENT) {
            if (sc.ch == ':') {
                sc.Forward();
                if (!sc.atLineEnd)
                    sc.SetState(SCE_PS_DSC_VALUE);
                else
                    sc.SetState(SCE_C_DEFAULT);
            } else if (sc.atLineEnd) {
                sc.SetState(SCE_C_DEFAULT);
            } else if (IsAWhitespaceChar(sc.ch) && sc.ch != '\r') {
                sc.ChangeState(SCE_PS_COMMENT);
            }
        } else if (sc.state == SCE_PS_NUMBER) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
                if ((sc.chPrev == '+' || sc.chPrev == '-' ||
                     sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0)
                    sc.ChangeState(SCE_PS_NAME);
                sc.SetState(SCE_C_DEFAULT);
            } else if (sc.ch == '#') {
                if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    char szradix[5];
                    sc.GetCurrent(szradix, 4);
                    numRadix = atoi(szradix);
                    if (numRadix < 2 || numRadix > 36)
                        sc.ChangeState(SCE_PS_NAME);
                }
            } else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) {
                if (numHasExponent) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    numHasExponent = true;
                    if (sc.chNext == '+' || sc.chNext == '-')
                        sc.Forward();
                }
            } else if (sc.ch == '.') {
                if (numHasPoint || numHasExponent || numRadix != 0) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    numHasPoint = true;
                }
            } else if (numRadix == 0) {
                if (!IsABaseNDigit(sc.ch, 10))
                    sc.ChangeState(SCE_PS_NAME);
            } else {
                if (!IsABaseNDigit(sc.ch, numRadix))
                    sc.ChangeState(SCE_PS_NAME);
            }
        } else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
                char s[100];
                sc.GetCurrent(s, sizeof(s));
                if ((pslevel >= 1 && keywords1.InList(s)) ||
                    (pslevel >= 2 && keywords2.InList(s)) ||
                    (pslevel >= 3 && keywords3.InList(s)) ||
                    keywords4.InList(s) || keywords5.InList(s)) {
                    sc.ChangeState(SCE_PS_KEYWORD);
                }
                sc.SetState(SCE_C_DEFAULT);
            }
        } else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch))
                sc.SetState(SCE_C_DEFAULT);
        } else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT ||
                   sc.state == SCE_PS_PAREN_PROC) {
            sc.SetState(SCE_C_DEFAULT);
        } else if (sc.state == SCE_PS_TEXT) {
            if (sc.ch == '(') {
                nestTextCurrent++;
            } else if (sc.ch == ')') {
                if (--nestTextCurrent == 0)
                   sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (sc.ch == '\\') {
                sc.Forward();
            }
        } else if (sc.state == SCE_PS_HEXSTRING) {
            if (sc.ch == '>') {
                sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_HEXSTRING);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            }
        } else if (sc.state == SCE_PS_BASE85STRING) {
            if (sc.Match('~', '>')) {
                sc.Forward();
                sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_BASE85STRING);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            }
        }

        // Determine if a new state should be entered.
        if (sc.state == SCE_C_DEFAULT) {
            unsigned int tokenpos = sc.currentPos;

            if (sc.ch == '[' || sc.ch == ']') {
                sc.SetState(SCE_PS_PAREN_ARRAY);
            } else if (sc.ch == '{' || sc.ch == '}') {
                sc.SetState(SCE_PS_PAREN_PROC);
            } else if (sc.ch == '/') {
                if (sc.chNext == '/') {
                    sc.SetState(SCE_PS_IMMEVAL);
                    sc.Forward();
                } else {
                    sc.SetState(SCE_PS_LITERAL);
                }
            } else if (sc.ch == '<') {
                if (sc.chNext == '<') {
                    sc.SetState(SCE_PS_PAREN_DICT);
                    sc.Forward();
                } else if (sc.chNext == '~') {
                    sc.SetState(SCE_PS_BASE85STRING);
                    sc.Forward();
                } else {
                    sc.SetState(SCE_PS_HEXSTRING);
                }
            } else if (sc.ch == '>' && sc.chNext == '>') {
                    sc.SetState(SCE_PS_PAREN_DICT);
                    sc.Forward();
            } else if (sc.ch == '>' || sc.ch == ')') {
                sc.SetState(SCE_C_DEFAULT);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            } else if (sc.ch == '(') {
                sc.SetState(SCE_PS_TEXT);
                nestTextCurrent = 1;
            } else if (sc.ch == '%') {
                if (sc.chNext == '%' && sc.atLineStart) {
                    sc.SetState(SCE_PS_DSC_COMMENT);
                    sc.Forward();
                    if (sc.chNext == '+') {
                        sc.Forward();
                        sc.ForwardSetState(SCE_PS_DSC_VALUE);
                    }
                } else {
                    sc.SetState(SCE_PS_COMMENT);
                }
            } else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') &&
                       IsABaseNDigit(sc.chNext, 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = (sc.ch == '.');
                numHasExponent = false;
                numHasSign = (sc.ch == '+' || sc.ch == '-');
            } else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' &&
                       IsABaseNDigit(sc.GetRelative(2), 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = false;
                numHasExponent = false;
                numHasSign = true;
            } else if (IsABaseNDigit(sc.ch, 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = false;
                numHasExponent = false;
                numHasSign = false;
            } else if (!IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_NAME);
            }

            // Mark the start of tokens
            if (tokenizing && sc.state != SCE_C_DEFAULT && sc.state != SCE_PS_COMMENT &&
                sc.state != SCE_PS_DSC_COMMENT && sc.state != SCE_PS_DSC_VALUE) {
                styler.Flush();
                styler.StartAt(tokenpos, static_cast<char>(INDIC2_MASK));
                styler.ColourTo(tokenpos, INDIC2_MASK);
                styler.Flush();
                styler.StartAt(tokenpos);
                styler.StartSegment(tokenpos);
            }
        }

        if (sc.atLineEnd)
            styler.SetLineState(lineCurrent, nestTextCurrent);
    }

    sc.Complete();
}

static void FoldPSDoc(unsigned int startPos, int length, int, WordList *[],
                       Accessor &styler) {
    bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
    bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
    unsigned int endPos = startPos + length;
    int visibleChars = 0;
    int lineCurrent = styler.GetLine(startPos);
    int levelCurrent = SC_FOLDLEVELBASE;
    if (lineCurrent > 0)
        levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
    int levelMinCurrent = levelCurrent;
    int levelNext = levelCurrent;
    char chNext = styler[startPos];
    int styleNext = styler.StyleAt(startPos);
    for (unsigned int i = startPos; i < endPos; i++) {
        char ch = chNext;
        chNext = styler.SafeGetCharAt(i + 1);
        int style = styleNext;
        styleNext = styler.StyleAt(i + 1);
        bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');  //mac??
        if ((style & 31) == SCE_PS_PAREN_PROC) {
            if (ch == '{') {
                // Measure the minimum before a '{' to allow
                // folding on "} {"
                if (levelMinCurrent > levelNext) {
                    levelMinCurrent = levelNext;
                }
                levelNext++;
            } else if (ch == '}') {
                levelNext--;
            }
        }
        if (atEOL) {
            int levelUse = levelCurrent;
            if (foldAtElse) {
                levelUse = levelMinCurrent;
            }
            int lev = levelUse | levelNext << 16;
            if (visibleChars == 0 && foldCompact)
                lev |= SC_FOLDLEVELWHITEFLAG;
            if (levelUse < levelNext)
                lev |= SC_FOLDLEVELHEADERFLAG;
            if (lev != styler.LevelAt(lineCurrent)) {
                styler.SetLevel(lineCurrent, lev);
            }
            lineCurrent++;
            levelCurrent = levelNext;
            levelMinCurrent = levelCurrent;
            visibleChars = 0;
        }
        if (!isspacechar(ch))
            visibleChars++;
    }
}

static const char * const psWordListDesc[] = {
    "PS Level 1 operators",
    "PS Level 2 operators",
    "PS Level 3 operators",
    "RIP-specific operators",
    "User-defined operators",
    0
};

LexerModule lmPS(SCLEX_PS, ColourisePSDoc, "ps", FoldPSDoc, psWordListDesc);
<commit_msg>Removing use of style byte indicator in PostScript lexer.<commit_after>// Scintilla source code edit control
/** @file LexPS.cxx
 ** Lexer for PostScript
 **
 ** Written by Nigel Hathaway <nigel@bprj.co.uk>.
 ** The License.txt file describes the conditions under which this software may be distributed.
 **/

// Previous releases of this lexer included support for marking token starts with
// a style byte indicator. This was used by the wxGhostscript IDE/debugger.
// Style byte indicators were removed in version 3.4.3.
// Anyone wanting to restore this functionality for wxGhostscript using 'modern'
// indicators can examine the earlier source in the Mercurial repository.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>

#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"

#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static inline bool IsASelfDelimitingChar(const int ch) {
    return (ch == '[' || ch == ']' || ch == '{' || ch == '}' ||
            ch == '/' || ch == '<' || ch == '>' ||
            ch == '(' || ch == ')' || ch == '%');
}

static inline bool IsAWhitespaceChar(const int ch) {
    return (ch == ' '  || ch == '\t' || ch == '\r' ||
            ch == '\n' || ch == '\f' || ch == '\0');
}

static bool IsABaseNDigit(const int ch, const int base) {
    int maxdig = '9';
    int letterext = -1;

    if (base <= 10)
        maxdig = '0' + base - 1;
    else
        letterext = base - 11;

    return ((ch >= '0' && ch <= maxdig) ||
            (ch >= 'A' && ch <= ('A' + letterext)) ||
            (ch >= 'a' && ch <= ('a' + letterext)));
}

static inline bool IsABase85Char(const int ch) {
    return ((ch >= '!' && ch <= 'u') || ch == 'z');
}

static void ColourisePSDoc(
    unsigned int startPos,
    int length,
    int initStyle,
    WordList *keywordlists[],
    Accessor &styler) {

    WordList &keywords1 = *keywordlists[0];
    WordList &keywords2 = *keywordlists[1];
    WordList &keywords3 = *keywordlists[2];
    WordList &keywords4 = *keywordlists[3];
    WordList &keywords5 = *keywordlists[4];

    StyleContext sc(startPos, length, initStyle, styler);

    int pslevel = styler.GetPropertyInt("ps.level", 3);
    int lineCurrent = styler.GetLine(startPos);
    int nestTextCurrent = 0;
    if (lineCurrent > 0 && initStyle == SCE_PS_TEXT)
        nestTextCurrent = styler.GetLineState(lineCurrent - 1);
    int numRadix = 0;
    bool numHasPoint = false;
    bool numHasExponent = false;
    bool numHasSign = false;

    for (; sc.More(); sc.Forward()) {
        if (sc.atLineStart)
            lineCurrent = styler.GetLine(sc.currentPos);

        // Determine if the current state should terminate.
        if (sc.state == SCE_PS_COMMENT || sc.state == SCE_PS_DSC_VALUE) {
            if (sc.atLineEnd) {
                sc.SetState(SCE_C_DEFAULT);
            }
        } else if (sc.state == SCE_PS_DSC_COMMENT) {
            if (sc.ch == ':') {
                sc.Forward();
                if (!sc.atLineEnd)
                    sc.SetState(SCE_PS_DSC_VALUE);
                else
                    sc.SetState(SCE_C_DEFAULT);
            } else if (sc.atLineEnd) {
                sc.SetState(SCE_C_DEFAULT);
            } else if (IsAWhitespaceChar(sc.ch) && sc.ch != '\r') {
                sc.ChangeState(SCE_PS_COMMENT);
            }
        } else if (sc.state == SCE_PS_NUMBER) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
                if ((sc.chPrev == '+' || sc.chPrev == '-' ||
                     sc.chPrev == 'E' || sc.chPrev == 'e') && numRadix == 0)
                    sc.ChangeState(SCE_PS_NAME);
                sc.SetState(SCE_C_DEFAULT);
            } else if (sc.ch == '#') {
                if (numHasPoint || numHasExponent || numHasSign || numRadix != 0) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    char szradix[5];
                    sc.GetCurrent(szradix, 4);
                    numRadix = atoi(szradix);
                    if (numRadix < 2 || numRadix > 36)
                        sc.ChangeState(SCE_PS_NAME);
                }
            } else if ((sc.ch == 'E' || sc.ch == 'e') && numRadix == 0) {
                if (numHasExponent) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    numHasExponent = true;
                    if (sc.chNext == '+' || sc.chNext == '-')
                        sc.Forward();
                }
            } else if (sc.ch == '.') {
                if (numHasPoint || numHasExponent || numRadix != 0) {
                    sc.ChangeState(SCE_PS_NAME);
                } else {
                    numHasPoint = true;
                }
            } else if (numRadix == 0) {
                if (!IsABaseNDigit(sc.ch, 10))
                    sc.ChangeState(SCE_PS_NAME);
            } else {
                if (!IsABaseNDigit(sc.ch, numRadix))
                    sc.ChangeState(SCE_PS_NAME);
            }
        } else if (sc.state == SCE_PS_NAME || sc.state == SCE_PS_KEYWORD) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch)) {
                char s[100];
                sc.GetCurrent(s, sizeof(s));
                if ((pslevel >= 1 && keywords1.InList(s)) ||
                    (pslevel >= 2 && keywords2.InList(s)) ||
                    (pslevel >= 3 && keywords3.InList(s)) ||
                    keywords4.InList(s) || keywords5.InList(s)) {
                    sc.ChangeState(SCE_PS_KEYWORD);
                }
                sc.SetState(SCE_C_DEFAULT);
            }
        } else if (sc.state == SCE_PS_LITERAL || sc.state == SCE_PS_IMMEVAL) {
            if (IsASelfDelimitingChar(sc.ch) || IsAWhitespaceChar(sc.ch))
                sc.SetState(SCE_C_DEFAULT);
        } else if (sc.state == SCE_PS_PAREN_ARRAY || sc.state == SCE_PS_PAREN_DICT ||
                   sc.state == SCE_PS_PAREN_PROC) {
            sc.SetState(SCE_C_DEFAULT);
        } else if (sc.state == SCE_PS_TEXT) {
            if (sc.ch == '(') {
                nestTextCurrent++;
            } else if (sc.ch == ')') {
                if (--nestTextCurrent == 0)
                   sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (sc.ch == '\\') {
                sc.Forward();
            }
        } else if (sc.state == SCE_PS_HEXSTRING) {
            if (sc.ch == '>') {
                sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (!IsABaseNDigit(sc.ch, 16) && !IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_HEXSTRING);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            }
        } else if (sc.state == SCE_PS_BASE85STRING) {
            if (sc.Match('~', '>')) {
                sc.Forward();
                sc.ForwardSetState(SCE_PS_DEFAULT);
            } else if (!IsABase85Char(sc.ch) && !IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_BASE85STRING);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            }
        }

        // Determine if a new state should be entered.
        if (sc.state == SCE_C_DEFAULT) {

            if (sc.ch == '[' || sc.ch == ']') {
                sc.SetState(SCE_PS_PAREN_ARRAY);
            } else if (sc.ch == '{' || sc.ch == '}') {
                sc.SetState(SCE_PS_PAREN_PROC);
            } else if (sc.ch == '/') {
                if (sc.chNext == '/') {
                    sc.SetState(SCE_PS_IMMEVAL);
                    sc.Forward();
                } else {
                    sc.SetState(SCE_PS_LITERAL);
                }
            } else if (sc.ch == '<') {
                if (sc.chNext == '<') {
                    sc.SetState(SCE_PS_PAREN_DICT);
                    sc.Forward();
                } else if (sc.chNext == '~') {
                    sc.SetState(SCE_PS_BASE85STRING);
                    sc.Forward();
                } else {
                    sc.SetState(SCE_PS_HEXSTRING);
                }
            } else if (sc.ch == '>' && sc.chNext == '>') {
                    sc.SetState(SCE_PS_PAREN_DICT);
                    sc.Forward();
            } else if (sc.ch == '>' || sc.ch == ')') {
                sc.SetState(SCE_C_DEFAULT);
                styler.ColourTo(sc.currentPos, SCE_PS_BADSTRINGCHAR);
            } else if (sc.ch == '(') {
                sc.SetState(SCE_PS_TEXT);
                nestTextCurrent = 1;
            } else if (sc.ch == '%') {
                if (sc.chNext == '%' && sc.atLineStart) {
                    sc.SetState(SCE_PS_DSC_COMMENT);
                    sc.Forward();
                    if (sc.chNext == '+') {
                        sc.Forward();
                        sc.ForwardSetState(SCE_PS_DSC_VALUE);
                    }
                } else {
                    sc.SetState(SCE_PS_COMMENT);
                }
            } else if ((sc.ch == '+' || sc.ch == '-' || sc.ch == '.') &&
                       IsABaseNDigit(sc.chNext, 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = (sc.ch == '.');
                numHasExponent = false;
                numHasSign = (sc.ch == '+' || sc.ch == '-');
            } else if ((sc.ch == '+' || sc.ch == '-') && sc.chNext == '.' &&
                       IsABaseNDigit(sc.GetRelative(2), 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = false;
                numHasExponent = false;
                numHasSign = true;
            } else if (IsABaseNDigit(sc.ch, 10)) {
                sc.SetState(SCE_PS_NUMBER);
                numRadix = 0;
                numHasPoint = false;
                numHasExponent = false;
                numHasSign = false;
            } else if (!IsAWhitespaceChar(sc.ch)) {
                sc.SetState(SCE_PS_NAME);
            }
        }

        if (sc.atLineEnd)
            styler.SetLineState(lineCurrent, nestTextCurrent);
    }

    sc.Complete();
}

static void FoldPSDoc(unsigned int startPos, int length, int, WordList *[],
                       Accessor &styler) {
    bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
    bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0;
    unsigned int endPos = startPos + length;
    int visibleChars = 0;
    int lineCurrent = styler.GetLine(startPos);
    int levelCurrent = SC_FOLDLEVELBASE;
    if (lineCurrent > 0)
        levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
    int levelMinCurrent = levelCurrent;
    int levelNext = levelCurrent;
    char chNext = styler[startPos];
    int styleNext = styler.StyleAt(startPos);
    for (unsigned int i = startPos; i < endPos; i++) {
        char ch = chNext;
        chNext = styler.SafeGetCharAt(i + 1);
        int style = styleNext;
        styleNext = styler.StyleAt(i + 1);
        bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');  //mac??
        if ((style & 31) == SCE_PS_PAREN_PROC) {
            if (ch == '{') {
                // Measure the minimum before a '{' to allow
                // folding on "} {"
                if (levelMinCurrent > levelNext) {
                    levelMinCurrent = levelNext;
                }
                levelNext++;
            } else if (ch == '}') {
                levelNext--;
            }
        }
        if (atEOL) {
            int levelUse = levelCurrent;
            if (foldAtElse) {
                levelUse = levelMinCurrent;
            }
            int lev = levelUse | levelNext << 16;
            if (visibleChars == 0 && foldCompact)
                lev |= SC_FOLDLEVELWHITEFLAG;
            if (levelUse < levelNext)
                lev |= SC_FOLDLEVELHEADERFLAG;
            if (lev != styler.LevelAt(lineCurrent)) {
                styler.SetLevel(lineCurrent, lev);
            }
            lineCurrent++;
            levelCurrent = levelNext;
            levelMinCurrent = levelCurrent;
            visibleChars = 0;
        }
        if (!isspacechar(ch))
            visibleChars++;
    }
}

static const char * const psWordListDesc[] = {
    "PS Level 1 operators",
    "PS Level 2 operators",
    "PS Level 3 operators",
    "RIP-specific operators",
    "User-defined operators",
    0
};

LexerModule lmPS(SCLEX_PS, ColourisePSDoc, "ps", FoldPSDoc, psWordListDesc);
<|endoftext|>


<commit_before>#include "Field.h"
#include "Type.h"
#include "Nothing.h"
#include <stddef.h>

namespace octarine {

	Field _FieldFields[] = {
		{ Type::sType, POINTER, offsetof(Field, mType), { 4, "type" } },
		{ UwordType, VALUE, offsetof(Field, mKind), { 4, "kind" } },
		{ UwordType, VALUE, offsetof(Field, mOffset), { 6, "offset" } },
		{ String::sType, VALUE, offsetof(Field, mName), { 4, "name" } }
	};

	Array _FieldFieldsArray = {
		Field::sType,
		VALUE,
		4,
		&_FieldFields
	};

	Type _FieldType = {
		sizeof(Field),
		sizeof(Uword),
		_FieldFieldsArray
	};

	Type* Field::sType = &_FieldType;

	static void _init(Self* self) {
		Field* f = (Field*) self;
		f->mType = Nothing::sType;
		f->mKind = VALUE;
		f->mOffset = 0;
		f->mName.sObjectFns->init((Self*) &f->mName);
	}

	static void _destroy(Self* self) {
	}

	static Type* mTypeFn(Self* self) {
		return Field::sType;
	}

	static Uword _hash(Self* self) {
		Field* f = (Field*) self;
		Uword hash = 17;
		hash += f->mKind * 37;
		hash += f->mName.sObjectFns->hash((Self*)&f->mName) * 37;
		hash += f->mOffset * 37;
		hash += f->mType->sObjectFns->hash((Self*)f->mType) * 37;
		return hash;
	}

	static Bool _equals(Self* self, Object other) {
		if (self == other.mSelf) {
			return True;
		}
		if (other.mFunctions->type(other.mSelf) != Field::sType) {
			return False;
		}
		Field* f = (Field*) self;
		Field* otherF = (Field*) other.mSelf;
		return f->mKind == otherF->mKind &&
			f->mName.sObjectFns->equals((Self*)&f->mName, otherF->mName.asObject()) &&
			f->mOffset == otherF->mOffset &&
			f->mType->sObjectFns->equals((Self*)f->mType, otherF->mType->asObject());
	}

	static void _trace(Self* self, MemoryManager mm) {
		Field* f = (Field*) self;
		Uword markResult;
		mm.functions->mark(mm.self, f, &markResult);
		if (markResult == MemoryManagerMarkResult::ALREADY_MARKED) {
			return;
		}
		f->mName.sObjectFns->trace((Self*)&f->mName, mm);
		f->mType->sObjectFns->trace((Self*)f->mType, mm);
	}

	ObjectFunctions _objectFns = { _init, _destroy, mTypeFn, _hash, _equals, _trace };

	ObjectFunctions* Field::sObjectFns = &_objectFns;

	Object Field::asObject() {
		return{ (Self*)this, Field::sObjectFns };
	}

}
<commit_msg>Field.cpp compiles<commit_after>#include "Field.h"
#include "Type.h"
#include "Nothing.h"
#include "MemoryManager.h"
#include <stddef.h>

namespace octarine {

	Field _FieldFields[] = {
		{ Type::sType, POINTER, offsetof(Field, mType), { 4, "type" } },
		{ UwordType, VALUE, offsetof(Field, mKind), { 4, "kind" } },
		{ UwordType, VALUE, offsetof(Field, mOffset), { 6, "offset" } },
		{ String::sType, VALUE, offsetof(Field, mName), { 4, "name" } }
	};

	Array _FieldFieldsArray = {
		Field::sType,
		VALUE,
		4,
		&_FieldFields
	};

	Type _FieldType = {
		sizeof(Field),
		sizeof(Uword),
		_FieldFieldsArray
	};

	Type* Field::sType = &_FieldType;

	static void _init(Self* self) {
		Field* f = (Field*) self;
		f->mType = Nothing::sType;
		f->mKind = VALUE;
		f->mOffset = 0;
		f->mName.sObjectFns->init((Self*) &f->mName);
	}

	static void _destroy(Self* self) {
	}

	static Type* mTypeFn(Self* self) {
		return Field::sType;
	}

	static Uword _hash(Self* self) {
		Field* f = (Field*) self;
		Uword hash = 17;
		hash += f->mKind * 37;
		hash += f->mName.sObjectFns->hash((Self*)&f->mName) * 37;
		hash += f->mOffset * 37;
		hash += f->mType->sObjectFns->hash((Self*)f->mType) * 37;
		return hash;
	}

	static Bool _equals(Self* self, Object other) {
		if (self == other.mSelf) {
			return True;
		}
		if (other.mFunctions->type(other.mSelf) != Field::sType) {
			return False;
		}
		Field* f = (Field*) self;
		Field* otherF = (Field*) other.mSelf;
		return f->mKind == otherF->mKind &&
			f->mName.sObjectFns->equals((Self*)&f->mName, otherF->mName.asObject()) &&
			f->mOffset == otherF->mOffset &&
			f->mType->sObjectFns->equals((Self*)f->mType, otherF->mType->asObject());
	}

	static void _trace(Self* self, MemoryManager* mm) {
		Field* f = (Field*) self;
		Uword markResult;
		mm->mFunctions->mark(mm->mSelf, f, &markResult);
		if (markResult == MemoryManagerMarkResult::ALREADY_MARKED) {
			return;
		}
		f->mName.sObjectFns->trace((Self*)&f->mName, mm);
		f->mType->sObjectFns->trace((Self*)f->mType, mm);
	}

	ObjectFunctions _objectFns = { _init, _destroy, mTypeFn, _hash, _equals, _trace };

	ObjectFunctions* Field::sObjectFns = &_objectFns;

	Object Field::asObject() {
		return{ (Self*)this, Field::sObjectFns };
	}

}
<|endoftext|>