<commit_before>/*************************************************************************
 *
 *  $RCSfile: viewcontactofmasterpagedescriptor.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-12 14:30:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SDR_CONTACT_VIEWCONTACTOFMASTERPAGEDESCRIPTOR_HXX
#define _SDR_CONTACT_VIEWCONTACTOFMASTERPAGEDESCRIPTOR_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _SDR_CONTACT_VIEWCONTACT_HXX
#include <svx/sdr/contact/viewcontact.hxx>
#endif

#ifndef _SDR_MASTERPAGEDESCRIPTOR_HXX
#include <sdrmasterpagedescriptor.hxx>
#endif

//////////////////////////////////////////////////////////////////////////////
// predeclarations

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

namespace sdr
{
    namespace contact
    {
        class ViewContactOfMasterPageDescriptor : public ViewContact
        {
        protected:
            // the owner of this ViewContact. Set from constructor and not
            // to be changed in any way.
            sdr::MasterPageDescriptor&                      mrMasterPageDescriptor;

            // internal access to SdrObject
            sdr::MasterPageDescriptor& GetMasterPageDescriptor() const
            {
                return mrMasterPageDescriptor;
            }

            // internal access to SdrObject
            SdrPage& GetSdrPage() const
            {
                return GetMasterPageDescriptor().GetUsedPage();
            }

            // method to create a AnimationInfo. Needs to give a result if
            // SupportsAnimation() is overloaded and returns sal_True.
            virtual sdr::animation::AnimationInfo* CreateAnimationInfo();

            // Create a Object-Specific ViewObjectContact, set ViewContact and
            // ObjectContact. Always needs to return something.
            virtual ViewObjectContact& CreateObjectSpecificViewObjectContact(ObjectContact& rObjectContact);

            // method to recalculate the PaintRectangle if the validity flag shows that
            // it is invalid. The flag is set from GetPaintRectangle, thus the implementation
            // only needs to refresh maPaintRectangle itself.
            virtual void CalcPaintRectangle();

        public:
            // basic constructor
            ViewContactOfMasterPageDescriptor(sdr::MasterPageDescriptor& rDescriptor);

            // The destructor.
            virtual ~ViewContactOfMasterPageDescriptor();

            // When ShouldPaintObject() returns sal_True, the object itself is painted and
            // PaintObject() is called.
            virtual sal_Bool ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC);

            // #115593# Paint this object. This is before evtl. SubObjects get painted. It needs to return
            // sal_True when something was pained and the paint output rectangle in rPaintRectangle.
            virtual sal_Bool PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC);

            // Access to possible sub-hierarchy
            virtual sal_uInt32 GetObjectCount() const;
            virtual ViewContact& GetViewContact(sal_uInt32 nIndex) const;

            // Since MasterPages are part of the hierarchy of a DrawPage, the
            // link to ParentContacts may be 1:n
            virtual sal_Bool GetParentContacts(ViewContactVector& rVContacts) const;

            // Does this ViewContact support animation?
            virtual sal_Bool SupportsAnimation() const;

            // overload for acessing the SdrPage
            virtual SdrPage* TryToGetSdrPage() const;
        };
    } // end of namespace contact
} // end of namespace sdr

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

#endif //_SDR_CONTACT_VIEWCONTACTOFMASTERPAGEDESCRIPTOR_HXX

// eof
<commit_msg>INTEGRATION: CWS aw018 (1.2.118); FILE MERGED 2004/09/21 11:40:17 aw 1.2.118.1: #i26631#<commit_after>/*************************************************************************
 *
 *  $RCSfile: viewcontactofmasterpagedescriptor.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2004-10-12 10:04:27 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SDR_CONTACT_VIEWCONTACTOFMASTERPAGEDESCRIPTOR_HXX
#define _SDR_CONTACT_VIEWCONTACTOFMASTERPAGEDESCRIPTOR_HXX

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _SDR_CONTACT_VIEWCONTACT_HXX
#include <svx/sdr/contact/viewcontact.hxx>
#endif

#ifndef _SDR_MASTERPAGEDESCRIPTOR_HXX
#include <sdrmasterpagedescriptor.hxx>
#endif

//////////////////////////////////////////////////////////////////////////////
// predeclarations
class SfxItemSet;

namespace sdr
{
    namespace contact
    {
        class OwnMasterPagePainter;
    } // end of namespace contact
} // end of namespace sdr

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

namespace sdr
{
    namespace contact
    {
        class ViewContactOfMasterPageDescriptor : public ViewContact
        {
        protected:
            // the owner of this ViewContact. Set from constructor and not
            // to be changed in any way.
            sdr::MasterPageDescriptor&                      mrMasterPageDescriptor;

            // the painter for the MasterPage content
            ::sdr::contact::OwnMasterPagePainter*           mpMasterPagePainter;

            // Get the correct BackgroundObject
            SdrObject* GetBackgroundObject() const;

            // Get the LayerId of the BackgroundObject
            sal_uInt8 GetBackgroundObjectLayerId() const;

            // Create a Object-Specific ViewObjectContact, set ViewContact and
            // ObjectContact. Always needs to return something. Default is to create
            // a standard ViewObjectContact containing the given ObjectContact and *this
            virtual ViewObjectContact& CreateObjectSpecificViewObjectContact(ObjectContact& rObjectContact);

            // method to recalculate the PaintRectangle if the validity flag shows that
            // it is invalid. The flag is set from GetPaintRectangle, thus the implementation
            // only needs to refresh maPaintRectangle itself.
            virtual void CalcPaintRectangle();

        public:
            // basic constructor
            ViewContactOfMasterPageDescriptor(sdr::MasterPageDescriptor& rDescriptor);

            // The destructor.
            virtual ~ViewContactOfMasterPageDescriptor();

            // access to MasterPageDescriptor
            sdr::MasterPageDescriptor& GetMasterPageDescriptor() const
            {
                return mrMasterPageDescriptor;
            }

            // When ShouldPaintObject() returns sal_True, the object itself is painted and
            // PaintObject() is called.
            virtual sal_Bool ShouldPaintObject(DisplayInfo& rDisplayInfo, const ViewObjectContact& rAssociatedVOC);

            // #115593# Paint this object. This is before evtl. SubObjects get painted. It needs to return
            // sal_True when something was pained and the paint output rectangle in rPaintRectangle.
            virtual sal_Bool PaintObject(DisplayInfo& rDisplayInfo, Rectangle& rPaintRectangle, const ViewObjectContact& rAssociatedVOC);
            virtual ViewContact* GetParentContact() const;
        };
    } // end of namespace contact
} // end of namespace sdr

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

#endif //_SDR_CONTACT_VIEWCONTACTOFMASTERPAGEDESCRIPTOR_HXX

// eof
<|endoftext|>


<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "clustering/administration/main/file_based_svs_by_namespace.hpp"

#include "errors.hpp"
#include <boost/bind.hpp>

#include "clustering/immediate_consistency/branch/multistore.hpp"
#include "clustering/reactor/reactor.hpp"
#include "logger.hpp"
#include "rdb_protocol/store.hpp"
#include "serializer/config.hpp"
#include "serializer/translator.hpp"
#include "serializer/merger.hpp"
#include "utils.hpp"

/* This object serves mostly as a container for arguments to the
 * do_construct_existing_store function because we hit the boost::bind argument
 * limit. */
struct store_args_t {
    store_args_t(io_backender_t *_io_backender,
                 const base_path_t &_base_path,
                 namespace_id_t _namespace_id,
                 cache_balancer_t *_balancer,
                 perfmon_collection_t *_serializers_perfmon_collection,
                 rdb_context_t *_ctx,
                 outdated_index_issue_tracker_t *_outdated_index_tracker,
                 namespace_id_t _ns_id)
        : io_backender(_io_backender), base_path(_base_path),
          namespace_id(_namespace_id), balancer(_balancer),
          serializers_perfmon_collection(_serializers_perfmon_collection),
          ctx(_ctx), outdated_index_tracker(_outdated_index_tracker), ns_id(_ns_id)
    { }

    io_backender_t *io_backender;
    base_path_t base_path;
    namespace_id_t namespace_id;
    cache_balancer_t *balancer;
    perfmon_collection_t *serializers_perfmon_collection;
    rdb_context_t *ctx;
    outdated_index_issue_tracker_t *outdated_index_tracker;
    namespace_id_t ns_id;
};

std::string hash_shard_perfmon_name(int hash_shard_number) {
    return strprintf("shard_%d", hash_shard_number);
}

void do_construct_existing_store(
    const std::vector<threadnum_t> &threads,
    int thread_offset,
    store_args_t store_args,
    serializer_multiplexer_t *multiplexer,
    scoped_array_t<scoped_ptr_t<store_t> > *stores_out_stores,
    store_view_t **store_views) {

    // TODO: Exceptions?  Can exceptions happen, and then this doesn't
    // catch it, and the caller doesn't handle it.
    on_thread_t th(threads[thread_offset]);

    // Only pass this down to the first store
    scoped_ptr_t<outdated_index_report_t> index_report;
    if (thread_offset == 0) {
        index_report = store_args.outdated_index_tracker->create_report(store_args.ns_id);
    }

    // TODO: Can we pass serializers_perfmon_collection across threads like this?
    store_t *store = new store_t(
        multiplexer->proxies[thread_offset], store_args.balancer,
        hash_shard_perfmon_name(thread_offset),
        false, store_args.serializers_perfmon_collection,
        store_args.ctx, store_args.io_backender, store_args.base_path,
        std::move(index_report), store_args.ns_id);
    (*stores_out_stores)[thread_offset].init(store);
    store_views[thread_offset] = store;
}

void do_create_new_store(
    const std::vector<threadnum_t> &threads,
    int thread_offset,
    store_args_t store_args,
    serializer_multiplexer_t *multiplexer,
    scoped_array_t<scoped_ptr_t<store_t> > *stores_out_stores,
    store_view_t **store_views) {

    on_thread_t th(threads[thread_offset]);

    // Only pass this down to the first store
    scoped_ptr_t<outdated_index_report_t> index_report;
    if (thread_offset == 0) {
        index_report = store_args.outdated_index_tracker->create_report(store_args.ns_id);
    }

    store_t *store = new store_t(
        multiplexer->proxies[thread_offset], store_args.balancer,
        hash_shard_perfmon_name(thread_offset),
        true, store_args.serializers_perfmon_collection,
        store_args.ctx, store_args.io_backender, store_args.base_path,
        std::move(index_report), store_args.ns_id);
    (*stores_out_stores)[thread_offset].init(store);
    store_views[thread_offset] = store;
}

void
file_based_svs_by_namespace_t::get_svs(
            perfmon_collection_t *serializers_perfmon_collection,
            namespace_id_t namespace_id,
            stores_lifetimer_t *stores_out,
            scoped_ptr_t<multistore_ptr_t> *svs_out,
            rdb_context_t *ctx) {
    const int num_db_threads = get_num_db_threads();

    // TODO: If the server gets killed when starting up, we can
    // get a database in an invalid startup state.

    // TODO: This is quite suspicious in that we check if the file
    // exists and then assume it exists or does not exist when
    // loading or creating it.

    // TODO: We should use N slices on M serializers, not N slices
    // on N serializers.

    const int num_stores = CPU_SHARDING_FACTOR;
    scoped_array_t<scoped_ptr_t<store_t> > *stores_out_stores
        = stores_out->stores();
    stores_out_stores->init(num_stores);

    const threadnum_t serializer_thread = next_thread(num_db_threads);
    std::vector<threadnum_t> store_threads;
    for (int i = 0; i < num_stores; ++i) {
        store_threads.push_back(next_thread(num_db_threads));
    }

    scoped_ptr_t<serializer_t> serializer;
    scoped_ptr_t<serializer_multiplexer_t> multiplexer;
    scoped_ptr_t<multistore_ptr_t> mptr;
    {
        on_thread_t th(serializer_thread);
        scoped_array_t<store_view_t *> store_views(num_stores);

        const serializer_filepath_t serializer_filepath = file_name_for(namespace_id);
        int res = access(serializer_filepath.permanent_path().c_str(), R_OK | W_OK);
        store_args_t store_args(io_backender_, base_path_,
                                namespace_id, balancer_,
                                serializers_perfmon_collection, ctx,
                                &outdated_index_tracker, namespace_id);
        filepath_file_opener_t file_opener(serializer_filepath, io_backender_);
        if (res == 0) {
            // TODO: Could we handle failure when loading the serializer?  Right
            // now, we don't.

            {
                scoped_ptr_t<serializer_t> ser
                    = make_scoped<standard_serializer_t>(
                        standard_serializer_t::dynamic_config_t(),
                        &file_opener,
                        serializers_perfmon_collection);
                ser = make_scoped<merger_serializer_t>(std::move(ser),
                                                       MERGER_SERIALIZER_MAX_ACTIVE_WRITES);
                serializer = std::move(ser);
            }

            std::vector<serializer_t *> ptrs;
            ptrs.push_back(serializer.get());
            multiplexer.init(new serializer_multiplexer_t(ptrs));

            // TODO: Exceptions?  Can exceptions happen, and then
            // store_views' values would leak.  That is, are we handling
            // them in the pmap?  No.
            pmap(num_stores, boost::bind(do_construct_existing_store,
                                         store_threads, _1, store_args,
                                         multiplexer.get(),
                                         stores_out_stores, store_views.data()));
            mptr.init(new multistore_ptr_t(store_views.data(), num_stores));
        } else {
            standard_serializer_t::create(&file_opener,
                                          standard_serializer_t::static_config_t());
            {
                scoped_ptr_t<serializer_t> ser
                    = make_scoped<standard_serializer_t>(
                        standard_serializer_t::dynamic_config_t(),
                        &file_opener,
                        serializers_perfmon_collection);
                ser = make_scoped<merger_serializer_t>(std::move(ser),
                                                       MERGER_SERIALIZER_MAX_ACTIVE_WRITES);
                serializer = std::move(ser);
            }

            std::vector<serializer_t *> ptrs;
            ptrs.push_back(serializer.get());
            serializer_multiplexer_t::create(ptrs, num_stores);
            multiplexer.init(new serializer_multiplexer_t(ptrs));

            // TODO: How do we specify what the stores' regions are?
            // TODO: Exceptions?  Can exceptions happen, and then store_views'
            // values would leak.
            // The files do not exist, create them.
            // TODO: This should use pmap.
            pmap(num_stores, boost::bind(do_create_new_store,
                                         store_threads, _1, store_args,
                                         multiplexer.get(),
                                         stores_out_stores, store_views.data()));
            mptr.init(new multistore_ptr_t(store_views.data(), num_stores));

            // Initialize the metadata in the underlying stores.
            object_buffer_t<fifo_enforcer_sink_t::exit_write_t> write_token;
            mptr->new_write_token(&write_token);
            cond_t dummy_interruptor;
            order_source_t order_source;  // TODO: order_token_t::ignore.  Use the svs.
            guarantee(mptr->get_region() == region_t::universe());
            mptr->set_metainfo(
                region_map_t<binary_blob_t>(
                    mptr->get_region(),
                    binary_blob_t(version_range_t(version_t::zero()))),
                order_source.check_in("file_based_svs_by_namespace_t"),
                &write_token,
                &dummy_interruptor);

            // Finally, the store is created.
            file_opener.move_serializer_file_to_permanent_location();
        }
    } // back on calling thread

    svs_out->init(mptr.release());
    stores_out->serializer()->init(serializer.release());
    stores_out->multiplexer()->init(multiplexer.release());
}

void file_based_svs_by_namespace_t::destroy_svs(namespace_id_t namespace_id) {
    // TODO: Handle errors?  It seems like we can't really handle the error so
    // let's just ignore it?
    const std::string filepath = file_name_for(namespace_id).permanent_path();
    logNTC("Removing file %s\n", filepath.c_str());
    const int res = ::unlink(filepath.c_str());
    guarantee_err(res == 0 || get_errno() == ENOENT,
                  "unlink failed for file %s", filepath.c_str());
}

serializer_filepath_t file_based_svs_by_namespace_t::file_name_for(namespace_id_t namespace_id) {
    return serializer_filepath_t(base_path_, uuid_to_str(namespace_id));
}

threadnum_t file_based_svs_by_namespace_t::next_thread(int num_db_threads) {
    thread_counter_ = (thread_counter_ + 1) % num_db_threads;
    return threadnum_t(thread_counter_);
}
<commit_msg>Sourcr refactor. Abstracted common functionality and merged two fairly lare functions into filebasedsvsbynamespace in order to sace redundant code<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#include "clustering/administration/main/file_based_svs_by_namespace.hpp"

#include "errors.hpp"
#include <boost/bind.hpp>

#include "clustering/immediate_consistency/branch/multistore.hpp"
#include "clustering/reactor/reactor.hpp"
#include "logger.hpp"
#include "rdb_protocol/store.hpp"
#include "serializer/config.hpp"
#include "serializer/translator.hpp"
#include "serializer/merger.hpp"
#include "utils.hpp"

/* This object serves mostly as a container for arguments to the
 * do_construct_existing_store function because we hit the boost::bind argument
 * limit. */
struct store_args_t {
    store_args_t(io_backender_t *_io_backender,
                 const base_path_t &_base_path,
                 namespace_id_t _namespace_id,
                 cache_balancer_t *_balancer,
                 perfmon_collection_t *_serializers_perfmon_collection,
                 rdb_context_t *_ctx,
                 outdated_index_issue_tracker_t *_outdated_index_tracker,
                 namespace_id_t _ns_id)
        : io_backender(_io_backender), base_path(_base_path),
          namespace_id(_namespace_id), balancer(_balancer),
          serializers_perfmon_collection(_serializers_perfmon_collection),
          ctx(_ctx), outdated_index_tracker(_outdated_index_tracker), ns_id(_ns_id)
    { }

    io_backender_t *io_backender;
    base_path_t base_path;
    namespace_id_t namespace_id;
    cache_balancer_t *balancer;
    perfmon_collection_t *serializers_perfmon_collection;
    rdb_context_t *ctx;
    outdated_index_issue_tracker_t *outdated_index_tracker;
    namespace_id_t ns_id;
};

std::string hash_shard_perfmon_name(int hash_shard_number) {
    return strprintf("shard_%d", hash_shard_number);
}

void do_store(
    const std::vector<threadnum_t> &threads,
    int thread_offset,
    store_args_t store_args,
    serializer_multiplexer_t *multiplexer,
    scoped_array_t<scoped_ptr_t<store_t> > *stores_out_stores,
    store_view_t **store_views,
    bool create) {

    // TODO: Exceptions?  Can exceptions happen, and then this doesn't
    // catch it, and the caller doesn't handle it.
    on_thread_t th(threads[thread_offset]);

    // Only pass this down to the first store
    scoped_ptr_t<outdated_index_report_t> index_report;
    if (thread_offset == 0) {
        index_report = store_args.outdated_index_tracker->create_report(store_args.ns_id);
    }

    // TODO: Can we pass serializers_perfmon_collection across threads like this?
    store_t *store = new store_t(
        multiplexer->proxies[thread_offset], store_args.balancer,
        hash_shard_perfmon_name(thread_offset),
        create, store_args.serializers_perfmon_collection,
        store_args.ctx, store_args.io_backender, store_args.base_path,
        std::move(index_report), store_args.ns_id);
    (*stores_out_stores)[thread_offset].init(store);
    store_views[thread_offset] = store;
}

void do_construct_existing_store(
    const std::vector<threadnum_t> &threads,
    int thread_offset,
    store_args_t store_args,
    serializer_multiplexer_t *multiplexer,
    scoped_array_t<scoped_ptr_t<store_t> > *stores_out_stores,
    store_view_t **store_views) {

    do_store(threads, thread_offset, store_args, multiplexer, stores_out_stores,
    store_views, false);
}

void do_create_new_store(
    const std::vector<threadnum_t> &threads,
    int thread_offset,
    store_args_t store_args,
    serializer_multiplexer_t *multiplexer,
    scoped_array_t<scoped_ptr_t<store_t> > *stores_out_stores,
    store_view_t **store_views) {

    do_store(threads, thread_offset, store_args, multiplexer, stores_out_stores,
    store_views, true);
}

void
file_based_svs_by_namespace_t::get_svs(
            perfmon_collection_t *serializers_perfmon_collection,
            namespace_id_t namespace_id,
            stores_lifetimer_t *stores_out,
            scoped_ptr_t<multistore_ptr_t> *svs_out,
            rdb_context_t *ctx) {
    const int num_db_threads = get_num_db_threads();

    // TODO: If the server gets killed when starting up, we can
    // get a database in an invalid startup state.

    // TODO: This is quite suspicious in that we check if the file
    // exists and then assume it exists or does not exist when
    // loading or creating it.

    // TODO: We should use N slices on M serializers, not N slices
    // on N serializers.

    const int num_stores = CPU_SHARDING_FACTOR;
    scoped_array_t<scoped_ptr_t<store_t> > *stores_out_stores
        = stores_out->stores();
    stores_out_stores->init(num_stores);

    const threadnum_t serializer_thread = next_thread(num_db_threads);
    std::vector<threadnum_t> store_threads;
    for (int i = 0; i < num_stores; ++i) {
        store_threads.push_back(next_thread(num_db_threads));
    }

    scoped_ptr_t<serializer_t> serializer;
    scoped_ptr_t<serializer_multiplexer_t> multiplexer;
    scoped_ptr_t<multistore_ptr_t> mptr;
    {
        on_thread_t th(serializer_thread);
        scoped_array_t<store_view_t *> store_views(num_stores);

        const serializer_filepath_t serializer_filepath = file_name_for(namespace_id);
        int res = access(serializer_filepath.permanent_path().c_str(), R_OK | W_OK);
        store_args_t store_args(io_backender_, base_path_,
                                namespace_id, balancer_,
                                serializers_perfmon_collection, ctx,
                                &outdated_index_tracker, namespace_id);
        filepath_file_opener_t file_opener(serializer_filepath, io_backender_);
        if (res == 0) {
            // TODO: Could we handle failure when loading the serializer?  Right
            // now, we don't.

            {
                scoped_ptr_t<serializer_t> ser
                    = make_scoped<standard_serializer_t>(
                        standard_serializer_t::dynamic_config_t(),
                        &file_opener,
                        serializers_perfmon_collection);
                ser = make_scoped<merger_serializer_t>(std::move(ser),
                                                       MERGER_SERIALIZER_MAX_ACTIVE_WRITES);
                serializer = std::move(ser);
            }

            std::vector<serializer_t *> ptrs;
            ptrs.push_back(serializer.get());
            multiplexer.init(new serializer_multiplexer_t(ptrs));

            // TODO: Exceptions?  Can exceptions happen, and then
            // store_views' values would leak.  That is, are we handling
            // them in the pmap?  No.
            pmap(num_stores, boost::bind(do_construct_existing_store,
                                         store_threads, _1, store_args,
                                         multiplexer.get(),
                                         stores_out_stores, store_views.data()));
            mptr.init(new multistore_ptr_t(store_views.data(), num_stores));
        } else {
            standard_serializer_t::create(&file_opener,
                                          standard_serializer_t::static_config_t());
            {
                scoped_ptr_t<serializer_t> ser
                    = make_scoped<standard_serializer_t>(
                        standard_serializer_t::dynamic_config_t(),
                        &file_opener,
                        serializers_perfmon_collection);
                ser = make_scoped<merger_serializer_t>(std::move(ser),
                                                       MERGER_SERIALIZER_MAX_ACTIVE_WRITES);
                serializer = std::move(ser);
            }

            std::vector<serializer_t *> ptrs;
            ptrs.push_back(serializer.get());
            serializer_multiplexer_t::create(ptrs, num_stores);
            multiplexer.init(new serializer_multiplexer_t(ptrs));

            // TODO: How do we specify what the stores' regions are?
            // TODO: Exceptions?  Can exceptions happen, and then store_views'
            // values would leak.
            // The files do not exist, create them.
            // TODO: This should use pmap.
            pmap(num_stores, boost::bind(do_create_new_store,
                                         store_threads, _1, store_args,
                                         multiplexer.get(),
                                         stores_out_stores, store_views.data()));
            mptr.init(new multistore_ptr_t(store_views.data(), num_stores));

            // Initialize the metadata in the underlying stores.
            object_buffer_t<fifo_enforcer_sink_t::exit_write_t> write_token;
            mptr->new_write_token(&write_token);
            cond_t dummy_interruptor;
            order_source_t order_source;  // TODO: order_token_t::ignore.  Use the svs.
            guarantee(mptr->get_region() == region_t::universe());
            mptr->set_metainfo(
                region_map_t<binary_blob_t>(
                    mptr->get_region(),
                    binary_blob_t(version_range_t(version_t::zero()))),
                order_source.check_in("file_based_svs_by_namespace_t"),
                &write_token,
                &dummy_interruptor);

            // Finally, the store is created.
            file_opener.move_serializer_file_to_permanent_location();
        }
    } // back on calling thread

    svs_out->init(mptr.release());
    stores_out->serializer()->init(serializer.release());
    stores_out->multiplexer()->init(multiplexer.release());
}

void file_based_svs_by_namespace_t::destroy_svs(namespace_id_t namespace_id) {
    // TODO: Handle errors?  It seems like we can't really handle the error so
    // let's just ignore it?
    const std::string filepath = file_name_for(namespace_id).permanent_path();
    logNTC("Removing file %s\n", filepath.c_str());
    const int res = ::unlink(filepath.c_str());
    guarantee_err(res == 0 || get_errno() == ENOENT,
                  "unlink failed for file %s", filepath.c_str());
}

serializer_filepath_t file_based_svs_by_namespace_t::file_name_for(namespace_id_t namespace_id) {
    return serializer_filepath_t(base_path_, uuid_to_str(namespace_id));
}

threadnum_t file_based_svs_by_namespace_t::next_thread(int num_db_threads) {
    thread_counter_ = (thread_counter_ + 1) % num_db_threads;
    return threadnum_t(thread_counter_);
}
<|endoftext|>


<commit_before>#include "MoveDummy.h"
#include "ObjectDummy.h"
#include "BodyDummy.h"
#include "ShapeCapsule.h"

#include "Utils.h"
#include "Engine.h"
#include "Physics.h"
#include "Game.h"
#include "World.h"

#define MOVE_DUMMY_IFPS			(1.0f/100.0f)
#define MOVE_DUMMY_CLAMP           89.9f
#define MOVE_DUMMY_COLLISIONS		1

using namespace MathLib;

CMoveDummy::CMoveDummy()		//캯
{
	m_pObject = new CObjectDummy();		//һʵ
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(0.5f, 1.0f);

	SetCollisionMask(1);
	Clear();
}

CMoveDummy::~CMoveDummy()
{
	m_pDummy->SetObject(NULL);
	SAFE_DELETE(m_pObject);
	SAFE_DELETE(m_pDummy);
}

void CMoveDummy::SetCollision(int c)
{
	m_nCollision = c;
}

int CMoveDummy::GetCollision() const
{
	return m_nCollision;
}

void CMoveDummy::SetCollisionMask(int m)
{
	m_pShape->SetCollisionMask(m);
}

int CMoveDummy::GetCollisionMask() const
{
	return m_nCollisionMask;
}

void CMoveDummy::SetGround(int g)
{
	m_nGround = g;
}

int CMoveDummy::GetGround() const
{
	return m_nGround;
}

void CMoveDummy::SetCeiling(int c)
{
	m_nCeiling = c;
}

int CMoveDummy::GetCeiling() const
{
	return m_nCeiling;
}

void CMoveDummy::SetPosition(const MathLib::vec3& p)
{
	m_vPosition = p;
}

const MathLib::vec3& CMoveDummy::GetPosition() const
{
	return m_vPosition;
}

void CMoveDummy::SetCollisionRadius(float radius)
{
	if (!Compare(m_pShape->GetRadius(), radius))
	{
		m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());
		m_pShape->SetRadius(radius);
	}

	Update_Bounds();
}

float CMoveDummy::GetCollisionRadius() const
{
	return m_pShape->GetRadius();
}

void CMoveDummy::SetCollisionHeight(float height)
{
	if (!Compare(m_pShape->GetHeight(), height))
	{
		m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());
		m_pShape->SetHeight(height);
	}

	Update_Bounds();
}
float CMoveDummy::GetCollisionHeight() const
{
	return m_pShape->GetHeight();
}

void CMoveDummy::SetUp(const MathLib::vec3& u)
{
	m_vUp = u;
}

const MathLib::vec3& CMoveDummy::GetUp() const
{
	return m_vUp;
}
void CMoveDummy::SetEnabled(int e)
{
	m_nEnabled = e;
}

float CMoveDummy::GetCollisionHeight() const
{
	return m_pShape->GetHeight();
}
void CMoveDummy::SetUp(const MathLib::vec3& u)
{
	m_vUp = u;
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "MoveDummy.h"
#include "ObjectDummy.h"
#include "BodyDummy.h"
#include "ShapeCapsule.h"

#include "Utils.h"
#include "Engine.h"
#include "Physics.h"
#include "Game.h"
#include "World.h"

#define MOVE_DUMMY_IFPS			(1.0f/100.0f)
#define MOVE_DUMMY_CLAMP           89.9f
#define MOVE_DUMMY_COLLISIONS		1

using namespace MathLib;

CMoveDummy::CMoveDummy()		//캯
{
	m_pObject = new CObjectDummy();		//һʵ
	m_pDummy = new CBodyDummy();
	m_pShape = new CShapeCapsule(0.5f, 1.0f);

	SetCollisionMask(1);
	Clear();
}

CMoveDummy::~CMoveDummy()
{
	m_pDummy->SetObject(NULL);
	SAFE_DELETE(m_pObject);
	SAFE_DELETE(m_pDummy);
}

void CMoveDummy::SetCollision(int c)
{
	m_nCollision = c;
}

int CMoveDummy::GetCollision() const
{
	return m_nCollision;
}

void CMoveDummy::SetCollisionMask(int m)
{
	m_pShape->SetCollisionMask(m);
}

int CMoveDummy::GetCollisionMask() const
{
	return m_nCollisionMask;
}

void CMoveDummy::SetGround(int g)
{
	m_nGround = g;
}

int CMoveDummy::GetGround() const
{
	return m_nGround;
}

void CMoveDummy::SetCeiling(int c)
{
	m_nCeiling = c;
}

int CMoveDummy::GetCeiling() const
{
	return m_nCeiling;
}

void CMoveDummy::SetPosition(const MathLib::vec3& p)
{
	m_vPosition = p;
}

const MathLib::vec3& CMoveDummy::GetPosition() const
{
	return m_vPosition;
}

void CMoveDummy::SetCollisionRadius(float radius)
{
	if (!Compare(m_pShape->GetRadius(), radius))
	{
		m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());
		m_pShape->SetRadius(radius);
	}

	Update_Bounds();
}

float CMoveDummy::GetCollisionRadius() const
{
	return m_pShape->GetRadius();
}

void CMoveDummy::SetCollisionHeight(float height)
{
	if (!Compare(m_pShape->GetHeight(), height))
	{
		m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());
		m_pShape->SetHeight(height);
	}

	Update_Bounds();
}
float CMoveDummy::GetCollisionHeight() const
{
	return m_pShape->GetHeight();
}

void CMoveDummy::SetUp(const MathLib::vec3& u)
{
	m_vUp = u;
}

const MathLib::vec3& CMoveDummy::GetUp() const
{
	return m_vUp;
}
void CMoveDummy::SetEnabled(int e)
{
	m_nEnabled = e;
}

float CMoveDummy::GetCollisionHeight() const
{
	return m_pShape->GetHeight();
}
void CMoveDummy::SetUp(const MathLib::vec3& u)
{
	m_vUp = u;
}

const MathLib::vec3& CMoveDummy::GetUp() const
{
	return m_vUp;
}
void CMoveDummy::SetEnabled(int e)
{
	m_nEnabled = e;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>
#include <list>

using namespace std;

double sinus(double x){
    return sin(x);
}

double power(double base, double exp){
    return pow(base, exp);
}

double wielomian(double a, double b, double c, double d, double x){
    return a*x*x*x -b*x*x +c*x -d;
}

//list<double> rozwiazania;
template<class F>void bisekcja(double start, double end, F funk, double epsilon){
    if( (funk(start) >=0 && funk(end) < 0) || (funk(start)<0 && funk(end) >=0) ){
        double center = (start+end)/2;
        double centerValue = funk(center);
        if(abs(centerValue) < epsilon){
            //rozwiazania.push_back(center);
            cout << center << endl;
        } else {
            bisekcja(start, center, funk, epsilon);
            bisekcja(center, end, funk, epsilon);
        }
    }
}

template<class F> double siecznych(F funk, double a, double b, double eps){
    double x0;
    x0 = a - funk(a) * (a - b) / (funk(a) - funk(b));

    if (fabs(funk(x0)) < eps){
        cout << x0 << endl;
        cout << funk(x0) << endl;
        return x0;
    }
    else{
        cout << x0 << endl;
        cout << funk(x0) << endl;
        return siecznych(funk, x0, a, eps);
    }
}

int main()
{
    cout << "Hello World!" << endl;
    //bisekcja(-1,1.1,sinus,0.02);
    auto exponent = [](double x) -> double {return power(2,x);};
    auto wiel = [](double x) -> double {return wielomian(2,3,2,1,x);};
    bisekcja(-1,1.1,sinus,0.001);
    cout << endl << endl;
    double a = 2;
    siecznych([a](double x)->double {return power(a, x);}, 2, 6, 0.2);
    /*for(list<double>::iterator it = rozwiazania.begin(); it != rozwiazania.end(); it++){
        cout << *it << endl;
    }*/

    return 0;
}

<commit_msg>dorzucony warunek do siecznych<commit_after>#include <iostream>
#include <cmath>
#include <list>

using namespace std;

double sinus(double x){
    return sin(x);
}

double power(double base, double exp){
    return pow(base, exp);
}

double wielomian(double a, double b, double c, double d, double x){
    return a*x*x*x -b*x*x +c*x -d;
}

//list<double> rozwiazania;
template<class F>void bisekcja(double start, double end, F funk, double epsilon){
    if( (funk(start) >=0 && funk(end) < 0) || (funk(start)<0 && funk(end) >=0) ){
        double center = (start+end)/2;
        double centerValue = funk(center);
        if(abs(centerValue) < epsilon){
            //rozwiazania.push_back(center);
            cout << center << endl;
        } else {
            bisekcja(start, center, funk, epsilon);
            bisekcja(center, end, funk, epsilon);
        }
    }
}

template<class F> double siecznych(F funk, double a, double b, double eps){
    double x0;
    double x00;
    x0 = a - funk(a) * (a - b) / (funk(a) - funk(b));
    if (x0 != x0){cout << "blad sieczna pionowa, najblizsza wartosc " << x00 << endl; return 0;}
    if (fabs(funk(x0)) < eps){
        //cout << x0 << endl;
        //cout << funk(x0) << endl;
        return x0;
    }
    else{
        //cout << x0 << endl;
        //cout << funk(x0) << endl;
        return siecznych(funk, x0, a, eps);
    }
    x00=x0;
}

int main()
{
    cout << "Hello World!" << endl;
    //bisekcja(-1,1.1,sinus,0.02);
    auto exponent = [](double x) -> double {return power(2,x);};
    auto wiel = [](double x) -> double {return wielomian(2,3,2,1,x);};
    bisekcja(-1,1.1,sinus,0.001);
    cout << endl << endl;
    double a = 2;
    cout << siecznych([a](double x)->double {return power(a, x);}, 2, 6, 0.2);
    /*for(list<double>::iterator it = rozwiazania.begin(); it != rozwiazania.end(); it++){
        cout << *it << endl;
    }*/

    return 0;
}

<|endoftext|>


<commit_before>// Nano.cpp:      .
//

#include "stdafx.h"
#include <fstream>

using namespace std;
#pragma region structurs
struct parametrs
{
public:
	double ETA;
	double kolvoatom;
	//double radiuscluster;
	double radiusatomov;
	double kolvopovtorenii;
};
struct cluster
{
public:
	double R;
	double X;
	double Y;
	double Z;

	double Volume;

	double ETA;  // ETA:=NNp*Volume/VolCl;
	double Hdip; //Hdip:=Ms*ETA;
	double Qint;

};
struct atom
{
public:
	double R;
	double X;
	double Y;
	double Z;
	double Volume;
	/*double M[1000];*/
};
#pragma endregion

atom randomAtom(double _R);

int main()
{
	double Pi = 3.16159265;
	ifstream fin("Parametrs.txt");
	double buf[50];
	parametrs Param[50];
	cluster LC[50];
	int i = 0;
	while (i != 50)
	{
		fin >> Param[i].ETA >> Param[i].kolvoatom >> Param[i].radiusatomov >> Param[i].kolvopovtorenii;
		LC[i].X = 0;
		LC[i].Y = 0;
		LC[i].Z = 0;
		LC[i].ETA = Param[i].ETA;
		LC[i].Volume = Param[i].kolvoatom * 4 * Pi*Param[i].radiusatomov / (3 * Param[i].ETA);
		LC[i].R = pow(LC[i].Volume, 1 / 3);
		atom LA[1000];
		for (int j = 0; j < 1000; j++)
		{
			LA[j] = randomAtom(Param[j].radiusatomov);
		}
		ofstream fout;
		fout.open("result.txt");
		fin.close();
		fout.close();
		i++;
	}
	return 0;
}

atom randomAtom(double _R)
{
	atom A;

	A.X = rand();
	A.Y = rand();
	A.Z = rand();
	A.R = _R;
	return A;
}

<commit_msg>Delete Nano.cpp<commit_after><|endoftext|>


<commit_before>#ifndef PIXELBOOST_DISABLE_GRAPHICS

#include "glm/gtc/matrix_transform.hpp"

#include "pixelboost/debug/log.h"
#include "pixelboost/file/fileHelpers.h"
#include "pixelboost/framework/engine.h"
#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/device/indexBuffer.h"
#include "pixelboost/graphics/device/program.h"
#include "pixelboost/graphics/device/vertexBuffer.h"
#include "pixelboost/graphics/renderer/common/renderer.h"
#include "pixelboost/graphics/renderer/font/fontRenderer.h"
#include "pixelboost/graphics/renderer/primitive/primitiveRenderer.h"
#include "pixelboost/graphics/renderer/rocket/rocketRenderer.h"
#include "pixelboost/graphics/renderer/sprite/sprite.h"
#include "pixelboost/graphics/renderer/sprite/spriteRenderer.h"
#include "pixelboost/graphics/shader/shader.h"
#include "pixelboost/graphics/shader/manager.h"

#include <math.h>

using namespace pb;

RocketRenderable::RocketRenderable(Rocket::Core::Context* context)
    : Renderable(0)
    , _Context(context)
{

}

RocketRenderable::~RocketRenderable()
{

}

Uid RocketRenderable::GetType()
{
    return RocketRenderable::GetStaticType();
}

Uid RocketRenderable::GetStaticType()
{
    return TypeHash("RocketRenderable");
}

void RocketRenderable::CalculateBounds()
{
    SetBounds(BoundingSphere());
}

void RocketRenderable::CalculateWorldMatrix()
{
    SetWorldMatrix(glm::mat4x4());
}

Shader* RocketRenderable::GetShader()
{
    Shader* baseShader = Renderable::GetShader();
    if (baseShader)
        return baseShader;

    return Renderer::Instance()->GetShaderManager()->GetShader("/data/shaders/pb_texturedColor.shc");
}

RocketRenderer::RocketRenderer()
{
    _MaxQuads = 1000;

    _IndexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatDynamic, 6*_MaxQuads);
    _VertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatDynamic, kVertexFormat_P_XYZ_RGBA_UV, 4*_MaxQuads);
    _VertexBuffer->Lock();
    Vertex_PXYZ_RGBA_UV* vertices = static_cast<Vertex_PXYZ_RGBA_UV*>(_VertexBuffer->GetData());
    for (int i=0; i<4*_MaxQuads; i++)
    {
        vertices[i].position[2] = 0;
    }
    _VertexBuffer->Unlock();

    Renderer::Instance()->SetHandler(RocketRenderable::GetStaticType(), this);

    Renderer::Instance()->GetShaderManager()->LoadShader("/data/shaders/pb_texturedColor.shc");
}

RocketRenderer::~RocketRenderer()
{
    Renderer::Instance()->GetShaderManager()->UnloadShader("/data/shaders/pb_texturedColor.shc");
}

void RocketRenderer::Render(int count, Renderable** renderables, Viewport* viewport, ShaderPass* shaderPass)
{
    _Viewport = viewport;
    _ShaderPass = shaderPass;

    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateDepthTest, false);
    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateBlend, true);
    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateTexture2D, true);

    for (int i=0; i<count; i++)
    {
        RocketRenderable* renderable = static_cast<RocketRenderable*>(renderables[i]);
        _Renderable = renderable;
        renderable->_Context->Render();
        PurgeBuffer(true);
    }

    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateTexture2D, false);
    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateDepthTest, true);
    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateBlend, false);
}

void RocketRenderer::RenderGeometry(Rocket::Core::Vertex* vertices, int numVertices, int* indices, int numIndices, Rocket::Core::TextureHandle textureHandle, const Rocket::Core::Vector2f& translation)
{
    Texture* texture = (Texture*)textureHandle;

    _VertexBuffer->Lock();
    Vertex_PXYZ_RGBA_UV* vertexData = static_cast<Vertex_PXYZ_RGBA_UV*>(_VertexBuffer->GetData());

    for (int i=0; i<numVertices; i++)
    {
        vertexData[i].position[0] = vertices[i].position.x/32.f;
        vertexData[i].position[1] = -vertices[i].position.y/32.f;
        vertexData[i].position[2] = 0.f;
        vertexData[i].color[0] = vertices[i].colour.red/255.f;
        vertexData[i].color[1] = vertices[i].colour.green/255.f;
        vertexData[i].color[2] = vertices[i].colour.blue/255.f;
        vertexData[i].color[3] = vertices[i].colour.alpha/255.f;
        vertexData[i].uv[0] = vertices[i].tex_coord.x;
        vertexData[i].uv[1] = vertices[i].tex_coord.y;
    }

    _VertexBuffer->Unlock(numVertices);

    _IndexBuffer->Lock();
    unsigned short* indexData = _IndexBuffer->GetData();

    for (int i=0; i<numIndices; i++)
    {
        indexData[i] = (unsigned short)indices[i];
    }

    _IndexBuffer->Unlock(numIndices);

    _ShaderPass->GetShaderProgram()->SetUniform("PB_ModelViewProj", glm::translate(_Renderable->GetMVP(), glm::vec3(translation.x/32.f, -translation.y/32.f, 0)));
    GraphicsDevice::Instance()->BindIndexBuffer(_IndexBuffer);
    GraphicsDevice::Instance()->BindVertexBuffer(_VertexBuffer);
    GraphicsDevice::Instance()->BindTexture(texture);
    GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementTriangles, _IndexBuffer->GetCurrentSize());
    GraphicsDevice::Instance()->BindIndexBuffer(0);
    GraphicsDevice::Instance()->BindVertexBuffer(0);
    GraphicsDevice::Instance()->BindTexture(0);
}

Rocket::Core::CompiledGeometryHandle RocketRenderer::CompileGeometry(Rocket::Core::Vertex* vertices, int numVertices, int* indices, int numIndices, Rocket::Core::TextureHandle texture)
{
    VertexBuffer* vertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatStatic, kVertexFormat_P_XYZ_RGBA_UV, numIndices);

    vertexBuffer->Lock();
    Vertex_PXYZ_RGBA_UV* vertexData = static_cast<Vertex_PXYZ_RGBA_UV*>(vertexBuffer->GetData());

    for (int i=0; i<numVertices; i++)
    {
        vertexData[i].position[0] = vertices[i].position.x/32.f;
        vertexData[i].position[1] = -vertices[i].position.y/32.f;
        vertexData[i].position[2] = 0.f;
        vertexData[i].color[0] = vertices[i].colour.red/255.f;
        vertexData[i].color[1] = vertices[i].colour.green/255.f;
        vertexData[i].color[2] = vertices[i].colour.blue/255.f;
        vertexData[i].color[3] = vertices[i].colour.alpha/255.f;
        vertexData[i].uv[0] = vertices[i].tex_coord.x;
        vertexData[i].uv[1] = vertices[i].tex_coord.y;
    }

    vertexBuffer->Unlock(numVertices);

    IndexBuffer* indexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatStatic, numIndices);

    indexBuffer->Lock();
    unsigned short* indexData = indexBuffer->GetData();

    for (int i=0; i<numIndices; i++)
    {
        indexData[i] = (unsigned short)indices[i];
    }

    indexBuffer->Unlock(numIndices);

    _BufferMap[vertexBuffer] = indexBuffer;
    _TextureMap[vertexBuffer] = (Texture*)texture;

    return (Rocket::Core::CompiledGeometryHandle)vertexBuffer;
}

void RocketRenderer::RenderCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry, const Rocket::Core::Vector2f& translation)
{
    VertexBuffer* vertexBuffer = (VertexBuffer*)geometry;
    IndexBuffer* indexBuffer = _BufferMap[vertexBuffer];
    Texture* texture = _TextureMap[vertexBuffer];

    _ShaderPass->GetShaderProgram()->SetUniform("PB_ModelViewProj", glm::translate(_Renderable->GetMVP(), glm::vec3(translation.x/32.f, -translation.y/32.f, 0)));
    GraphicsDevice::Instance()->BindIndexBuffer(indexBuffer);
    GraphicsDevice::Instance()->BindVertexBuffer(vertexBuffer);
    GraphicsDevice::Instance()->BindTexture(texture);
    GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementTriangles, indexBuffer->GetCurrentSize());
    GraphicsDevice::Instance()->BindIndexBuffer(0);
    GraphicsDevice::Instance()->BindVertexBuffer(0);
    GraphicsDevice::Instance()->BindTexture(0);
}

void RocketRenderer::ReleaseCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry)
{
    VertexBuffer* vertexBuffer = (VertexBuffer*)geometry;
    IndexBuffer* indexBuffer = _BufferMap[vertexBuffer];
    _BufferMap.erase(vertexBuffer);
    _TextureMap.erase(vertexBuffer);

    GraphicsDevice::Instance()->DestroyIndexBuffer(indexBuffer);
    GraphicsDevice::Instance()->DestroyVertexBuffer(vertexBuffer);
}

void RocketRenderer::EnableScissorRegion(bool enable)
{
    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateScissor, enable);
}

void RocketRenderer::SetScissorRegion(int x, int y, int width, int height)
{
    GraphicsDevice::Instance()->SetScissor(glm::vec4(x, _Viewport->GetResolution().y-y-height, width, height));
}

bool RocketRenderer::LoadTexture(Rocket::Core::TextureHandle& textureHandle, Rocket::Core::Vector2i& textureDimensions, const Rocket::Core::String& source)
{
    std::string fileName = source.CString();

    Texture* texture = GraphicsDevice::Instance()->CreateTexture();

    if (!texture->LoadFromFile(pb::kFileLocationUser, fileName, false, false))
    {
        GraphicsDevice::Instance()->DestroyTexture(texture);
        return false;
    }

    textureHandle = (Rocket::Core::TextureHandle)texture;

    textureDimensions.x = texture->GetSize().x;
    textureDimensions.y = texture->GetSize().y;

    return true;
}

bool RocketRenderer::GenerateTexture(Rocket::Core::TextureHandle& textureHandle, const Rocket::Core::byte* source, const Rocket::Core::Vector2i& sourceDimensions)
{
    Texture* texture = GraphicsDevice::Instance()->CreateTexture();

    if (!texture->LoadFromBytes(source, sourceDimensions.x, sourceDimensions.y, false, Texture::kTextureFormatRGBA, false))
    {
        GraphicsDevice::Instance()->DestroyTexture(texture);
        return false;
    }

    textureHandle = (Rocket::Core::TextureHandle)texture;

    return true;
}

void RocketRenderer::ReleaseTexture(Rocket::Core::TextureHandle texture)
{
    if (texture)
    {
        GraphicsDevice::Instance()->DestroyTexture((Texture*)texture);
    }
}

float RocketRenderer::GetHorizontalTexelOffset()
{
    return 0.f;
}

float RocketRenderer::GetVerticalTexelOffset()
{
    return 0.f;
}

void RocketRenderer::Release()
{

}

void RocketRenderer::PurgeBuffer(bool force)
{

}

#endif
<commit_msg>Render librocket around center of camera<commit_after>#ifndef PIXELBOOST_DISABLE_GRAPHICS

#include "glm/gtc/matrix_transform.hpp"

#include "pixelboost/debug/log.h"
#include "pixelboost/file/fileHelpers.h"
#include "pixelboost/framework/engine.h"
#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/device/indexBuffer.h"
#include "pixelboost/graphics/device/program.h"
#include "pixelboost/graphics/device/vertexBuffer.h"
#include "pixelboost/graphics/renderer/common/renderer.h"
#include "pixelboost/graphics/renderer/font/fontRenderer.h"
#include "pixelboost/graphics/renderer/primitive/primitiveRenderer.h"
#include "pixelboost/graphics/renderer/rocket/rocketRenderer.h"
#include "pixelboost/graphics/renderer/sprite/sprite.h"
#include "pixelboost/graphics/renderer/sprite/spriteRenderer.h"
#include "pixelboost/graphics/shader/shader.h"
#include "pixelboost/graphics/shader/manager.h"

#include <math.h>

using namespace pb;

RocketRenderable::RocketRenderable(Rocket::Core::Context* context)
    : Renderable(0)
    , _Context(context)
{

}

RocketRenderable::~RocketRenderable()
{

}

Uid RocketRenderable::GetType()
{
    return RocketRenderable::GetStaticType();
}

Uid RocketRenderable::GetStaticType()
{
    return TypeHash("RocketRenderable");
}

void RocketRenderable::CalculateBounds()
{
    SetBounds(BoundingSphere());
}

void RocketRenderable::CalculateWorldMatrix()
{
    SetWorldMatrix(glm::mat4x4());
}

Shader* RocketRenderable::GetShader()
{
    Shader* baseShader = Renderable::GetShader();
    if (baseShader)
        return baseShader;

    return Renderer::Instance()->GetShaderManager()->GetShader("/data/shaders/pb_texturedColor.shc");
}

RocketRenderer::RocketRenderer()
{
    _MaxQuads = 1000;

    _IndexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatDynamic, 6*_MaxQuads);
    _VertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatDynamic, kVertexFormat_P_XYZ_RGBA_UV, 4*_MaxQuads);
    _VertexBuffer->Lock();
    Vertex_PXYZ_RGBA_UV* vertices = static_cast<Vertex_PXYZ_RGBA_UV*>(_VertexBuffer->GetData());
    for (int i=0; i<4*_MaxQuads; i++)
    {
        vertices[i].position[2] = 0;
    }
    _VertexBuffer->Unlock();

    Renderer::Instance()->SetHandler(RocketRenderable::GetStaticType(), this);

    Renderer::Instance()->GetShaderManager()->LoadShader("/data/shaders/pb_texturedColor.shc");
}

RocketRenderer::~RocketRenderer()
{
    Renderer::Instance()->GetShaderManager()->UnloadShader("/data/shaders/pb_texturedColor.shc");
}

void RocketRenderer::Render(int count, Renderable** renderables, Viewport* viewport, ShaderPass* shaderPass)
{
    _Viewport = viewport;
    _ShaderPass = shaderPass;

    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateDepthTest, false);
    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateBlend, true);
    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateTexture2D, true);

    for (int i=0; i<count; i++)
    {
        RocketRenderable* renderable = static_cast<RocketRenderable*>(renderables[i]);
        _Renderable = renderable;
        renderable->_Context->Render();
        PurgeBuffer(true);
    }

    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateTexture2D, false);
    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateDepthTest, true);
    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateBlend, false);
}

void RocketRenderer::RenderGeometry(Rocket::Core::Vertex* vertices, int numVertices, int* indices, int numIndices, Rocket::Core::TextureHandle textureHandle, const Rocket::Core::Vector2f& translation)
{
    Texture* texture = (Texture*)textureHandle;

    if (texture->HasPremultipliedAlpha())
    {
        GraphicsDevice::Instance()->SetBlendMode(GraphicsDevice::kBlendOne, GraphicsDevice::kBlendOneMinusSourceAlpha);
    } else {
        GraphicsDevice::Instance()->SetBlendMode(GraphicsDevice::kBlendSourceAlpha, GraphicsDevice::kBlendOneMinusSourceAlpha);
    }

    _VertexBuffer->Lock();
    Vertex_PXYZ_RGBA_UV* vertexData = static_cast<Vertex_PXYZ_RGBA_UV*>(_VertexBuffer->GetData());

    for (int i=0; i<numVertices; i++)
    {
        vertexData[i].position[0] = vertices[i].position.x/32.f;
        vertexData[i].position[1] = -vertices[i].position.y/32.f;
        vertexData[i].position[2] = 0.f;
        vertexData[i].color[0] = vertices[i].colour.red/255.f;
        vertexData[i].color[1] = vertices[i].colour.green/255.f;
        vertexData[i].color[2] = vertices[i].colour.blue/255.f;
        vertexData[i].color[3] = vertices[i].colour.alpha/255.f;
        vertexData[i].uv[0] = vertices[i].tex_coord.x;
        vertexData[i].uv[1] = vertices[i].tex_coord.y;
    }

    _VertexBuffer->Unlock(numVertices);

    _IndexBuffer->Lock();
    unsigned short* indexData = _IndexBuffer->GetData();

    for (int i=0; i<numIndices; i++)
    {
        indexData[i] = (unsigned short)indices[i];
    }

    _IndexBuffer->Unlock(numIndices);

    glm::mat4x4 matrix = _Renderable->GetMVP();
    matrix = glm::scale(matrix, glm::vec3(1.f,1.f,1.f)/32.f);
    matrix = glm::translate(matrix, glm::vec3(-pb::GraphicsDevice::Instance()->GetDisplayResolution().x/2.f, pb::GraphicsDevice::Instance()->GetDisplayResolution().y/2.f, 0.f));
    matrix = glm::translate(matrix, glm::vec3(translation.x, -translation.y, 0));
    _ShaderPass->GetShaderProgram()->SetUniform("PB_ModelViewProj", matrix);

    GraphicsDevice::Instance()->BindIndexBuffer(_IndexBuffer);
    GraphicsDevice::Instance()->BindVertexBuffer(_VertexBuffer);
    GraphicsDevice::Instance()->BindTexture(texture);
    GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementTriangles, _IndexBuffer->GetCurrentSize());
    GraphicsDevice::Instance()->BindIndexBuffer(0);
    GraphicsDevice::Instance()->BindVertexBuffer(0);
    GraphicsDevice::Instance()->BindTexture(0);
}

Rocket::Core::CompiledGeometryHandle RocketRenderer::CompileGeometry(Rocket::Core::Vertex* vertices, int numVertices, int* indices, int numIndices, Rocket::Core::TextureHandle texture)
{
    VertexBuffer* vertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatStatic, kVertexFormat_P_XYZ_RGBA_UV, numIndices);

    vertexBuffer->Lock();
    Vertex_PXYZ_RGBA_UV* vertexData = static_cast<Vertex_PXYZ_RGBA_UV*>(vertexBuffer->GetData());

    for (int i=0; i<numVertices; i++)
    {
        vertexData[i].position[0] = vertices[i].position.x;
        vertexData[i].position[1] = -vertices[i].position.y;
        vertexData[i].position[2] = 0.f;
        vertexData[i].color[0] = vertices[i].colour.red/255.f;
        vertexData[i].color[1] = vertices[i].colour.green/255.f;
        vertexData[i].color[2] = vertices[i].colour.blue/255.f;
        vertexData[i].color[3] = vertices[i].colour.alpha/255.f;
        vertexData[i].uv[0] = vertices[i].tex_coord.x;
        vertexData[i].uv[1] = vertices[i].tex_coord.y;
    }

    vertexBuffer->Unlock(numVertices);

    IndexBuffer* indexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatStatic, numIndices);

    indexBuffer->Lock();
    unsigned short* indexData = indexBuffer->GetData();

    for (int i=0; i<numIndices; i++)
    {
        indexData[i] = (unsigned short)indices[i];
    }

    indexBuffer->Unlock(numIndices);

    _BufferMap[vertexBuffer] = indexBuffer;
    _TextureMap[vertexBuffer] = (Texture*)texture;

    return (Rocket::Core::CompiledGeometryHandle)vertexBuffer;
}

void RocketRenderer::RenderCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry, const Rocket::Core::Vector2f& translation)
{
    VertexBuffer* vertexBuffer = (VertexBuffer*)geometry;
    IndexBuffer* indexBuffer = _BufferMap[vertexBuffer];
    Texture* texture = _TextureMap[vertexBuffer];

    if (texture->HasPremultipliedAlpha())
    {
        GraphicsDevice::Instance()->SetBlendMode(GraphicsDevice::kBlendOne, GraphicsDevice::kBlendOneMinusSourceAlpha);
    } else {
        GraphicsDevice::Instance()->SetBlendMode(GraphicsDevice::kBlendSourceAlpha, GraphicsDevice::kBlendOneMinusSourceAlpha);
    }

    glm::mat4x4 matrix = _Renderable->GetMVP();
    matrix = glm::scale(matrix, glm::vec3(1.f,1.f,1.f)/32.f);
    matrix = glm::translate(matrix, glm::vec3(-pb::GraphicsDevice::Instance()->GetDisplayResolution().x/2.f, pb::GraphicsDevice::Instance()->GetDisplayResolution().y/2.f, 0.f));
    matrix = glm::translate(matrix, glm::vec3(translation.x, -translation.y, 0));
    _ShaderPass->GetShaderProgram()->SetUniform("PB_ModelViewProj", matrix);

    GraphicsDevice::Instance()->BindIndexBuffer(indexBuffer);
    GraphicsDevice::Instance()->BindVertexBuffer(vertexBuffer);
    GraphicsDevice::Instance()->BindTexture(texture);
    GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementTriangles, indexBuffer->GetCurrentSize());
    GraphicsDevice::Instance()->BindIndexBuffer(0);
    GraphicsDevice::Instance()->BindVertexBuffer(0);
    GraphicsDevice::Instance()->BindTexture(0);
}

void RocketRenderer::ReleaseCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry)
{
    VertexBuffer* vertexBuffer = (VertexBuffer*)geometry;
    IndexBuffer* indexBuffer = _BufferMap[vertexBuffer];
    _BufferMap.erase(vertexBuffer);
    _TextureMap.erase(vertexBuffer);

    GraphicsDevice::Instance()->DestroyIndexBuffer(indexBuffer);
    GraphicsDevice::Instance()->DestroyVertexBuffer(vertexBuffer);
}

void RocketRenderer::EnableScissorRegion(bool enable)
{
    GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateScissor, enable);
}

void RocketRenderer::SetScissorRegion(int x, int y, int width, int height)
{
    GraphicsDevice::Instance()->SetScissor(glm::vec4(x, _Viewport->GetResolution().y-y-height, width, height));
}

bool RocketRenderer::LoadTexture(Rocket::Core::TextureHandle& textureHandle, Rocket::Core::Vector2i& textureDimensions, const Rocket::Core::String& source)
{
    std::string fileName = source.CString();

    Texture* texture = GraphicsDevice::Instance()->CreateTexture();

    if (!texture->LoadFromFile(pb::kFileLocationUser, fileName, false, false))
    {
        GraphicsDevice::Instance()->DestroyTexture(texture);
        return false;
    }

    textureHandle = (Rocket::Core::TextureHandle)texture;

    textureDimensions.x = texture->GetSize().x;
    textureDimensions.y = texture->GetSize().y;

    return true;
}

bool RocketRenderer::GenerateTexture(Rocket::Core::TextureHandle& textureHandle, const Rocket::Core::byte* source, const Rocket::Core::Vector2i& sourceDimensions)
{
    Texture* texture = GraphicsDevice::Instance()->CreateTexture();

    if (!texture->LoadFromBytes(source, sourceDimensions.x, sourceDimensions.y, false, Texture::kTextureFormatRGBA, false))
    {
        GraphicsDevice::Instance()->DestroyTexture(texture);
        return false;
    }

    textureHandle = (Rocket::Core::TextureHandle)texture;

    return true;
}

void RocketRenderer::ReleaseTexture(Rocket::Core::TextureHandle texture)
{
    if (texture)
    {
        GraphicsDevice::Instance()->DestroyTexture((Texture*)texture);
    }
}

float RocketRenderer::GetHorizontalTexelOffset()
{
    return 0.f;
}

float RocketRenderer::GetVerticalTexelOffset()
{
    return 0.f;
}

void RocketRenderer::Release()
{

}

void RocketRenderer::PurgeBuffer(bool force)
{

}

#endif
<|endoftext|>


<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008      Patrick Spendrin <ps_ml@gmx.de>
//

#include "tccore.h"
#include <TileLoaderHelper.h>
#include <global.h>
#include <QFile>
#include <cmath>
#include <QPainter>
#include <QProcess>
#include <QFileInfo>
#include <QDir>

using namespace Marble;

class TileCreatorSourceSrtm : public TileCreatorSource
{
public:
    TileCreatorSourceSrtm( const QString &sourceDir )
        : m_sourceDir( sourceDir )
    {
    }

    virtual QString sourcePath() const
    {
        return m_sourceDir;
    }

    virtual QSize fullImageSize() const
    {
        return QSize( 512*c_defaultTileSize*2, 512*c_defaultTileSize ); //512: 2**9 (9 zoom levels)
    }

    virtual QImage tile( int n, int m, int maxTileLevel )
    {
        Q_ASSERT( maxTileLevel == 9 );

        int  nmax = TileLoaderHelper::levelToRow( defaultLevelZeroRows, maxTileLevel );
        Q_ASSERT( nmax == 512 );
        int  mmax = TileLoaderHelper::levelToColumn( defaultLevelZeroColumns, maxTileLevel );

        //int  stdImageHeight  = nmax * c_defaultTileSize;
        //int  stdImageWidth  = mmax * c_defaultTileSize;
//n(lat)  m(lng)
//47      13

// for ( int n = 0; n < nmax; ++n ) {
//     for ( int m = 0; m < mmax; ++m ) {

        qDebug() << "**************************";
        qDebug() << "n" << n << "m" << m;

        qreal startLat = ( ( ( (qreal)n * 180 ) / nmax ) - 90 ) * -1;
        qreal startLng = ( ( (qreal)m * 360 ) / mmax ) - 180;
        qDebug() << "lat(n)(47)" << startLat;
        qDebug() << "lng(m)(13)" << startLng;

        int startLngPxResized = c_defaultTileSize * m;
        int startLatPxResized = c_defaultTileSize * n;

        QImage image( 2400, 2400, QImage::Format_ARGB32  );
        {
            QPainter painter( &image );
            QImage i = readHgt(std::floor(startLng), std::floor(startLat));
            painter.drawImage( 0, 0, i );
            painter.drawImage( 1200, 0, readHgt( std::floor(startLng)+1, std::floor(startLat) ) );
            painter.drawImage( 0, 1200, readHgt( std::floor(startLng), std::floor(startLat)-1 ) );
            painter.drawImage( 1200, 1200, readHgt( std::floor(startLng)+1, std::floor(startLat)-1 ) );
        }
        qDebug() << "got it";

        int imageSizeResized = 2400 * (512 * c_defaultTileSize) / (1200 * 180);

        // Pick the current row and smooth scale it
        // to make it match the expected size
        image = image.scaled( QSize(imageSizeResized, imageSizeResized),
                        Qt::IgnoreAspectRatio,
                        Qt::SmoothTransformation );

        //startL??Px: position in pixeln von dem was wir brauchen
        int startLngPx = startLng * 1200;
        startLngPx = ( 180 * 1200 ) + startLngPx;
        qDebug() << "startLngPx(/1200)" << (qreal)startLngPx / 1200;

        int startLatPx = startLat * 1200;
        startLatPx = ( 90 * 1200 ) - startLatPx;
        qDebug() << "startLatPx(/1200)" << (qreal)startLatPx / 1200;

        //imageL??Px: position in pixeln von image
        int imageLngPx = std::floor(startLng);
        imageLngPx = 180 + imageLngPx;
        qDebug() << "imageLngPx(/1200)" << imageLngPx << "*1200" << imageLngPx*1200;
        imageLngPx *= 1200;

        int imageLatPx = std::floor(90 - startLat);
        qDebug() << "imageLatPx(/1200)" << imageLatPx;
        imageLatPx *= 1200;

        qDebug() << "lng" << imageLngPx << startLngPx << "offset" << startLngPx - imageLngPx;
        qDebug() << "lat" << imageLatPx << startLatPx << "offset" << startLatPx - imageLatPx;
        Q_ASSERT(1200*2 - (startLngPx - imageLngPx) >= 675);
        Q_ASSERT(1200*2 - (startLatPx - imageLatPx) >= 675);
        Q_ASSERT(startLngPx - imageLngPx >= 0);
        Q_ASSERT(startLatPx - imageLatPx >= 0);

        int imageLngPxResized = imageLngPx * 1.6; //(512 * c_defaultTileSize) / (1200 * 180);
        int imageLatPxResized = imageLatPx * 1.6; //(512 * c_defaultTileSize) / (1200 * 180);
        qDebug() << "lng(m)" << startLngPxResized << imageLngPxResized << "diff" << startLngPxResized - imageLngPxResized;
        qDebug() << "lat(n)" << startLatPxResized << imageLngPxResized << "diff" << startLatPxResized - imageLatPxResized;
        Q_ASSERT(startLngPxResized - imageLngPxResized < imageSizeResized);
        Q_ASSERT(startLatPxResized - imageLatPxResized < imageSizeResized);
        Q_ASSERT(startLngPxResized - imageLngPxResized >= 0);
        Q_ASSERT(startLatPxResized - imageLatPxResized >= 0);

        QImage croppedImage = image.copy(startLngPx - imageLngPx, startLatPx - imageLatPx, 675, 675);
        QImage ret = image.copy(startLngPxResized - imageLngPxResized, startLatPxResized - imageLatPxResized, c_defaultTileSize, c_defaultTileSize);
        qDebug() << image.size() << ret.size();
//     }
// }
//         Q_ASSERT(false);
        return ret;
//         return QImage();
    }

private:
    QImage readHgt( int lng, int lat )
    {
        QChar EW( lng >= 0 ? 'E' : 'W' );
        QChar NS( lat >= 0 ? 'N' : 'S' );

        QString fileName = m_sourceDir; //"/home/niko/kdesvn/srtm2postgis/data/";
        fileName += "Eurasia/"; //TODO there is more than that
        if ( lat < 0 ) lat *= -1;
        fileName += QString( "%1%2%3%4.hgt" ).arg( NS ).arg( std::abs( lat ), 2, 10, QLatin1Char('0') )
                                    .arg( EW ).arg( std::abs( lng ), 3, 10, QLatin1Char('0' ) );
        qDebug() << fileName;
        QFile file( fileName );
        if ( !file.exists() && QFile::exists( fileName + ".zip" ) ) {
            qDebug() << "zip found, unzipping";
            QProcess p;
            p.setWorkingDirectory( QFileInfo(fileName).dir().absolutePath() );
            p.setWorkingDirectory( "/home/niko/kdesvn/srtm2postgis/data/Eurasia" );
            p.execute("unzip", QStringList() << fileName + ".zip" );
            qDebug() << QFile( QDir::currentPath() + "/" + QFileInfo( fileName ).fileName()).fileName();
            Q_ASSERT( QFile( QDir::currentPath() + "/" + QFileInfo( fileName ).fileName()).rename(fileName) );
            p.execute("pwd");

            p.waitForFinished();
        }
        if (!file.exists() ) {
            qDebug() << "hgt file does not exist, returing null image";
            return QImage();
        }
    //     qDebug() << fileName;
        file.open( QIODevice::ReadOnly );
        int iLat = 0;
        int iLng = 0;

        //eigentlich ist es 1201 groß, aber das letze pixel ist überlappung glaub ich
        QImage image( 1200, 1200, QImage::Format_ARGB32 );
        while(true) {
            QByteArray data = file.read( 2 );

            if ( iLng < 1200 ) {
                unsigned short height =  *(unsigned short*)data.data();
                height = ( height << 8 | height >> 8 );
                unsigned int pixel;
                pixel = height;
                pixel += 0xFF000000; //fully opaque
                image.setPixel( iLng, iLat, pixel );
            }

            if ( iLat >= 1199 && iLng >= 1199 ) break;

            iLng++;
            if ( iLng > 1200 ) { //hier nicht nur bis 1199 sondern eins mehr, wegen dem letzten überlappungspixel
                iLng = 0;
                iLat++;
            }
        }
        file.close();

        return image;
    }

    QString m_sourceDir;
};

TCCoreApplication::TCCoreApplication( int argc, char ** argv ) : QCoreApplication( argc, argv )
{

    if( !(argc < 2) )
    {
        TileCreatorSource *source = new TileCreatorSourceSrtm( argv[1] );
        m_tilecreator = new TileCreator( source, "false", argv[2] );
        connect( m_tilecreator, SIGNAL( finished() ), this, SLOT( quit() ) );
        m_tilecreator->start();
    }
}
<commit_msg>fix build<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008      Patrick Spendrin <ps_ml@gmx.de>
//

#include "tccore.h"
#include <TileLoaderHelper.h>
#include <global.h>
#include <QFile>
#include <cmath>
#include <QPainter>
#include <QProcess>
#include <QFileInfo>
#include <QDir>

using namespace Marble;

class TileCreatorSourceSrtm : public TileCreatorSource
{
public:
    TileCreatorSourceSrtm( const QString &sourceDir )
        : m_sourceDir( sourceDir )
    {
    }

    virtual QString sourcePath() const
    {
        return m_sourceDir;
    }

    virtual QSize fullImageSize() const
    {
        return QSize( 512*c_defaultTileSize*2, 512*c_defaultTileSize ); //512: 2**9 (9 zoom levels)
    }

    virtual QImage tile( int n, int m, int maxTileLevel )
    {
        Q_ASSERT( maxTileLevel == 9 );

        int  nmax = TileLoaderHelper::levelToRow( defaultLevelZeroRows, maxTileLevel );
        Q_ASSERT( nmax == 512 );
        int  mmax = TileLoaderHelper::levelToColumn( defaultLevelZeroColumns, maxTileLevel );

        //int  stdImageHeight  = nmax * c_defaultTileSize;
        //int  stdImageWidth  = mmax * c_defaultTileSize;
//n(lat)  m(lng)
//47      13

// for ( int n = 0; n < nmax; ++n ) {
//     for ( int m = 0; m < mmax; ++m ) {

        qDebug() << "**************************";
        qDebug() << "n" << n << "m" << m;

        qreal startLat = ( ( ( (qreal)n * 180 ) / nmax ) - 90 ) * -1;
        qreal startLng = ( ( (qreal)m * 360 ) / mmax ) - 180;
        qDebug() << "lat(n)(47)" << startLat;
        qDebug() << "lng(m)(13)" << startLng;

        int startLngPxResized = c_defaultTileSize * m;
        int startLatPxResized = c_defaultTileSize * n;

        QImage image( 2400, 2400, QImage::Format_ARGB32  );
        {
            QPainter painter( &image );
            QImage i = readHgt(std::floor(startLng), std::floor(startLat));
            painter.drawImage( 0, 0, i );
            painter.drawImage( 1200, 0, readHgt( std::floor(startLng)+1, std::floor(startLat) ) );
            painter.drawImage( 0, 1200, readHgt( std::floor(startLng), std::floor(startLat)-1 ) );
            painter.drawImage( 1200, 1200, readHgt( std::floor(startLng)+1, std::floor(startLat)-1 ) );
        }
        qDebug() << "got it";

        int imageSizeResized = 2400 * (512 * c_defaultTileSize) / (1200 * 180);

        // Pick the current row and smooth scale it
        // to make it match the expected size
        image = image.scaled( QSize(imageSizeResized, imageSizeResized),
                        Qt::IgnoreAspectRatio,
                        Qt::SmoothTransformation );

        //startL??Px: position in pixeln von dem was wir brauchen
        int startLngPx = startLng * 1200;
        startLngPx = ( 180 * 1200 ) + startLngPx;
        qDebug() << "startLngPx(/1200)" << (qreal)startLngPx / 1200;

        int startLatPx = startLat * 1200;
        startLatPx = ( 90 * 1200 ) - startLatPx;
        qDebug() << "startLatPx(/1200)" << (qreal)startLatPx / 1200;

        //imageL??Px: position in pixeln von image
        int imageLngPx = std::floor(startLng);
        imageLngPx = 180 + imageLngPx;
        qDebug() << "imageLngPx(/1200)" << imageLngPx << "*1200" << imageLngPx*1200;
        imageLngPx *= 1200;

        int imageLatPx = std::floor(90 - startLat);
        qDebug() << "imageLatPx(/1200)" << imageLatPx;
        imageLatPx *= 1200;

        qDebug() << "lng" << imageLngPx << startLngPx << "offset" << startLngPx - imageLngPx;
        qDebug() << "lat" << imageLatPx << startLatPx << "offset" << startLatPx - imageLatPx;
        Q_ASSERT(1200*2 - (startLngPx - imageLngPx) >= 675);
        Q_ASSERT(1200*2 - (startLatPx - imageLatPx) >= 675);
        Q_ASSERT(startLngPx - imageLngPx >= 0);
        Q_ASSERT(startLatPx - imageLatPx >= 0);

        int imageLngPxResized = imageLngPx * 1.6; //(512 * c_defaultTileSize) / (1200 * 180);
        int imageLatPxResized = imageLatPx * 1.6; //(512 * c_defaultTileSize) / (1200 * 180);
        qDebug() << "lng(m)" << startLngPxResized << imageLngPxResized << "diff" << startLngPxResized - imageLngPxResized;
        qDebug() << "lat(n)" << startLatPxResized << imageLngPxResized << "diff" << startLatPxResized - imageLatPxResized;
        Q_ASSERT(startLngPxResized - imageLngPxResized < imageSizeResized);
        Q_ASSERT(startLatPxResized - imageLatPxResized < imageSizeResized);
        Q_ASSERT(startLngPxResized - imageLngPxResized >= 0);
        Q_ASSERT(startLatPxResized - imageLatPxResized >= 0);

        QImage croppedImage = image.copy(startLngPx - imageLngPx, startLatPx - imageLatPx, 675, 675);
        QImage ret = image.copy(startLngPxResized - imageLngPxResized, startLatPxResized - imageLatPxResized, c_defaultTileSize, c_defaultTileSize);
        qDebug() << image.size() << ret.size();
//     }
// }
//         Q_ASSERT(false);
        return ret;
//         return QImage();
    }

private:
    QImage readHgt( int lng, int lat )
    {
        QChar EW( lng >= 0 ? 'E' : 'W' );
        QChar NS( lat >= 0 ? 'N' : 'S' );

        QString fileName = m_sourceDir; //"/home/niko/kdesvn/srtm2postgis/data/";
        fileName += "Eurasia/"; //TODO there is more than that
        if ( lat < 0 ) lat *= -1;
        fileName += QString( "%1%2%3%4.hgt" ).arg( NS ).arg( lat<0 ? lat*-1 : lat, 2, 10, QLatin1Char('0') )
                                    .arg( EW ).arg( lng<0 ? lng*-1 : lng, 3, 10, QLatin1Char('0' ) );
        qDebug() << fileName;
        QFile file( fileName );
        if ( !file.exists() && QFile::exists( fileName + ".zip" ) ) {
            qDebug() << "zip found, unzipping";
            QProcess p;
            p.setWorkingDirectory( QFileInfo(fileName).dir().absolutePath() );
            p.setWorkingDirectory( "/home/niko/kdesvn/srtm2postgis/data/Eurasia" );
            p.execute("unzip", QStringList() << fileName + ".zip" );
            qDebug() << QFile( QDir::currentPath() + "/" + QFileInfo( fileName ).fileName()).fileName();
            Q_ASSERT( QFile( QDir::currentPath() + "/" + QFileInfo( fileName ).fileName()).rename(fileName) );
            p.execute("pwd");

            p.waitForFinished();
        }
        if (!file.exists() ) {
            qDebug() << "hgt file does not exist, returing null image";
            return QImage();
        }
    //     qDebug() << fileName;
        file.open( QIODevice::ReadOnly );
        int iLat = 0;
        int iLng = 0;

        //eigentlich ist es 1201 groß, aber das letze pixel ist überlappung glaub ich
        QImage image( 1200, 1200, QImage::Format_ARGB32 );
        while(true) {
            QByteArray data = file.read( 2 );

            if ( iLng < 1200 ) {
                unsigned short height =  *(unsigned short*)data.data();
                height = ( height << 8 | height >> 8 );
                unsigned int pixel;
                pixel = height;
                pixel += 0xFF000000; //fully opaque
                image.setPixel( iLng, iLat, pixel );
            }

            if ( iLat >= 1199 && iLng >= 1199 ) break;

            iLng++;
            if ( iLng > 1200 ) { //hier nicht nur bis 1199 sondern eins mehr, wegen dem letzten überlappungspixel
                iLng = 0;
                iLat++;
            }
        }
        file.close();

        return image;
    }

    QString m_sourceDir;
};

TCCoreApplication::TCCoreApplication( int argc, char ** argv ) : QCoreApplication( argc, argv )
{

    if( !(argc < 2) )
    {
        TileCreatorSource *source = new TileCreatorSourceSrtm( argv[1] );
        m_tilecreator = new TileCreator( source, "false", argv[2] );
        connect( m_tilecreator, SIGNAL( finished() ), this, SLOT( quit() ) );
        m_tilecreator->start();
    }
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/common/include/p9_obus_scom_addresses_fixes.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file obus_scom_addresses_fixes.H
/// @brief The *scom_addresses.H files are  generated form figtree, but
///        the figree can be wrong.  This file is included at the end
///        of scom_addresses.H and allows incorrect constants to be
///        fixed manually.
///
///
// *HWP HWP Owner: Ben Gass <bgass@us.ibm.com>
// *HWP FW Owner: ? <?>
// *HWP Team: SAO
// *HWP Level: 1
// *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE

#ifndef __P9_OBUS_SCOM_ADDRESSES_FIXES_H
#define __P9_OBUS_SCOM_ADDRESSES_FIXES_H

//Example,
//Copy the whole line from the *scom_addresses.H file.  Then add
//FIX in front of REG, and add another paramter that is the new
//corrected value.
//FIXREG64( PU_ALTD_ADDR_REG,
//          RULL(0x05022800), SH_UNT, SH_ACS_SCOM,
//          RULL(0x00090000)
//        );

static const uint64_t SH_UNT_OBUS_1 = 514;
static const uint64_t SH_UNT_OBUS_2 = 515;

REG64( OBUS_1_LL3_IOOL_CONTROL,
       RULL(0x0A01080B), SH_UNT_OBUS_1, SH_ACS_SCOM );
REG64( OBUS_2_LL3_IOOL_CONTROL,
       RULL(0x0B01080B), SH_UNT_OBUS_2, SH_ACS_SCOM );

#endif
<commit_msg>L2 - Fabric updates for multi-chip support<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/common/include/p9_obus_scom_addresses_fixes.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file obus_scom_addresses_fixes.H
/// @brief The *scom_addresses.H files are  generated form figtree, but
///        the figree can be wrong.  This file is included at the end
///        of scom_addresses.H and allows incorrect constants to be
///        fixed manually.
///
///
// *HWP HWP Owner: Ben Gass <bgass@us.ibm.com>
// *HWP FW Owner: ? <?>
// *HWP Team: SAO
// *HWP Level: 1
// *HWP Consumed by: FSP:HB:HS:OCC:SBE:CME:SGPE:PGPE:FPPE:IPPE

#ifndef __P9_OBUS_SCOM_ADDRESSES_FIXES_H
#define __P9_OBUS_SCOM_ADDRESSES_FIXES_H

//Example,
//Copy the whole line from the *scom_addresses.H file.  Then add
//FIX in front of REG, and add another paramter that is the new
//corrected value.
//FIXREG64( PU_ALTD_ADDR_REG,
//          RULL(0x05022800), SH_UNT, SH_ACS_SCOM,
//          RULL(0x00090000)
//        );

static const uint64_t SH_UNT_OBUS_1 = 514;
static const uint64_t SH_UNT_OBUS_2 = 515;

REG64( OBUS_1_LL1_IOOL_CONTROL,
       RULL(0x0A01080B), SH_UNT_OBUS_1, SH_ACS_SCOM );
REG64( OBUS_1_LL1_LL1_LL1_PB_IOOL_FIR_REG,
       RULL(0x0A010800), SH_UNT_OBUS_2, SH_ACS_SCOM );

REG64( OBUS_2_LL2_IOOL_CONTROL,
       RULL(0x0B01080B), SH_UNT_OBUS_2, SH_ACS_SCOM );
REG64( OBUS_2_LL2_LL2_LL2_PB_IOOL_FIR_REG,
       RULL(0x0B010800), SH_UNT_OBUS_2, SH_ACS_SCOM );

#endif
<|endoftext|>


<commit_before>
// FloodyFluidSimulator.cpp

// Interfaces to the cFloodyFluidSimulator that represents a fluid simulator that tries to flood everything :)
// http://forum.mc-server.org/showthread.php?tid=565

#include "Globals.h"

#include "FloodyFluidSimulator.h"
#include "../World.h"
#include "../BlockArea.h"
#include "../Blocks/BlockHandler.h"

// Enable or disable detailed logging
#if 1
	#define FLOG LOG
#else
	#define FLOG(...)
#endif

cFloodyFluidSimulator::cFloodyFluidSimulator(cWorld * a_World, BLOCKTYPE a_Fluid, BLOCKTYPE a_StationaryFluid, NIBBLETYPE a_Falloff, int a_TickDelay) :
	super(a_World, a_Fluid, a_StationaryFluid, a_TickDelay),
	m_Falloff(a_Falloff)
{
}

void cFloodyFluidSimulator::SimulateBlock(int a_BlockX, int a_BlockY, int a_BlockZ)
{
	FLOG("Simulating block {%d, %d, %d}", a_BlockX, a_BlockY, a_BlockZ);

	cBlockArea Area;
	int MinBlockY = std::max(0, a_BlockY - 1);
	int MaxBlockY = std::min(cChunkDef::Height, a_BlockY + 1);
	if (!Area.Read(m_World, a_BlockX - 1, a_BlockX + 1, MinBlockY, MaxBlockY, a_BlockZ - 1, a_BlockZ + 1))
	{
		// Cannot read the immediate neighborhood, probably too close to an unloaded chunk. Bail out.
		// TODO: Shouldn't we re-schedule?
		FLOG("  Cannot read area, bailing out.");
		return;
	}
	int y = (a_BlockY > 0) ? 1 : 0;  // Relative y-coord of this block in Area

	NIBBLETYPE MyMeta = Area.GetRelBlockMeta(1, y, 1);
	if (!IsAnyFluidBlock(Area.GetRelBlockType(1, y, 1)))
	{
		// Can happen - if a block is scheduled for simulating and gets replaced in the meantime.
		FLOG("  Not my type: exp %d, got %d", m_FluidBlock, Area.GetRelBlockType(1, y, 1));
		return;
	}

	if (MyMeta != 0)
	{
		if (CheckTributaries(a_BlockX, a_BlockY, a_BlockZ, Area, MyMeta))
		{
			return;
		}
	}

	// New meta for the spreading to neighbors:
	// If this is a source block or was falling, the new meta is just the falloff
	// Otherwise it is the current meta plus falloff (may be larger than max height, will be checked later)
	NIBBLETYPE NewMeta = ((MyMeta == 0) || ((MyMeta & 0x08) != 0)) ? m_Falloff : (MyMeta + m_Falloff);

	BLOCKTYPE Below = Area.GetRelBlockType(1, 0, 1);
	if ((a_BlockY > 0) && (IsPassableForFluid(Below) || IsBlockLava(Below) || IsBlockWater(Below)))
	{
		// Spread only down, possibly washing away what's there or turning lava to stone / cobble / obsidian:
		SpreadToNeighbor(a_BlockX, a_BlockY - 1, a_BlockZ, Area, 8);
	}
	else if (NewMeta < 8)   // Can reach there
	{
		// Spread to the neighbors:
		SpreadToNeighbor(a_BlockX - 1, a_BlockY, a_BlockZ,     Area, NewMeta);
		SpreadToNeighbor(a_BlockX + 1, a_BlockY, a_BlockZ,     Area, NewMeta);
		SpreadToNeighbor(a_BlockX,     a_BlockY, a_BlockZ - 1, Area, NewMeta);
		SpreadToNeighbor(a_BlockX,     a_BlockY, a_BlockZ + 1, Area, NewMeta);
	}

	// Mark as processed:
	m_World->FastSetBlock(a_BlockX, a_BlockY, a_BlockZ, m_StationaryFluidBlock, MyMeta);
}

bool cFloodyFluidSimulator::CheckTributaries(int a_BlockX, int a_BlockY, int a_BlockZ, const cBlockArea & a_Area, NIBBLETYPE a_MyMeta)
{
	bool IsFed = false;
	int y = (a_BlockY > 0) ? 1 : 0;  // Relative y-coord of this block in Area

	// If we have a section above, check if there's fluid above this block that would feed it:
	if (a_BlockY < cChunkDef::Height - 1)
	{
		IsFed = IsAnyFluidBlock(a_Area.GetRelBlockType(1, 2, 1));
	}

	// If not fed from above, check if there's a feed from the side:
	if (!IsFed)
	{
		IsFed = (
			(IsAllowedBlock(a_Area.GetRelBlockType(0, y, 1)) && IsHigherMeta(a_Area.GetRelBlockMeta(0, y, 1), a_MyMeta)) ||
			(IsAllowedBlock(a_Area.GetRelBlockType(2, y, 1)) && IsHigherMeta(a_Area.GetRelBlockMeta(2, y, 1), a_MyMeta)) ||
			(IsAllowedBlock(a_Area.GetRelBlockType(1, y, 0)) && IsHigherMeta(a_Area.GetRelBlockMeta(1, y, 0), a_MyMeta)) ||
			(IsAllowedBlock(a_Area.GetRelBlockType(1, y, 2)) && IsHigherMeta(a_Area.GetRelBlockMeta(1, y, 2), a_MyMeta))
		);
	}

	// If not fed, decrease by m_Falloff levels:
	if (!IsFed)
	{
		FLOG("  Not fed, decreasing from %d to %d", a_MyMeta, a_MyMeta + m_Falloff);

		a_MyMeta += m_Falloff;
		if (a_MyMeta < 8)
		{
			m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, m_StationaryFluidBlock, a_MyMeta);
		}
		else
		{
			m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_AIR, 0);
		}
		return true;
	}
	return false;
}

void cFloodyFluidSimulator::SpreadToNeighbor(int a_BlockX, int a_BlockY, int a_BlockZ, const cBlockArea & a_Area, NIBBLETYPE a_NewMeta)
{
	ASSERT(a_NewMeta <= 8);  // Invalid meta values
	ASSERT(a_NewMeta > 0);  // Source blocks aren't spread

	BLOCKTYPE Block = a_Area.GetBlockType(a_BlockX, a_BlockY, a_BlockZ);

	if (IsAllowedBlock(Block))
	{
		NIBBLETYPE Meta = a_Area.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ);
		if ((Meta == a_NewMeta) || IsHigherMeta(Meta, a_NewMeta))
		{
			// Don't spread there, there's already a higher or same level there
			return;
		}
	}

	// Check water - lava interaction:
	if (m_FluidBlock == E_BLOCK_LAVA)
	{
		if (IsBlockWater(Block))
		{
			// Lava flowing into water, change to stone / cobblestone based on direction:
			BLOCKTYPE NewBlock = (a_NewMeta == 8) ? E_BLOCK_STONE : E_BLOCK_COBBLESTONE;
			FLOG("  Lava flowing into water, turning water at {%d, %d, %d} into stone",
				a_BlockX, a_BlockY, a_BlockZ,
				ItemTypeToString(NewBlock).c_str()
			);
			m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, NewBlock, 0);

			// TODO: Sound effect

			return;
		}
	}
	else if (m_FluidBlock == E_BLOCK_WATER)
	{
		if (IsBlockLava(Block))
		{
			// Water flowing into lava, change to cobblestone / obsidian based on dest block:
			BLOCKTYPE NewBlock = (a_Area.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) == 0) ? E_BLOCK_OBSIDIAN : E_BLOCK_COBBLESTONE;
			FLOG("  Water flowing into lava, turning lava at {%d, %d, %d} into %s",
				a_BlockX, a_BlockY, a_BlockZ, ItemTypeToString(NewBlock).c_str()
			);
			m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, NewBlock, 0);

			// TODO: Sound effect

			return;
		}
	}
	else
	{
		ASSERT(!"Unknown fluid!");
	}

	if (!IsPassableForFluid(Block))
	{
		// Can't spread there
		return;
	}

	// Wash away the block there, if possible:
	if (CanWashAway(Block))
	{
		cBlockHandler * Handler = BlockHandler(Block);
		if (Handler->DoesDropOnUnsuitable())
		{
			Handler->DropBlock(m_World, a_BlockX, a_BlockY, a_BlockZ);
		}
	}

	// Spread:
	FLOG("  Spreading to {%d, %d, %d} with meta %d", a_BlockX, a_BlockY, a_BlockZ, a_NewMeta);
	m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, m_FluidBlock, a_NewMeta);
}

<commit_msg>Decreased logging in floody fluid simulator.<commit_after>
// FloodyFluidSimulator.cpp

// Interfaces to the cFloodyFluidSimulator that represents a fluid simulator that tries to flood everything :)
// http://forum.mc-server.org/showthread.php?tid=565

#include "Globals.h"

#include "FloodyFluidSimulator.h"
#include "../World.h"
#include "../BlockArea.h"
#include "../Blocks/BlockHandler.h"

// Enable or disable detailed logging
#if 1
	#define FLOG LOGD
#else
	#define FLOG(...)
#endif

cFloodyFluidSimulator::cFloodyFluidSimulator(cWorld * a_World, BLOCKTYPE a_Fluid, BLOCKTYPE a_StationaryFluid, NIBBLETYPE a_Falloff, int a_TickDelay) :
	super(a_World, a_Fluid, a_StationaryFluid, a_TickDelay),
	m_Falloff(a_Falloff)
{
}

void cFloodyFluidSimulator::SimulateBlock(int a_BlockX, int a_BlockY, int a_BlockZ)
{
	FLOG("Simulating block {%d, %d, %d}", a_BlockX, a_BlockY, a_BlockZ);

	cBlockArea Area;
	int MinBlockY = std::max(0, a_BlockY - 1);
	int MaxBlockY = std::min(cChunkDef::Height, a_BlockY + 1);
	if (!Area.Read(m_World, a_BlockX - 1, a_BlockX + 1, MinBlockY, MaxBlockY, a_BlockZ - 1, a_BlockZ + 1))
	{
		// Cannot read the immediate neighborhood, probably too close to an unloaded chunk. Bail out.
		// TODO: Shouldn't we re-schedule?
		FLOG("  Cannot read area, bailing out.");
		return;
	}
	int y = (a_BlockY > 0) ? 1 : 0;  // Relative y-coord of this block in Area

	NIBBLETYPE MyMeta = Area.GetRelBlockMeta(1, y, 1);
	if (!IsAnyFluidBlock(Area.GetRelBlockType(1, y, 1)))
	{
		// Can happen - if a block is scheduled for simulating and gets replaced in the meantime.
		FLOG("  Not my type: exp %d, got %d", m_FluidBlock, Area.GetRelBlockType(1, y, 1));
		return;
	}

	if (MyMeta != 0)
	{
		if (CheckTributaries(a_BlockX, a_BlockY, a_BlockZ, Area, MyMeta))
		{
			return;
		}
	}

	// New meta for the spreading to neighbors:
	// If this is a source block or was falling, the new meta is just the falloff
	// Otherwise it is the current meta plus falloff (may be larger than max height, will be checked later)
	NIBBLETYPE NewMeta = ((MyMeta == 0) || ((MyMeta & 0x08) != 0)) ? m_Falloff : (MyMeta + m_Falloff);

	BLOCKTYPE Below = Area.GetRelBlockType(1, 0, 1);
	if ((a_BlockY > 0) && (IsPassableForFluid(Below) || IsBlockLava(Below) || IsBlockWater(Below)))
	{
		// Spread only down, possibly washing away what's there or turning lava to stone / cobble / obsidian:
		SpreadToNeighbor(a_BlockX, a_BlockY - 1, a_BlockZ, Area, 8);
	}
	else if (NewMeta < 8)   // Can reach there
	{
		// Spread to the neighbors:
		SpreadToNeighbor(a_BlockX - 1, a_BlockY, a_BlockZ,     Area, NewMeta);
		SpreadToNeighbor(a_BlockX + 1, a_BlockY, a_BlockZ,     Area, NewMeta);
		SpreadToNeighbor(a_BlockX,     a_BlockY, a_BlockZ - 1, Area, NewMeta);
		SpreadToNeighbor(a_BlockX,     a_BlockY, a_BlockZ + 1, Area, NewMeta);
	}

	// Mark as processed:
	m_World->FastSetBlock(a_BlockX, a_BlockY, a_BlockZ, m_StationaryFluidBlock, MyMeta);
}

bool cFloodyFluidSimulator::CheckTributaries(int a_BlockX, int a_BlockY, int a_BlockZ, const cBlockArea & a_Area, NIBBLETYPE a_MyMeta)
{
	bool IsFed = false;
	int y = (a_BlockY > 0) ? 1 : 0;  // Relative y-coord of this block in Area

	// If we have a section above, check if there's fluid above this block that would feed it:
	if (a_BlockY < cChunkDef::Height - 1)
	{
		IsFed = IsAnyFluidBlock(a_Area.GetRelBlockType(1, 2, 1));
	}

	// If not fed from above, check if there's a feed from the side:
	if (!IsFed)
	{
		IsFed = (
			(IsAllowedBlock(a_Area.GetRelBlockType(0, y, 1)) && IsHigherMeta(a_Area.GetRelBlockMeta(0, y, 1), a_MyMeta)) ||
			(IsAllowedBlock(a_Area.GetRelBlockType(2, y, 1)) && IsHigherMeta(a_Area.GetRelBlockMeta(2, y, 1), a_MyMeta)) ||
			(IsAllowedBlock(a_Area.GetRelBlockType(1, y, 0)) && IsHigherMeta(a_Area.GetRelBlockMeta(1, y, 0), a_MyMeta)) ||
			(IsAllowedBlock(a_Area.GetRelBlockType(1, y, 2)) && IsHigherMeta(a_Area.GetRelBlockMeta(1, y, 2), a_MyMeta))
		);
	}

	// If not fed, decrease by m_Falloff levels:
	if (!IsFed)
	{
		FLOG("  Not fed, decreasing from %d to %d", a_MyMeta, a_MyMeta + m_Falloff);

		a_MyMeta += m_Falloff;
		if (a_MyMeta < 8)
		{
			m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, m_StationaryFluidBlock, a_MyMeta);
		}
		else
		{
			m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_AIR, 0);
		}
		return true;
	}
	return false;
}

void cFloodyFluidSimulator::SpreadToNeighbor(int a_BlockX, int a_BlockY, int a_BlockZ, const cBlockArea & a_Area, NIBBLETYPE a_NewMeta)
{
	ASSERT(a_NewMeta <= 8);  // Invalid meta values
	ASSERT(a_NewMeta > 0);  // Source blocks aren't spread

	BLOCKTYPE Block = a_Area.GetBlockType(a_BlockX, a_BlockY, a_BlockZ);

	if (IsAllowedBlock(Block))
	{
		NIBBLETYPE Meta = a_Area.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ);
		if ((Meta == a_NewMeta) || IsHigherMeta(Meta, a_NewMeta))
		{
			// Don't spread there, there's already a higher or same level there
			return;
		}
	}

	// Check water - lava interaction:
	if (m_FluidBlock == E_BLOCK_LAVA)
	{
		if (IsBlockWater(Block))
		{
			// Lava flowing into water, change to stone / cobblestone based on direction:
			BLOCKTYPE NewBlock = (a_NewMeta == 8) ? E_BLOCK_STONE : E_BLOCK_COBBLESTONE;
			FLOG("  Lava flowing into water, turning water at {%d, %d, %d} into stone",
				a_BlockX, a_BlockY, a_BlockZ,
				ItemTypeToString(NewBlock).c_str()
			);
			m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, NewBlock, 0);

			// TODO: Sound effect

			return;
		}
	}
	else if (m_FluidBlock == E_BLOCK_WATER)
	{
		if (IsBlockLava(Block))
		{
			// Water flowing into lava, change to cobblestone / obsidian based on dest block:
			BLOCKTYPE NewBlock = (a_Area.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ) == 0) ? E_BLOCK_OBSIDIAN : E_BLOCK_COBBLESTONE;
			FLOG("  Water flowing into lava, turning lava at {%d, %d, %d} into %s",
				a_BlockX, a_BlockY, a_BlockZ, ItemTypeToString(NewBlock).c_str()
			);
			m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, NewBlock, 0);

			// TODO: Sound effect

			return;
		}
	}
	else
	{
		ASSERT(!"Unknown fluid!");
	}

	if (!IsPassableForFluid(Block))
	{
		// Can't spread there
		return;
	}

	// Wash away the block there, if possible:
	if (CanWashAway(Block))
	{
		cBlockHandler * Handler = BlockHandler(Block);
		if (Handler->DoesDropOnUnsuitable())
		{
			Handler->DropBlock(m_World, a_BlockX, a_BlockY, a_BlockZ);
		}
	}

	// Spread:
	FLOG("  Spreading to {%d, %d, %d} with meta %d", a_BlockX, a_BlockY, a_BlockZ, a_NewMeta);
	m_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, m_FluidBlock, a_NewMeta);
}

<|endoftext|>