<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/kernel/ipc.C $                                            */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2013,2020                        */
/* [+] 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                                                     */
#include <arch/ppc.H>
#include <kernel/ipc.H>
#include <kernel/cpu.H>
#include <kernel/intmsghandler.H>
#include <kernel/console.H>
#include <errno.h>
#include <kernel/doorbell.H>
#include <assert.h>

using namespace KernelIpc;

// The base divisor (common to both modes) is everything until the 4 bits of topology ID. Converting bits into total
// values, this is 2 (reserved) * 32 (cores) * 4 (threads)
//
// To get the rest of the divisor we consider the mode.
// Mode 0 = GGGC, also known as chip=node mode
// Since C is the node number and it's not used (always zero) simply divide the PIR by a value larger than it
// to always get 0 for the node number.
#define TOPOLOGY_MODE_0_NODE_DIVISOR (16 * 2 * 32 * 4)
// Mode 1 = GGCC, also known as chip=group mode
// GG are the bits the represent the node number so divide by the value that leaves only GG as the remainder.
#define TOPOLOGY_MODE_1_NODE_DIVISOR (4 * 2 * 32 * 4)

TARGETING::topoMode_t g_topology_mode = TARGETING::PROC_FABRIC_TOPOLOGY_MODE_INVALID;

/**
 * IPC communication area. Interrupt service provider initializes.
 * @see intrrp.C
 */
KernelIpc::ipc_data_area_t KernelIpc::ipc_data_area;

// Put the IPC message in the other nodes memory space
//    Two potential issues:
//    1. The destination node is not there - memory location is nonexistant.
//    2. The destination node never responds, potentially hanging this thread.
int KernelIpc::send(uint64_t i_q, msg_t * i_msg)
{
    // the destination node is a 3 bit field encoded in the 64 bit queue id
    // big endian bits 29:31, ie, xxxx_xxxN__xxxx_xxxx
    // extract it from the appropriate field
    uint64_t dest_node = ((i_q >> 32) &
                         (internode_info_vals_t::MAX_NODES_PER_SYS - 1));

    ipc_data_area_t * p_dest = ipc_data_area.remote_ipc_data_addr[dest_node];
    printkd("IPC Dest addr %px Q_id:%lx dest_node:%.lx\n",
            p_dest,i_q, dest_node);

    // validate destination address
    if ( (p_dest == nullptr ) ||
         ((reinterpret_cast<uint64_t>(p_dest) &
                 IPC_INVALID_REMOTE_ADDR_MASK) ==
           IPC_INVALID_REMOTE_ADDR))
    {
        return( EINVAL);
    }

    // get lock on IPC data area in other node
    if(false == __sync_bool_compare_and_swap(&(p_dest->msg_queue_id),
                                                IPC_DATA_AREA_CLEAR,
                                                IPC_DATA_AREA_LOCKED))
    {
        return -EAGAIN;
    }

    p_dest->msg_payload = *i_msg;  // copy in message
    lwsync();

    p_dest->msg_queue_id = i_q;    // set destination queue id
    lwsync();

    printk("IPC to PIR %x\n",p_dest->pir);

    // send doorbell to interrupt the other drawer
    send_doorbell_ipc(p_dest->pir);

    // The message allocation is freed here to make msg_send for IPC
    // messages behave the same as non-IPC msg_send; that is, the message
    // is freed by the consumer; however, i_msg was allocated in user space
    // code and freed here in kernel space. The assumption is that this is OK.
    msg_free(i_msg);

    return 0;
}

// update the address this IPC instance will use to send messages
//  to a remote node
int KernelIpc::updateRemoteIpcAddr(uint64_t i_Node, uint64_t i_RemoteAddr)
{
    int rc;
    if // input node is valid
      (i_Node < internode_info_vals_t::MAX_NODES_PER_SYS)
    {
        // update local array entry
        rc = 0;
        printk("IPC ADDR %d = 0x%lx\n", (int)i_Node, i_RemoteAddr);
        ipc_data_area.remote_ipc_data_addr[i_Node] =
                reinterpret_cast<ipc_data_area_t*>(i_RemoteAddr);
    }
    else
    {
        rc = EINVAL;
        printk("updateRemoteAddr() Invalid input node: %lx\n",i_Node);
    }

    return(rc);
}

// query the node and remote address other nodes will use to send
//  messages to this IPC instance
int KernelIpc::qryLocalIpcInfo(uint64_t * i_pONode, uint64_t * i_pOAddr)
{
    // determine node and remote address
    uint64_t l_localNode = 0;

    if (g_topology_mode == PROC_FABRIC_TOPOLOGY_MODE_MODE0)
    {
        l_localNode = getPIR()/TOPOLOGY_MODE_0_NODE_DIVISOR;
    }
    else if (g_topology_mode == PROC_FABRIC_TOPOLOGY_MODE_MODE1)
    {
        l_localNode = getPIR()/TOPOLOGY_MODE_1_NODE_DIVISOR;
    }
    else
    {
        // Topology Mode was not setup yet.
        crit_assert(false);
    }

    uint64_t l_localAddr = reinterpret_cast<uint64_t>(&ipc_data_area);
    uint64_t l_hrmor = getHRMOR();

    uint64_t l_oAddr = (( l_localAddr +
                          l_hrmor ) |
                          0x8000000000000000ul);

    *i_pONode = l_localNode;
    *i_pOAddr = l_oAddr;

    return(0);
}

void KernelIpc::setTopologyMode(TARGETING::topoMode_t const i_topologyMode)
{
    g_topology_mode = i_topologyMode;
    printk("Topology Mode = %d\n",g_topology_mode);
}

<commit_msg>Remove confusing comments from ipc.C regarding topoId<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/kernel/ipc.C $                                            */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2013,2020                        */
/* [+] 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                                                     */
#include <arch/ppc.H>
#include <kernel/ipc.H>
#include <kernel/cpu.H>
#include <kernel/intmsghandler.H>
#include <kernel/console.H>
#include <errno.h>
#include <kernel/doorbell.H>
#include <assert.h>

using namespace KernelIpc;

// The base divisor (common to both modes) is everything until the 4 bits of topology ID. Converting bits into total
// values, this is 2 (reserved) * 32 (cores) * 4 (threads)
//
// To get the rest of the divisor we consider the mode.
// Mode 0 = GGGC, C is the node number and it's not used (always zero) simply divide the PIR by a value larger
// than it to always get 0 for the node number.
#define TOPOLOGY_MODE_0_NODE_DIVISOR (16 * 2 * 32 * 4)
// Mode 1 = GGCC, GG are the bits the represent the node number so divide by the value that leaves only GG as the
// remainder.
#define TOPOLOGY_MODE_1_NODE_DIVISOR (4 * 2 * 32 * 4)

TARGETING::topoMode_t g_topology_mode = TARGETING::PROC_FABRIC_TOPOLOGY_MODE_INVALID;

/**
 * IPC communication area. Interrupt service provider initializes.
 * @see intrrp.C
 */
KernelIpc::ipc_data_area_t KernelIpc::ipc_data_area;

// Put the IPC message in the other nodes memory space
//    Two potential issues:
//    1. The destination node is not there - memory location is nonexistant.
//    2. The destination node never responds, potentially hanging this thread.
int KernelIpc::send(uint64_t i_q, msg_t * i_msg)
{
    // the destination node is a 3 bit field encoded in the 64 bit queue id
    // big endian bits 29:31, ie, xxxx_xxxN__xxxx_xxxx
    // extract it from the appropriate field
    uint64_t dest_node = ((i_q >> 32) &
                         (internode_info_vals_t::MAX_NODES_PER_SYS - 1));

    ipc_data_area_t * p_dest = ipc_data_area.remote_ipc_data_addr[dest_node];
    printkd("IPC Dest addr %px Q_id:%lx dest_node:%.lx\n",
            p_dest,i_q, dest_node);

    // validate destination address
    if ( (p_dest == nullptr ) ||
         ((reinterpret_cast<uint64_t>(p_dest) &
                 IPC_INVALID_REMOTE_ADDR_MASK) ==
           IPC_INVALID_REMOTE_ADDR))
    {
        return( EINVAL);
    }

    // get lock on IPC data area in other node
    if(false == __sync_bool_compare_and_swap(&(p_dest->msg_queue_id),
                                                IPC_DATA_AREA_CLEAR,
                                                IPC_DATA_AREA_LOCKED))
    {
        return -EAGAIN;
    }

    p_dest->msg_payload = *i_msg;  // copy in message
    lwsync();

    p_dest->msg_queue_id = i_q;    // set destination queue id
    lwsync();

    printk("IPC to PIR %x\n",p_dest->pir);

    // send doorbell to interrupt the other drawer
    send_doorbell_ipc(p_dest->pir);

    // The message allocation is freed here to make msg_send for IPC
    // messages behave the same as non-IPC msg_send; that is, the message
    // is freed by the consumer; however, i_msg was allocated in user space
    // code and freed here in kernel space. The assumption is that this is OK.
    msg_free(i_msg);

    return 0;
}

// update the address this IPC instance will use to send messages
//  to a remote node
int KernelIpc::updateRemoteIpcAddr(uint64_t i_Node, uint64_t i_RemoteAddr)
{
    int rc;
    if // input node is valid
      (i_Node < internode_info_vals_t::MAX_NODES_PER_SYS)
    {
        // update local array entry
        rc = 0;
        printk("IPC ADDR %d = 0x%lx\n", (int)i_Node, i_RemoteAddr);
        ipc_data_area.remote_ipc_data_addr[i_Node] =
                reinterpret_cast<ipc_data_area_t*>(i_RemoteAddr);
    }
    else
    {
        rc = EINVAL;
        printk("updateRemoteAddr() Invalid input node: %lx\n",i_Node);
    }

    return(rc);
}

// query the node and remote address other nodes will use to send
//  messages to this IPC instance
int KernelIpc::qryLocalIpcInfo(uint64_t * i_pONode, uint64_t * i_pOAddr)
{
    // determine node and remote address
    uint64_t l_localNode = 0;

    if (g_topology_mode == PROC_FABRIC_TOPOLOGY_MODE_MODE0)
    {
        l_localNode = getPIR()/TOPOLOGY_MODE_0_NODE_DIVISOR;
    }
    else if (g_topology_mode == PROC_FABRIC_TOPOLOGY_MODE_MODE1)
    {
        l_localNode = getPIR()/TOPOLOGY_MODE_1_NODE_DIVISOR;
    }
    else
    {
        // Topology Mode was not setup yet.
        crit_assert(false);
    }

    uint64_t l_localAddr = reinterpret_cast<uint64_t>(&ipc_data_area);
    uint64_t l_hrmor = getHRMOR();

    uint64_t l_oAddr = (( l_localAddr +
                          l_hrmor ) |
                          0x8000000000000000ul);

    *i_pONode = l_localNode;
    *i_pOAddr = l_oAddr;

    return(0);
}

void KernelIpc::setTopologyMode(TARGETING::topoMode_t const i_topologyMode)
{
    g_topology_mode = i_topologyMode;
    printk("Topology Mode = %d\n",g_topology_mode);
}

<|endoftext|>


<commit_before>#include "SpikeSlab.h"
#include "Utils.h"

using namespace std;
using namespace DNest4;

SpikeSlab::SpikeSlab()
:params(20)
{

}

void SpikeSlab::from_prior(RNG& rng)
{
	for(size_t i=0; i<params.size(); i++)
		params[i] = -0.5 + rng.rand();
}

double SpikeSlab::perturb(RNG& rng)
{
	int which = rng.rand_int(params.size());
	params[which] += rng.randh();
	wrap(params[which], -0.5, 0.5);
	return 0.;
}

double SpikeSlab::log_likelihood() const
{
	double u = 0.01;
	double v = 0.1;
	double C = log(1.0/sqrt(2*M_PI));

	double logl1 = params.size()*(C - log(u));
	double logl2 = params.size()*(C - log(v));

	for(const double& x: params)
	{
		logl1 += -0.5*pow((x - 0.031)/u, 2);
		logl2 += -0.5*pow(x/v, 2);
	}
	logl1 += log(100.);

	return logsumexp(logl1, logl2);
}

void SpikeSlab::print(std::ostream& out) const
{
	for(const double& x: params)
		out<<x<<' ';
}

string SpikeSlab::description() const
{
	return string("Each column is one of the 20 parameters.");
}

<commit_msg>constexpr<commit_after>#include "SpikeSlab.h"
#include "Utils.h"

using namespace std;
using namespace DNest4;

SpikeSlab::SpikeSlab()
:params(20)
{

}

void SpikeSlab::from_prior(RNG& rng)
{
	for(size_t i=0; i<params.size(); i++)
		params[i] = -0.5 + rng.rand();
}

double SpikeSlab::perturb(RNG& rng)
{
	int which = rng.rand_int(params.size());
	params[which] += rng.randh();
	wrap(params[which], -0.5, 0.5);
	return 0.;
}

double SpikeSlab::log_likelihood() const
{
	constexpr double u = 0.01;
	constexpr double v = 0.1;
	constexpr double C = log(1.0/sqrt(2*M_PI));

	double logl1 = params.size()*(C - log(u));
	double logl2 = params.size()*(C - log(v));

	for(const double& x: params)
	{
		logl1 += -0.5*pow((x - 0.031)/u, 2);
		logl2 += -0.5*pow(x/v, 2);
	}
	logl1 += log(100.);

	return logsumexp(logl1, logl2);
}

void SpikeSlab::print(std::ostream& out) const
{
	for(const double& x: params)
		out<<x<<' ';
}

string SpikeSlab::description() const
{
	return string("Each column is one of the 20 parameters.");
}

<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <cstdlib>
#include    <cstring>
#include    <ctime>

#if     qPlatform_POSIX
#include    <time.h>
#endif

#include    "../Configuration/Common.h"
#include    "../Characters/String.h"
#include    "../Characters/String_Constant.h"
#include    "../Containers/Mapping.h"
#include    "../Debug/Assertions.h"
#include    "../Debug/Trace.h"
#include    "DateTime.h"
#include    "../Execution/ProcessRunner.h"
#include    "../IO/FileSystem/BinaryFileInputStream.h"
#include    "../Streams/TextInputStreamBinaryAdapter.h"

#include    "Timezone.h"

using   namespace   Stroika;
using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Characters;
using   namespace   Stroika::Foundation::Time;

/*
 ********************************************************************************
 ***************************** Time::GetTimezoneInfo ****************************
 ********************************************************************************
 */
TimeZoneInformationType    Time::GetTimezoneInfo ()
{
    TimeZoneInformationType result;
#if     qPlatform_POSIX
    try {
        result.fID = Streams::TextInputStreamBinaryAdapter (IO::FileSystem::BinaryFileInputStream::mk (String_Constant (L"/etc/timezone"))).ReadAll ().Trim ();
    }
    catch (...) {
        DbgTrace ("Ignoring missing ID from /etc/timezone");
    }
    if (result.fID.empty ()) {
        try {
            result.fID = Execution::ProcessRunner (L"date +%Z").Run (String ()).Trim ();
        }
        catch (...) {
            DbgTrace ("Ignoring missing ID from date +%Z");
        }
    }
    if (result.fID.empty ()) {
        // We could look to see if /etc/localtime is a symlink or a copy of any named file from /usr/share/zoneinfo, but
        // hope thats not needed!
    }
    // @see http://pubs.opengroup.org/onlinepubs/7908799/xsh/tzset.html
    result.fStandardTime.fName = String::FromSDKString (tzname[0]);
    result.fDaylightSavingsTime.fName = String::FromSDKString (tzname[1]);
#elif   qPlatform_Windows
    using   Containers::Mapping;
    using   Common::KeyValuePair;
    static const    Mapping<String, String> kWinDoze2OlsonName_ =  {
        KeyValuePair<String, String> { L"Afghanistan Standard Time", L"Asia/Kabul" },
        KeyValuePair<String, String> { L"Alaskan Standard Time", L"America/Juneau" },
        KeyValuePair<String, String> { L"Arab Standard Time", L"Asia/Riyadh" },
        KeyValuePair<String, String> { L"Arabian Standard Time", L"Asia/Muscat" },
        KeyValuePair<String, String> { L"Arabic Standard Time", L"Asia/Baghdad" },
        KeyValuePair<String, String> { L"Argentina Standard Time", L"America/Rosario" },
        KeyValuePair<String, String> { L"Atlantic Standard Time", L"America/Halifax" },
        KeyValuePair<String, String> { L"AUS Central Standard Time", L"Australia/Darwin" },
        KeyValuePair<String, String> { L"AUS Eastern Standard Time", L"Australia/Sydney" },
        KeyValuePair<String, String> { L"Azerbaijan Standard Time", L"Asia/Baku" },
        KeyValuePair<String, String> { L"Azores Standard Time", L"Atlantic/Azores" },
        KeyValuePair<String, String> { L"Bahia Standard Time", L"America/Maceio" },
        KeyValuePair<String, String> { L"Bangladesh Standard Time", L"Asia/Dhaka" },
        KeyValuePair<String, String> { L"Canada Central Standard Time", L"America/Swift_Current" },
        KeyValuePair<String, String> { L"Cape Verde Standard Time", L"Atlantic/Cape_Verde" },
        KeyValuePair<String, String> { L"Caucasus Standard Time", L"Asia/Yerevan" },
        KeyValuePair<String, String> { L"Cen. Australia Standard Time", L"Australia/Adelaide" },
        KeyValuePair<String, String> { L"Central America Standard Time", L"America/Tegucigalpa" },
        KeyValuePair<String, String> { L"Central Asia Standard Time", L"Asia/Almaty" },
        KeyValuePair<String, String> { L"Central Brazilian Standard Time", L"America/Cuiaba" },
        KeyValuePair<String, String> { L"Central Europe Standard Time", L"Europe/Prague" },
        KeyValuePair<String, String> { L"Central European Standard Time", L"Europe/Skopje" },
        KeyValuePair<String, String> { L"Central Pacific Standard Time", L"Pacific/Guadalcanal" },
        KeyValuePair<String, String> { L"Central Standard Time", L"America/Chicago" },
        KeyValuePair<String, String> { L"Central Standard Time (Mexico)", L"America/Monterrey" },
        KeyValuePair<String, String> { L"China Standard Time", L"Asia/Urumqi" },
        KeyValuePair<String, String> { L"E. Africa Standard Time", L"Africa/Nairobi" },
        KeyValuePair<String, String> { L"E. Australia Standard Time", L"Australia/Brisbane" },
        KeyValuePair<String, String> { L"E. Europe Standard Time", L"Europe/Bucharest" },
        KeyValuePair<String, String> { L"E. South America Standard Time", L"America/Sao_Paulo" },
        KeyValuePair<String, String> { L"Eastern Standard Time", L"America/New_York" },
        KeyValuePair<String, String> { L"Egypt Standard Time", L"Africa/Cairo" },
        KeyValuePair<String, String> { L"Ekaterinburg Standard Time", L"Asia/Yekaterinburg" },
        KeyValuePair<String, String> { L"Fiji Standard Time", L"Pacific/Fiji" },
        KeyValuePair<String, String> { L"FLE Standard Time", L"Europe/Helsinki" },
        KeyValuePair<String, String> { L"Georgian Standard Time", L"Asia/Tbilisi" },
        KeyValuePair<String, String> { L"GMT Standard Time", L"Europe/London" },
        KeyValuePair<String, String> { L"Greenland Standard Time", L"America/Godthab" },
        KeyValuePair<String, String> { L"Greenwich Standard Time", L"Atlantic/Reykjavik" },
        KeyValuePair<String, String> { L"GTB Standard Time", L"Europe/Bucharest" },
        KeyValuePair<String, String> { L"Hawaiian Standard Time", L"Pacific/Honolulu" },
        KeyValuePair<String, String> { L"India Standard Time", L"Asia/Calcutta" },
        KeyValuePair<String, String> { L"Iran Standard Time", L"Asia/Tehran" },
        KeyValuePair<String, String> { L"Jerusalem Standard Time", L"Asia/Jerusalem" },
        KeyValuePair<String, String> { L"Jordan Standard Time", L"Asia/Amman" },
        KeyValuePair<String, String> { L"Kaliningrad Standard Time", L"Europe/Kaliningrad" },
        KeyValuePair<String, String> { L"Korea Standard Time", L"Asia/Seoul" },
        KeyValuePair<String, String> { L"Libya Standard Time", L"Africa/Tripoli" },
        KeyValuePair<String, String> { L"Magadan Standard Time", L"Asia/Magadan" },
        KeyValuePair<String, String> { L"Mauritius Standard Time", L"Indian/Mauritius" },
        KeyValuePair<String, String> { L"Middle East Standard Time", L"Asia/Beirut" },
        KeyValuePair<String, String> { L"Montevideo Standard Time", L"America/Montevideo" },
        KeyValuePair<String, String> { L"Morocco Standard Time", L"Africa/Casablanca" },
        KeyValuePair<String, String> { L"Mountain Standard Time", L"America/Denver" },
        KeyValuePair<String, String> { L"Mountain Standard Time (Mexico)", L"America/Mazatlan" },
        KeyValuePair<String, String> { L"Myanmar Standard Time", L"Asia/Rangoon" },
        KeyValuePair<String, String> { L"N. Central Asia Standard Time", L"Asia/Novosibirsk" },
        KeyValuePair<String, String> { L"Namibia Standard Time", L"Africa/Windhoek" },
        KeyValuePair<String, String> { L"Nepal Standard Time", L"Asia/Katmandu" },
        KeyValuePair<String, String> { L"New Zealand Standard Time", L"Pacific/Auckland" },
        KeyValuePair<String, String> { L"Newfoundland Standard Time", L"America/St_Johns" },
        KeyValuePair<String, String> { L"North Asia East Standard Time", L"Asia/Irkutsk" },
        KeyValuePair<String, String> { L"North Asia Standard Time", L"Asia/Krasnoyarsk" },
        KeyValuePair<String, String> { L"Pacific SA Standard Time", L"America/Santiago" },
        KeyValuePair<String, String> { L"Pacific Standard Time", L"America/Los_Angeles" },
        KeyValuePair<String, String> { L"Pacific Standard Time (Mexico)", L"America/Tijuana" },
        KeyValuePair<String, String> { L"Pakistan Standard Time", L"Asia/Karachi" },
        KeyValuePair<String, String> { L"Paraguay Standard Time", L"America/Asuncion" },
        KeyValuePair<String, String> { L"Romance Standard Time", L"Europe/Paris" },
        KeyValuePair<String, String> { L"Russian Standard Time", L"Europe/Moscow" },
        KeyValuePair<String, String> { L"SA Eastern Standard Time", L"America/Cayenne" },
        KeyValuePair<String, String> { L"SA Pacific Standard Time", L"America/Lima" },
        KeyValuePair<String, String> { L"SA Western Standard Time", L"America/La_Paz" },
        KeyValuePair<String, String> { L"SE Asia Standard Time", L"Asia/Jakarta" },
        KeyValuePair<String, String> { L"Malay Peninsula Standard Time", L"Asia/Singapore" },
        KeyValuePair<String, String> { L"South Africa Standard Time", L"Africa/Harare" },
        KeyValuePair<String, String> { L"Syria Standard Time", L"Asia/Damascus" },
        KeyValuePair<String, String> { L"Taipei Standard Time", L"Asia/Taipei" },
        KeyValuePair<String, String> { L"Tasmania Standard Time", L"Australia/Hobart" },
        KeyValuePair<String, String> { L"Tokyo Standard Time", L"Asia/Tokyo" },
        KeyValuePair<String, String> { L"Tonga Standard Time", L"Pacific/Tongatapu" },
        KeyValuePair<String, String> { L"Turkey Standard Time", L"Asia/Istanbul" },
        KeyValuePair<String, String> { L"Ulaanbaatar Standard Time", L"Asia/Ulaanbaatar" },
        KeyValuePair<String, String> { L"US Eastern Standard Time", L"America/Indianapolis" },
        KeyValuePair<String, String> { L"US Mountain Standard Time", L"America/Denver" },
        KeyValuePair<String, String> { L"Venezuela Standard Time", L"America/Caracas" },
        KeyValuePair<String, String> { L"Vladivostok Standard Time", L"Asia/Vladivostok" },
        KeyValuePair<String, String> { L"W. Australia Standard Time", L"Australia/Perth" },
        KeyValuePair<String, String> { L"W. Central Africa Standard Time", L"Africa/Brazzaville" },
        KeyValuePair<String, String> { L"W. Europe Standard Time", L"Europe/Vienna" },
        KeyValuePair<String, String> { L"West Asia Standard Time", L"Asia/Tashkent" },
        KeyValuePair<String, String> { L"West Pacific Standard Time", L"Pacific/Port_Moresby" },
        KeyValuePair<String, String> { L"Yakutsk Standard Time", L"Asia/Yakutsk" }
    };
    TIME_ZONE_INFORMATION   tzInfo;
    memset (&tzInfo, 0, sizeof (tzInfo));
    (void)::GetTimeZoneInformation (&tzInfo);
    result.fStandardTime.fName = tzInfo.StandardName;
    result.fDaylightSavingsTime.fName = tzInfo.DaylightName;
    result.fID = kWinDoze2OlsonName_.LookupValue (tzInfo.StandardName, tzInfo.StandardName);
#else
    AssertNotImplemented ();
    return String ();
#endif
    return result;
}

/*
 ********************************************************************************
 ********************************* Time::GetTimezone ****************************
 ********************************************************************************
 */
String    Time::GetTimezone ()
{
    return GetTimezone (DateTime::Now ());
}

String    Time::GetTimezone (bool applyDST)
{
#if     qPlatform_Windows
    TIME_ZONE_INFORMATION   tzInfo;
    memset (&tzInfo, 0, sizeof (tzInfo));
    (void)::GetTimeZoneInformation (&tzInfo);
    return tzInfo.StandardName;
#elif   qPlatform_POSIX
    // @see http://pubs.opengroup.org/onlinepubs/7908799/xsh/tzset.html
    return String::FromSDKString (IsDaylightSavingsTime (DateTime::Now ()) ? tzname[1] : tzname[0]);
#else
    AssertNotImplemented ();
    return String ();
#endif
}

String    Time::GetTimezone (const DateTime& d)
{
    return GetTimezone (IsDaylightSavingsTime (d));
}

/*
 ********************************************************************************
 *********************** Time::IsDaylightSavingsTime ****************************
 ********************************************************************************
 */
bool    Time::IsDaylightSavingsTime (const DateTime& d)
{
    struct  tm  asTM    =   d.As<struct tm> ();
    asTM.tm_isdst = -1; // force calc of correct daylight savings time flag
    // THINK this is true - not totally clear - docs on mktime () don't specify unambiguously that this should work...
    // So far it seems too however, --LGP 2011-10-15
    time_t  result  =   mktime (&asTM);
    return asTM.tm_isdst >= 1;
}

/*
 ********************************************************************************
 ********************* Time::GetLocaltimeToGMTOffset ****************************
 ********************************************************************************
 */
time_t  Time::GetLocaltimeToGMTOffset (bool applyDST)
{
#if     0
    // WRONG - but COULD use this API - but not sure needed
#if     qPlatform_Windows
    TIME_ZONE_INFORMATION   tzInfo;
    memset (&tzInfo, 0, sizeof (tzInfo));
    (void)::GetTimeZoneInformation (&tzInfo);
    int unsignedBias    =   abs (tzInfo.Bias);
    int hrs =   unsignedBias / 60;
    int mins = unsignedBias - hrs * 60;
    tzBiasString = ::Format (L"%s%.2d:%.2d", (tzInfo.Bias >= 0 ? L"-" : L"+"), hrs, mins);
#endif
#endif

    /*
     * COULD this be cached? It SHOULD be - but what about when the timezone changes? there maybe a better way to compute this using the
     * timezone global var???
     */
    struct tm tm;
    memset (&tm, 0, sizeof(tm));
    tm.tm_year = 70;
    tm.tm_mon = 0;      // Jan
    tm.tm_mday = 1;
    tm.tm_isdst = applyDST;
    time_t  result  =   mktime (&tm);
    return result;
}

time_t  Time::GetLocaltimeToGMTOffset (const DateTime& forTime)
{
    return GetLocaltimeToGMTOffset (IsDaylightSavingsTime (forTime));
}<commit_msg>fix mistake in last checkin(posix)<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    <cstdlib>
#include    <cstring>
#include    <ctime>

#if     qPlatform_POSIX
#include    <time.h>
#endif

#include    "../Configuration/Common.h"
#include    "../Characters/String.h"
#include    "../Characters/String_Constant.h"
#include    "../Containers/Mapping.h"
#include    "../Debug/Assertions.h"
#include    "../Debug/Trace.h"
#include    "DateTime.h"
#include    "../Execution/ProcessRunner.h"
#include    "../IO/FileSystem/BinaryFileInputStream.h"
#include    "../Streams/TextInputStreamBinaryAdapter.h"

#include    "Timezone.h"

using   namespace   Stroika;
using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Characters;
using   namespace   Stroika::Foundation::Time;

/*
 ********************************************************************************
 ***************************** Time::GetTimezoneInfo ****************************
 ********************************************************************************
 */
TimeZoneInformationType    Time::GetTimezoneInfo ()
{
    TimeZoneInformationType result;
#if     qPlatform_POSIX
    try {
        result.fID = Streams::TextInputStreamBinaryAdapter (IO::FileSystem::BinaryFileInputStream::mk (String_Constant (L"/etc/timezone"))).ReadAll ().Trim ();
    }
    catch (...) {
        DbgTrace ("Ignoring missing ID from /etc/timezone");
    }
    if (result.fID.IsMissing ()) {
        try {
            result.fID = Execution::ProcessRunner (L"date +%Z").Run (String ()).Trim ();
        }
        catch (...) {
            DbgTrace ("Ignoring missing ID from date +%Z");
        }
    }
    if (result.fID.empty ()) {
        // We could look to see if /etc/localtime is a symlink or a copy of any named file from /usr/share/zoneinfo, but
        // hope thats not needed!
    }
    // @see http://pubs.opengroup.org/onlinepubs/7908799/xsh/tzset.html
    result.fStandardTime.fName = String::FromSDKString (tzname[0]);
    result.fDaylightSavingsTime.fName = String::FromSDKString (tzname[1]);
#elif   qPlatform_Windows
    using   Containers::Mapping;
    using   Common::KeyValuePair;
    static const    Mapping<String, String> kWinDoze2OlsonName_ =  {
        KeyValuePair<String, String> { L"Afghanistan Standard Time", L"Asia/Kabul" },
        KeyValuePair<String, String> { L"Alaskan Standard Time", L"America/Juneau" },
        KeyValuePair<String, String> { L"Arab Standard Time", L"Asia/Riyadh" },
        KeyValuePair<String, String> { L"Arabian Standard Time", L"Asia/Muscat" },
        KeyValuePair<String, String> { L"Arabic Standard Time", L"Asia/Baghdad" },
        KeyValuePair<String, String> { L"Argentina Standard Time", L"America/Rosario" },
        KeyValuePair<String, String> { L"Atlantic Standard Time", L"America/Halifax" },
        KeyValuePair<String, String> { L"AUS Central Standard Time", L"Australia/Darwin" },
        KeyValuePair<String, String> { L"AUS Eastern Standard Time", L"Australia/Sydney" },
        KeyValuePair<String, String> { L"Azerbaijan Standard Time", L"Asia/Baku" },
        KeyValuePair<String, String> { L"Azores Standard Time", L"Atlantic/Azores" },
        KeyValuePair<String, String> { L"Bahia Standard Time", L"America/Maceio" },
        KeyValuePair<String, String> { L"Bangladesh Standard Time", L"Asia/Dhaka" },
        KeyValuePair<String, String> { L"Canada Central Standard Time", L"America/Swift_Current" },
        KeyValuePair<String, String> { L"Cape Verde Standard Time", L"Atlantic/Cape_Verde" },
        KeyValuePair<String, String> { L"Caucasus Standard Time", L"Asia/Yerevan" },
        KeyValuePair<String, String> { L"Cen. Australia Standard Time", L"Australia/Adelaide" },
        KeyValuePair<String, String> { L"Central America Standard Time", L"America/Tegucigalpa" },
        KeyValuePair<String, String> { L"Central Asia Standard Time", L"Asia/Almaty" },
        KeyValuePair<String, String> { L"Central Brazilian Standard Time", L"America/Cuiaba" },
        KeyValuePair<String, String> { L"Central Europe Standard Time", L"Europe/Prague" },
        KeyValuePair<String, String> { L"Central European Standard Time", L"Europe/Skopje" },
        KeyValuePair<String, String> { L"Central Pacific Standard Time", L"Pacific/Guadalcanal" },
        KeyValuePair<String, String> { L"Central Standard Time", L"America/Chicago" },
        KeyValuePair<String, String> { L"Central Standard Time (Mexico)", L"America/Monterrey" },
        KeyValuePair<String, String> { L"China Standard Time", L"Asia/Urumqi" },
        KeyValuePair<String, String> { L"E. Africa Standard Time", L"Africa/Nairobi" },
        KeyValuePair<String, String> { L"E. Australia Standard Time", L"Australia/Brisbane" },
        KeyValuePair<String, String> { L"E. Europe Standard Time", L"Europe/Bucharest" },
        KeyValuePair<String, String> { L"E. South America Standard Time", L"America/Sao_Paulo" },
        KeyValuePair<String, String> { L"Eastern Standard Time", L"America/New_York" },
        KeyValuePair<String, String> { L"Egypt Standard Time", L"Africa/Cairo" },
        KeyValuePair<String, String> { L"Ekaterinburg Standard Time", L"Asia/Yekaterinburg" },
        KeyValuePair<String, String> { L"Fiji Standard Time", L"Pacific/Fiji" },
        KeyValuePair<String, String> { L"FLE Standard Time", L"Europe/Helsinki" },
        KeyValuePair<String, String> { L"Georgian Standard Time", L"Asia/Tbilisi" },
        KeyValuePair<String, String> { L"GMT Standard Time", L"Europe/London" },
        KeyValuePair<String, String> { L"Greenland Standard Time", L"America/Godthab" },
        KeyValuePair<String, String> { L"Greenwich Standard Time", L"Atlantic/Reykjavik" },
        KeyValuePair<String, String> { L"GTB Standard Time", L"Europe/Bucharest" },
        KeyValuePair<String, String> { L"Hawaiian Standard Time", L"Pacific/Honolulu" },
        KeyValuePair<String, String> { L"India Standard Time", L"Asia/Calcutta" },
        KeyValuePair<String, String> { L"Iran Standard Time", L"Asia/Tehran" },
        KeyValuePair<String, String> { L"Jerusalem Standard Time", L"Asia/Jerusalem" },
        KeyValuePair<String, String> { L"Jordan Standard Time", L"Asia/Amman" },
        KeyValuePair<String, String> { L"Kaliningrad Standard Time", L"Europe/Kaliningrad" },
        KeyValuePair<String, String> { L"Korea Standard Time", L"Asia/Seoul" },
        KeyValuePair<String, String> { L"Libya Standard Time", L"Africa/Tripoli" },
        KeyValuePair<String, String> { L"Magadan Standard Time", L"Asia/Magadan" },
        KeyValuePair<String, String> { L"Mauritius Standard Time", L"Indian/Mauritius" },
        KeyValuePair<String, String> { L"Middle East Standard Time", L"Asia/Beirut" },
        KeyValuePair<String, String> { L"Montevideo Standard Time", L"America/Montevideo" },
        KeyValuePair<String, String> { L"Morocco Standard Time", L"Africa/Casablanca" },
        KeyValuePair<String, String> { L"Mountain Standard Time", L"America/Denver" },
        KeyValuePair<String, String> { L"Mountain Standard Time (Mexico)", L"America/Mazatlan" },
        KeyValuePair<String, String> { L"Myanmar Standard Time", L"Asia/Rangoon" },
        KeyValuePair<String, String> { L"N. Central Asia Standard Time", L"Asia/Novosibirsk" },
        KeyValuePair<String, String> { L"Namibia Standard Time", L"Africa/Windhoek" },
        KeyValuePair<String, String> { L"Nepal Standard Time", L"Asia/Katmandu" },
        KeyValuePair<String, String> { L"New Zealand Standard Time", L"Pacific/Auckland" },
        KeyValuePair<String, String> { L"Newfoundland Standard Time", L"America/St_Johns" },
        KeyValuePair<String, String> { L"North Asia East Standard Time", L"Asia/Irkutsk" },
        KeyValuePair<String, String> { L"North Asia Standard Time", L"Asia/Krasnoyarsk" },
        KeyValuePair<String, String> { L"Pacific SA Standard Time", L"America/Santiago" },
        KeyValuePair<String, String> { L"Pacific Standard Time", L"America/Los_Angeles" },
        KeyValuePair<String, String> { L"Pacific Standard Time (Mexico)", L"America/Tijuana" },
        KeyValuePair<String, String> { L"Pakistan Standard Time", L"Asia/Karachi" },
        KeyValuePair<String, String> { L"Paraguay Standard Time", L"America/Asuncion" },
        KeyValuePair<String, String> { L"Romance Standard Time", L"Europe/Paris" },
        KeyValuePair<String, String> { L"Russian Standard Time", L"Europe/Moscow" },
        KeyValuePair<String, String> { L"SA Eastern Standard Time", L"America/Cayenne" },
        KeyValuePair<String, String> { L"SA Pacific Standard Time", L"America/Lima" },
        KeyValuePair<String, String> { L"SA Western Standard Time", L"America/La_Paz" },
        KeyValuePair<String, String> { L"SE Asia Standard Time", L"Asia/Jakarta" },
        KeyValuePair<String, String> { L"Malay Peninsula Standard Time", L"Asia/Singapore" },
        KeyValuePair<String, String> { L"South Africa Standard Time", L"Africa/Harare" },
        KeyValuePair<String, String> { L"Syria Standard Time", L"Asia/Damascus" },
        KeyValuePair<String, String> { L"Taipei Standard Time", L"Asia/Taipei" },
        KeyValuePair<String, String> { L"Tasmania Standard Time", L"Australia/Hobart" },
        KeyValuePair<String, String> { L"Tokyo Standard Time", L"Asia/Tokyo" },
        KeyValuePair<String, String> { L"Tonga Standard Time", L"Pacific/Tongatapu" },
        KeyValuePair<String, String> { L"Turkey Standard Time", L"Asia/Istanbul" },
        KeyValuePair<String, String> { L"Ulaanbaatar Standard Time", L"Asia/Ulaanbaatar" },
        KeyValuePair<String, String> { L"US Eastern Standard Time", L"America/Indianapolis" },
        KeyValuePair<String, String> { L"US Mountain Standard Time", L"America/Denver" },
        KeyValuePair<String, String> { L"Venezuela Standard Time", L"America/Caracas" },
        KeyValuePair<String, String> { L"Vladivostok Standard Time", L"Asia/Vladivostok" },
        KeyValuePair<String, String> { L"W. Australia Standard Time", L"Australia/Perth" },
        KeyValuePair<String, String> { L"W. Central Africa Standard Time", L"Africa/Brazzaville" },
        KeyValuePair<String, String> { L"W. Europe Standard Time", L"Europe/Vienna" },
        KeyValuePair<String, String> { L"West Asia Standard Time", L"Asia/Tashkent" },
        KeyValuePair<String, String> { L"West Pacific Standard Time", L"Pacific/Port_Moresby" },
        KeyValuePair<String, String> { L"Yakutsk Standard Time", L"Asia/Yakutsk" }
    };
    TIME_ZONE_INFORMATION   tzInfo;
    memset (&tzInfo, 0, sizeof (tzInfo));
    (void)::GetTimeZoneInformation (&tzInfo);
    result.fStandardTime.fName = tzInfo.StandardName;
    result.fDaylightSavingsTime.fName = tzInfo.DaylightName;
    result.fID = kWinDoze2OlsonName_.LookupValue (tzInfo.StandardName, tzInfo.StandardName);
#else
    AssertNotImplemented ();
    return String ();
#endif
    return result;
}

/*
 ********************************************************************************
 ********************************* Time::GetTimezone ****************************
 ********************************************************************************
 */
String    Time::GetTimezone ()
{
    return GetTimezone (DateTime::Now ());
}

String    Time::GetTimezone (bool applyDST)
{
#if     qPlatform_Windows
    TIME_ZONE_INFORMATION   tzInfo;
    memset (&tzInfo, 0, sizeof (tzInfo));
    (void)::GetTimeZoneInformation (&tzInfo);
    return tzInfo.StandardName;
#elif   qPlatform_POSIX
    // @see http://pubs.opengroup.org/onlinepubs/7908799/xsh/tzset.html
    return String::FromSDKString (IsDaylightSavingsTime (DateTime::Now ()) ? tzname[1] : tzname[0]);
#else
    AssertNotImplemented ();
    return String ();
#endif
}

String    Time::GetTimezone (const DateTime& d)
{
    return GetTimezone (IsDaylightSavingsTime (d));
}

/*
 ********************************************************************************
 *********************** Time::IsDaylightSavingsTime ****************************
 ********************************************************************************
 */
bool    Time::IsDaylightSavingsTime (const DateTime& d)
{
    struct  tm  asTM    =   d.As<struct tm> ();
    asTM.tm_isdst = -1; // force calc of correct daylight savings time flag
    // THINK this is true - not totally clear - docs on mktime () don't specify unambiguously that this should work...
    // So far it seems too however, --LGP 2011-10-15
    time_t  result  =   mktime (&asTM);
    return asTM.tm_isdst >= 1;
}

/*
 ********************************************************************************
 ********************* Time::GetLocaltimeToGMTOffset ****************************
 ********************************************************************************
 */
time_t  Time::GetLocaltimeToGMTOffset (bool applyDST)
{
#if     0
    // WRONG - but COULD use this API - but not sure needed
#if     qPlatform_Windows
    TIME_ZONE_INFORMATION   tzInfo;
    memset (&tzInfo, 0, sizeof (tzInfo));
    (void)::GetTimeZoneInformation (&tzInfo);
    int unsignedBias    =   abs (tzInfo.Bias);
    int hrs =   unsignedBias / 60;
    int mins = unsignedBias - hrs * 60;
    tzBiasString = ::Format (L"%s%.2d:%.2d", (tzInfo.Bias >= 0 ? L"-" : L"+"), hrs, mins);
#endif
#endif

    /*
     * COULD this be cached? It SHOULD be - but what about when the timezone changes? there maybe a better way to compute this using the
     * timezone global var???
     */
    struct tm tm;
    memset (&tm, 0, sizeof(tm));
    tm.tm_year = 70;
    tm.tm_mon = 0;      // Jan
    tm.tm_mday = 1;
    tm.tm_isdst = applyDST;
    time_t  result  =   mktime (&tm);
    return result;
}

time_t  Time::GetLocaltimeToGMTOffset (const DateTime& forTime)
{
    return GetLocaltimeToGMTOffset (IsDaylightSavingsTime (forTime));
}<|endoftext|>


<commit_before>#include "symbiosis.hpp"
#include "shader.hpp"
#include "symbiont_material.hpp"
#include "symbiont_species.hpp"
#include "holobiont.hpp"
#include "material_struct.hpp"
#include "entity_templates.hpp"
#include "render_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
#include <ofbx.h>

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string
#include <vector>   // std::vector

namespace ontology
{
    class Holobiont;

    void Symbiosis::bind_symbiont_material(ontology::SymbiontMaterial* const symbiont_material)
    {
        // get `childID` from `Symbiosis` and set pointer to `symbiont_material`.
        hierarchy::bind_child_to_parent<ontology::SymbiontMaterial*>(
                symbiont_material,
                this->symbiont_material_pointer_vector,
                this->free_symbiont_materialID_queue,
                &this->number_of_symbiont_materials);
    }

    void Symbiosis::bind_holobiont(ontology::Holobiont* const holobiont)
    {
        // get `childID` from `Symbiosis` and set pointer to `object`.
        hierarchy::bind_child_to_parent<ontology::Holobiont*>(
                holobiont,
                this->holobiont_pointer_vector,
                this->free_holobiontID_queue,
                &this->number_of_holobionts);
    }

    void Symbiosis::unbind_holobiont(const int32_t childID)
    {
        ontology::Holobiont* dummy_child_pointer = nullptr;
        hierarchy::set_child_pointer(
                childID,
                dummy_child_pointer,
                this->holobiont_pointer_vector,
                this->free_holobiontID_queue,
                &this->number_of_holobionts);
    }

    void Symbiosis::bind_to_parent()
    {
        // get `childID` from `Shader` and set pointer to this `Symbiosis`.
        this->parent->bind_symbiosis(this);
    }

    void Symbiosis::bind_to_new_parent(ontology::Shader* const new_shader_pointer)
    {
        // unbind from the old parent `Shader`.
        this->parent->unbind_symbiosis(this->childID);

        // get `childID` from `Shader` and set pointer to this `Symbiosis`.
        this->parent = new_shader_pointer;
        this->parent->bind_symbiosis(this);
    }

    Symbiosis::~Symbiosis()
    {
        // destructor.
        std::cout << "Symbiosis with childID " << std::dec << this->childID << " will be destroyed.\n";

        // destroy all holobionts of this symbiosis.
        std::cout << "All holobionts of this symbiosis will be destroyed.\n";
        hierarchy::delete_children<ontology::Holobiont*>(this->holobiont_pointer_vector, &this->number_of_holobionts);

        // destroy all symbiont materials of this symbiosis.
        std::cout << "All symbiont materials of this symbiosis will be destroyed.\n";
        hierarchy::delete_children<ontology::SymbiontMaterial*>(this->symbiont_material_pointer_vector, &this->number_of_symbiont_materials);

        // set pointer to this symbiosis to nullptr.
        this->parent->set_symbiosis_pointer(this->childID, nullptr);
    }

    void Symbiosis::render()
    {
        this->prerender();

        // render this `Symbiosis` by calling `render()` function of each `Holobiont`.
        ontology::render_children<ontology::Holobiont*>(this->holobiont_pointer_vector);

        this->postrender();
    }

    void Symbiosis::set_name(const std::string& name)
    {
        ontology::set_name(name, this);
    }

    ontology::Entity* Symbiosis::get_parent() const
    {
        return this->parent;
    }

    int32_t Symbiosis::get_number_of_children() const
    {
        return this->number_of_symbiont_materials + this->number_of_holobionts;
    }

    int32_t Symbiosis::get_number_of_descendants() const
    {
        return -1;
    }

    const std::string& Symbiosis::get_model_file_format()
    {
        return this->model_file_format;
    }

    void Symbiosis::set_symbiont_material_pointer(const int32_t childID, ontology::SymbiontMaterial* const child_pointer)
    {
        hierarchy::set_child_pointer(
                childID,
                child_pointer,
                this->symbiont_material_pointer_vector,
                this->free_symbiont_materialID_queue,
                &this->number_of_symbiont_materials);
    }

    void Symbiosis::set_holobiont_pointer(const int32_t childID, ontology::Holobiont* const child_pointer)
    {
        hierarchy::set_child_pointer(
                childID,
                child_pointer,
                this->holobiont_pointer_vector,
                this->free_holobiontID_queue,
                &this->number_of_holobionts);
    }

    void Symbiosis::create_symbionts()
    {
        SymbiosisLoaderStruct symbiosis_loader_struct;
        symbiosis_loader_struct.model_filename = this->model_filename;
        symbiosis_loader_struct.model_file_format = this->model_file_format;
        symbiosis_loader_struct.triangulation_type = this->triangulation_type;

        if (loaders::load_symbiosis(
                    symbiosis_loader_struct,
                    this->vertices,
                    this->uvs,
                    this->normals,
                    this->indices,
                    this->indexed_vertices,
                    this->indexed_uvs,
                    this->indexed_normals,
                    this->ofbx_diffuse_texture_mesh_map,
                    this->ofbx_meshes,
                    this->ofbx_diffuse_texture_vector,
                    this->ofbx_normal_texture_vector,
                    this->ofbx_count_texture_vector,
                    this->ofbx_mesh_count))
        {
            std::cout << "number of meshes: " << this->ofbx_mesh_count << "\n";

            std::vector<const ofbx::Texture*> ofbx_diffuse_texture_pointer_vector;
            ofbx_diffuse_texture_pointer_vector.reserve(this->ofbx_diffuse_texture_mesh_map.size());
            this->biontID_symbiont_material_vector.resize(this->ofbx_mesh_count);

            this->biontID_symbiont_species_vector.resize(this->ofbx_mesh_count);

            for (auto key_and_value : ofbx_diffuse_texture_mesh_map)
            {
                ofbx_diffuse_texture_pointer_vector.push_back(key_and_value.first); // key.
            }

            // Create `SymbiontMaterial`s.
            for (const ofbx::Texture* ofbx_texture : ofbx_diffuse_texture_pointer_vector)
            {
                std::cout << "Creating ontology::SymbiontMaterial* based on ofbx::Texture* at 0x" << std::hex << (uint64_t) ofbx_texture << std::dec << " ...\n";
                MaterialStruct material_struct;
                material_struct.shader = this->parent;
                material_struct.symbiosis = this;
                material_struct.is_symbiont_material = true;
                material_struct.ofbx_texture = ofbx_texture;
                ontology::SymbiontMaterial* symbiont_material = new ontology::SymbiontMaterial(this->universe, material_struct);
                symbiont_material->load_texture();

                std::cout << "ontology::SymbiontMaterial* successfully created.\n";

                // Create `SymbiontSpecies`s.
                // Care only about `ofbx::Texture*`s with are DIFFUSE textures.
                for (int32_t mesh_i : this->ofbx_diffuse_texture_mesh_map.at(ofbx_texture))
                {
                    int32_t vertex_count = this->vertices.at(mesh_i).size();
                    std::vector<glm::vec3> vertices = this->vertices.at(mesh_i);

                    SpeciesStruct species_struct;
                    species_struct.is_symbiont_species = true;
                    species_struct.scene = static_cast<ontology::Scene*>(this->parent->get_parent());
                    species_struct.shader = this->parent;
                    species_struct.symbiont_material = symbiont_material;
                    species_struct.vertex_count = vertex_count;
                    species_struct.vertices = this->vertices.at(mesh_i);
                    species_struct.uvs = this->uvs.at(mesh_i);
                    species_struct.normals = this->normals.at(mesh_i);
                    species_struct.light_position = this->light_position;

                    std::cout << "Creating ontology::SymbiontSpecies*, mesh index " << mesh_i << "...\n";

                    ontology::SymbiontSpecies* symbiont_species = new ontology::SymbiontSpecies(this->universe, species_struct);

                    std::cout << "ontology::SymbiontSpecies*, mesh index " << mesh_i << " successfully created.\n";

                    std::cout << "storing ontology::SymbiontMaterial* symbiont_material into vector with mesh_i " << mesh_i << " ...\n";
                    this->biontID_symbiont_material_vector.at(mesh_i) = symbiont_material;
                    std::cout << "storing ontology::SymbiontSpecies* symbiont_species into vector with mesh_i " << mesh_i << " ...\n";
                    this->biontID_symbiont_species_vector.at(mesh_i) = symbiont_species;

                    std::cout << "Success.\n";
                    // TODO: Compute the graph of each type to enable object vertex modification!
                }
            }

            std::cout << "All symbionts successfully created.\n";
        }
    }

    ontology::SymbiontSpecies* Symbiosis::get_symbiont_species(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID);
    }

    GLuint Symbiosis::get_vertex_position_modelspaceID(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_position_modelspaceID();
    }

    GLuint Symbiosis::get_vertexUVID(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_vertexUVID();
    }

    GLuint Symbiosis::get_vertex_normal_modelspaceID(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_normal_modelspaceID();
    }

    GLuint Symbiosis::get_vertexbuffer(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_vertexbuffer();
    }

    GLuint Symbiosis::get_uvbuffer(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_uvbuffer();
    }

    GLuint Symbiosis::get_normalbuffer(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_normalbuffer();
    }

    GLuint Symbiosis::get_elementbuffer(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_elementbuffer();
    }

    std::vector<uint32_t> Symbiosis::get_indices(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_indices();
        // return this->indices.at(biontID);
    }

    GLuint Symbiosis::get_indices_size(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_indices_size();
        // return this->indices.at(biontID).size();
    }

    int32_t Symbiosis::get_number_of_symbionts() const
    {
        return this->ofbx_mesh_count;
    }

    bool Symbiosis::has_texture(const int32_t biontID) const
    {
        if (biontID >= this->biontID_symbiont_material_vector.size())
        {
            return false;
        }

        if (this->biontID_symbiont_material_vector.at(biontID) == nullptr)
        {
            return false;
        }

        return true;
    }

    GLuint Symbiosis::get_texture(const int32_t biontID) const
    {
        return this->biontID_symbiont_material_vector.at(biontID)->get_texture();
    }

    GLuint Symbiosis::get_openGL_textureID(const int32_t biontID) const
    {
        return this->biontID_symbiont_material_vector.at(biontID)->get_openGL_textureID();
    }

    GLuint Symbiosis::get_lightID(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_lightID();
    }

    glm::vec3 Symbiosis::get_light_position(const int32_t biontID) const
    {
        return this->light_position;
    }
}
<commit_msg>Fixed a typo in a comment.<commit_after>#include "symbiosis.hpp"
#include "shader.hpp"
#include "symbiont_material.hpp"
#include "symbiont_species.hpp"
#include "holobiont.hpp"
#include "material_struct.hpp"
#include "entity_templates.hpp"
#include "render_templates.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
#include <ofbx.h>

// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string
#include <vector>   // std::vector

namespace ontology
{
    class Holobiont;

    void Symbiosis::bind_symbiont_material(ontology::SymbiontMaterial* const symbiont_material)
    {
        // get `childID` from `Symbiosis` and set pointer to `symbiont_material`.
        hierarchy::bind_child_to_parent<ontology::SymbiontMaterial*>(
                symbiont_material,
                this->symbiont_material_pointer_vector,
                this->free_symbiont_materialID_queue,
                &this->number_of_symbiont_materials);
    }

    void Symbiosis::bind_holobiont(ontology::Holobiont* const holobiont)
    {
        // get `childID` from `Symbiosis` and set pointer to `object`.
        hierarchy::bind_child_to_parent<ontology::Holobiont*>(
                holobiont,
                this->holobiont_pointer_vector,
                this->free_holobiontID_queue,
                &this->number_of_holobionts);
    }

    void Symbiosis::unbind_holobiont(const int32_t childID)
    {
        ontology::Holobiont* dummy_child_pointer = nullptr;
        hierarchy::set_child_pointer(
                childID,
                dummy_child_pointer,
                this->holobiont_pointer_vector,
                this->free_holobiontID_queue,
                &this->number_of_holobionts);
    }

    void Symbiosis::bind_to_parent()
    {
        // get `childID` from `Shader` and set pointer to this `Symbiosis`.
        this->parent->bind_symbiosis(this);
    }

    void Symbiosis::bind_to_new_parent(ontology::Shader* const new_shader_pointer)
    {
        // unbind from the old parent `Shader`.
        this->parent->unbind_symbiosis(this->childID);

        // get `childID` from `Shader` and set pointer to this `Symbiosis`.
        this->parent = new_shader_pointer;
        this->parent->bind_symbiosis(this);
    }

    Symbiosis::~Symbiosis()
    {
        // destructor.
        std::cout << "Symbiosis with childID " << std::dec << this->childID << " will be destroyed.\n";

        // destroy all holobionts of this symbiosis.
        std::cout << "All holobionts of this symbiosis will be destroyed.\n";
        hierarchy::delete_children<ontology::Holobiont*>(this->holobiont_pointer_vector, &this->number_of_holobionts);

        // destroy all symbiont materials of this symbiosis.
        std::cout << "All symbiont materials of this symbiosis will be destroyed.\n";
        hierarchy::delete_children<ontology::SymbiontMaterial*>(this->symbiont_material_pointer_vector, &this->number_of_symbiont_materials);

        // set pointer to this symbiosis to nullptr.
        this->parent->set_symbiosis_pointer(this->childID, nullptr);
    }

    void Symbiosis::render()
    {
        this->prerender();

        // render this `Symbiosis` by calling `render()` function of each `Holobiont`.
        ontology::render_children<ontology::Holobiont*>(this->holobiont_pointer_vector);

        this->postrender();
    }

    void Symbiosis::set_name(const std::string& name)
    {
        ontology::set_name(name, this);
    }

    ontology::Entity* Symbiosis::get_parent() const
    {
        return this->parent;
    }

    int32_t Symbiosis::get_number_of_children() const
    {
        return this->number_of_symbiont_materials + this->number_of_holobionts;
    }

    int32_t Symbiosis::get_number_of_descendants() const
    {
        return -1;
    }

    const std::string& Symbiosis::get_model_file_format()
    {
        return this->model_file_format;
    }

    void Symbiosis::set_symbiont_material_pointer(const int32_t childID, ontology::SymbiontMaterial* const child_pointer)
    {
        hierarchy::set_child_pointer(
                childID,
                child_pointer,
                this->symbiont_material_pointer_vector,
                this->free_symbiont_materialID_queue,
                &this->number_of_symbiont_materials);
    }

    void Symbiosis::set_holobiont_pointer(const int32_t childID, ontology::Holobiont* const child_pointer)
    {
        hierarchy::set_child_pointer(
                childID,
                child_pointer,
                this->holobiont_pointer_vector,
                this->free_holobiontID_queue,
                &this->number_of_holobionts);
    }

    void Symbiosis::create_symbionts()
    {
        SymbiosisLoaderStruct symbiosis_loader_struct;
        symbiosis_loader_struct.model_filename = this->model_filename;
        symbiosis_loader_struct.model_file_format = this->model_file_format;
        symbiosis_loader_struct.triangulation_type = this->triangulation_type;

        if (loaders::load_symbiosis(
                    symbiosis_loader_struct,
                    this->vertices,
                    this->uvs,
                    this->normals,
                    this->indices,
                    this->indexed_vertices,
                    this->indexed_uvs,
                    this->indexed_normals,
                    this->ofbx_diffuse_texture_mesh_map,
                    this->ofbx_meshes,
                    this->ofbx_diffuse_texture_vector,
                    this->ofbx_normal_texture_vector,
                    this->ofbx_count_texture_vector,
                    this->ofbx_mesh_count))
        {
            std::cout << "number of meshes: " << this->ofbx_mesh_count << "\n";

            std::vector<const ofbx::Texture*> ofbx_diffuse_texture_pointer_vector;
            ofbx_diffuse_texture_pointer_vector.reserve(this->ofbx_diffuse_texture_mesh_map.size());
            this->biontID_symbiont_material_vector.resize(this->ofbx_mesh_count);

            this->biontID_symbiont_species_vector.resize(this->ofbx_mesh_count);

            for (auto key_and_value : ofbx_diffuse_texture_mesh_map)
            {
                ofbx_diffuse_texture_pointer_vector.push_back(key_and_value.first); // key.
            }

            // Create `SymbiontMaterial`s.
            for (const ofbx::Texture* ofbx_texture : ofbx_diffuse_texture_pointer_vector)
            {
                std::cout << "Creating ontology::SymbiontMaterial* based on ofbx::Texture* at 0x" << std::hex << (uint64_t) ofbx_texture << std::dec << " ...\n";
                MaterialStruct material_struct;
                material_struct.shader = this->parent;
                material_struct.symbiosis = this;
                material_struct.is_symbiont_material = true;
                material_struct.ofbx_texture = ofbx_texture;
                ontology::SymbiontMaterial* symbiont_material = new ontology::SymbiontMaterial(this->universe, material_struct);
                symbiont_material->load_texture();

                std::cout << "ontology::SymbiontMaterial* successfully created.\n";

                // Create `SymbiontSpecies`s.
                // Care only about `ofbx::Texture*`s which are DIFFUSE textures.
                for (int32_t mesh_i : this->ofbx_diffuse_texture_mesh_map.at(ofbx_texture))
                {
                    int32_t vertex_count = this->vertices.at(mesh_i).size();
                    std::vector<glm::vec3> vertices = this->vertices.at(mesh_i);

                    SpeciesStruct species_struct;
                    species_struct.is_symbiont_species = true;
                    species_struct.scene = static_cast<ontology::Scene*>(this->parent->get_parent());
                    species_struct.shader = this->parent;
                    species_struct.symbiont_material = symbiont_material;
                    species_struct.vertex_count = vertex_count;
                    species_struct.vertices = this->vertices.at(mesh_i);
                    species_struct.uvs = this->uvs.at(mesh_i);
                    species_struct.normals = this->normals.at(mesh_i);
                    species_struct.light_position = this->light_position;

                    std::cout << "Creating ontology::SymbiontSpecies*, mesh index " << mesh_i << "...\n";

                    ontology::SymbiontSpecies* symbiont_species = new ontology::SymbiontSpecies(this->universe, species_struct);

                    std::cout << "ontology::SymbiontSpecies*, mesh index " << mesh_i << " successfully created.\n";

                    std::cout << "storing ontology::SymbiontMaterial* symbiont_material into vector with mesh_i " << mesh_i << " ...\n";
                    this->biontID_symbiont_material_vector.at(mesh_i) = symbiont_material;
                    std::cout << "storing ontology::SymbiontSpecies* symbiont_species into vector with mesh_i " << mesh_i << " ...\n";
                    this->biontID_symbiont_species_vector.at(mesh_i) = symbiont_species;

                    std::cout << "Success.\n";
                    // TODO: Compute the graph of each type to enable object vertex modification!
                }
            }

            std::cout << "All symbionts successfully created.\n";
        }
    }

    ontology::SymbiontSpecies* Symbiosis::get_symbiont_species(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID);
    }

    GLuint Symbiosis::get_vertex_position_modelspaceID(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_position_modelspaceID();
    }

    GLuint Symbiosis::get_vertexUVID(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_vertexUVID();
    }

    GLuint Symbiosis::get_vertex_normal_modelspaceID(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_normal_modelspaceID();
    }

    GLuint Symbiosis::get_vertexbuffer(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_vertexbuffer();
    }

    GLuint Symbiosis::get_uvbuffer(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_uvbuffer();
    }

    GLuint Symbiosis::get_normalbuffer(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_normalbuffer();
    }

    GLuint Symbiosis::get_elementbuffer(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_elementbuffer();
    }

    std::vector<uint32_t> Symbiosis::get_indices(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_indices();
        // return this->indices.at(biontID);
    }

    GLuint Symbiosis::get_indices_size(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_indices_size();
        // return this->indices.at(biontID).size();
    }

    int32_t Symbiosis::get_number_of_symbionts() const
    {
        return this->ofbx_mesh_count;
    }

    bool Symbiosis::has_texture(const int32_t biontID) const
    {
        if (biontID >= this->biontID_symbiont_material_vector.size())
        {
            return false;
        }

        if (this->biontID_symbiont_material_vector.at(biontID) == nullptr)
        {
            return false;
        }

        return true;
    }

    GLuint Symbiosis::get_texture(const int32_t biontID) const
    {
        return this->biontID_symbiont_material_vector.at(biontID)->get_texture();
    }

    GLuint Symbiosis::get_openGL_textureID(const int32_t biontID) const
    {
        return this->biontID_symbiont_material_vector.at(biontID)->get_openGL_textureID();
    }

    GLuint Symbiosis::get_lightID(const int32_t biontID) const
    {
        return this->biontID_symbiont_species_vector.at(biontID)->get_lightID();
    }

    glm::vec3 Symbiosis::get_light_position(const int32_t biontID) const
    {
        return this->light_position;
    }
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-05-13 14:52:01 +0200 (Mi, 13. Mai 2009) $
Version:   $Revision: 17230 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkNavigationDataPlayer.h"
#include "mitkNavigationData.h"

#include "mitkTestingMacros.h"
#include "mitkStandardFileLocations.h"
#include "mitkTimeStamp.h"

#include <iostream>
#include <sstream>

/**Documentation
 *  test for the class "NavigationDataPlayer".
 */
int mitkNavigationDataPlayerTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("NavigationDataPlayer");
  std::string tmp = "";
  std::ostringstream* stream = new std::ostringstream( std::ostringstream::trunc );

  // let's create an object of our class
  mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();

  // first test: did this work?
  // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
  // it makes no sense to continue without an object.
  MITK_TEST_CONDITION_REQUIRED(player.IsNotNull(), "Testing instantiation");

  std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData.xml", "Modules/IGT/Testing/Data");

  player->SetFileName( file );

  MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), file.c_str()) == 0, "Testing SetFileName and GetFileName");

  player->SetStream( mitk::NavigationDataPlayer::NormalFile );
  player->StartPlaying();
  player->Update();
  player->StopPlaying();

  mitk::NavigationData::Pointer nd = player->GetOutput();
  mitk::Point3D pnt;
  pnt[0] = 1;
  pnt[1] = 0;
  pnt[2] = 3;

  MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" );
  //MITK_TEST_CONDITION_REQUIRED( nd->GetTimeStamp() == 3068.94, "Testing for correct TimeStamp" );

  std::vector<double> times, refTimes;
  refTimes.resize(5);
  refTimes[0] = 3.9;
  refTimes[1] = 83.6;
  refTimes[2] = 174.4;
  refTimes[3] = 275.0;
  refTimes[4] = 385.39;

  mitk::TimeStamp::Pointer timer = mitk::TimeStamp::GetInstance();
  timer->Initialize();

  itk::Object::Pointer obj = itk::Object::New();
  timer->Start( obj );

  mitk::Point3D oldPos;
  oldPos[0] = 1;
  oldPos[1] = 0;
  oldPos[2] = 3;
  //pnt = oldPos;
  player->StartPlaying();
  while( times.size()<5 )
  {
    player->Update();
    pnt = nd->GetPosition();
    if ( pnt != oldPos )
    {
      times.push_back( timer->GetElapsed(obj) );
      oldPos = pnt;
    }
  }

  // if this test fails, it may be because the dartclient runs on a virtual machine.
  // Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms
  for ( int i=0;i<5;i++ )
  {
    std::cout << "ref: " << refTimes[i] << "  /  time elapsed: " << times[i] << std::endl;
    MITK_TEST_CONDITION_REQUIRED( (times[i]>refTimes[i]-10 && times[i]<refTimes[i]+10), "checking for more or less correct time-line"  );
  }

  // always end with this!
  MITK_TEST_END();
}
<commit_msg>STYLE: removed unused variable<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2009-05-13 14:52:01 +0200 (Mi, 13. Mai 2009) $
Version:   $Revision: 17230 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkNavigationDataPlayer.h"
#include "mitkNavigationData.h"

#include "mitkTestingMacros.h"
#include "mitkStandardFileLocations.h"
#include "mitkTimeStamp.h"

#include <iostream>
#include <sstream>

/**Documentation
 *  test for the class "NavigationDataPlayer".
 */
int mitkNavigationDataPlayerTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("NavigationDataPlayer");
  std::string tmp = "";

  // let's create an object of our class
  mitk::NavigationDataPlayer::Pointer player = mitk::NavigationDataPlayer::New();

  // first test: did this work?
  // using MITK_TEST_CONDITION_REQUIRED makes the test stop after failure, since
  // it makes no sense to continue without an object.
  MITK_TEST_CONDITION_REQUIRED(player.IsNotNull(), "Testing instantiation");

  std::string file = mitk::StandardFileLocations::GetInstance()->FindFile("NavigationDataTestData.xml", "Modules/IGT/Testing/Data");

  player->SetFileName( file );

  MITK_TEST_CONDITION_REQUIRED( strcmp(player->GetFileName(), file.c_str()) == 0, "Testing SetFileName and GetFileName");

  player->SetStream( mitk::NavigationDataPlayer::NormalFile );
  player->StartPlaying();
  player->Update();
  player->StopPlaying();

  mitk::NavigationData::Pointer nd = player->GetOutput();
  mitk::Point3D pnt;
  pnt[0] = 1;
  pnt[1] = 0;
  pnt[2] = 3;

  MITK_TEST_CONDITION_REQUIRED( nd->GetPosition() == pnt, "Testing position of replayed NavigaionData" );
  //MITK_TEST_CONDITION_REQUIRED( nd->GetTimeStamp() == 3068.94, "Testing for correct TimeStamp" );

  std::vector<double> times, refTimes;
  refTimes.resize(5);
  refTimes[0] = 3.9;
  refTimes[1] = 83.6;
  refTimes[2] = 174.4;
  refTimes[3] = 275.0;
  refTimes[4] = 385.39;

  mitk::TimeStamp::Pointer timer = mitk::TimeStamp::GetInstance();
  timer->Initialize();

  itk::Object::Pointer obj = itk::Object::New();
  timer->Start( obj );

  mitk::Point3D oldPos;
  oldPos[0] = 1;
  oldPos[1] = 0;
  oldPos[2] = 3;
  //pnt = oldPos;
  player->StartPlaying();
  while( times.size()<5 )
  {
    player->Update();
    pnt = nd->GetPosition();
    if ( pnt != oldPos )
    {
      times.push_back( timer->GetElapsed(obj) );
      oldPos = pnt;
    }
  }

  // if this test fails, it may be because the dartclient runs on a virtual machine.
  // Under these circumstances, it may be impossible to achieve a time-accuracy of 10ms
  for ( int i=0;i<5;i++ )
  {
    std::cout << "ref: " << refTimes[i] << "  /  time elapsed: " << times[i] << std::endl;
    MITK_TEST_CONDITION_REQUIRED( (times[i]>refTimes[i]-10 && times[i]<refTimes[i]+10), "checking for more or less correct time-line"  );
  }

  // always end with this!
  MITK_TEST_END();
}
<|endoftext|>


<commit_before>#include <catch.hpp>
#include <ProgramOptions.hxx>
#include "arg_provider.hxx"

TEST_CASE( "callback", "[ProgramOptions]" ) {
	po::parser parser;
	parser.silent();

	po::i32_t a_value{};
	po::string_t a_value_str{};
	std::size_t a_counter_1 = 0;
	std::size_t a_counter_2 = 0;
	auto&& a = parser[ "a" ]
		.type( po::i32 )
		.callback( [ & ]( po::i32_t const& value ){ ++a_counter_1; a_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++a_counter_2; a_value_str = value; } );

	po::i64_t b_value{};
	po::string_t b_value_str{};
	std::size_t b_counter_1 = 0;
	std::size_t b_counter_2 = 0;
	auto&& b = parser[ "b" ]
		.type( po::i64 )
		.callback( [ & ]( po::i64_t const& value ){ ++b_counter_1; b_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++b_counter_2; b_value_str = value; } );

	po::u32_t c_value{};
	po::string_t c_value_str{};
	std::size_t c_counter_1 = 0;
	std::size_t c_counter_2 = 0;
	auto&& c = parser[ "c" ]
		.type( po::u32 )
		.callback( [ & ]( po::u32_t const& value ){ ++c_counter_1; c_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++c_counter_2; c_value_str = value; } );

	po::u64_t d_value{};
	po::string_t d_value_str{};
	std::size_t d_counter_1 = 0;
	std::size_t d_counter_2 = 0;
	auto&& d = parser[ "d" ]
		.type( po::u64 )
		.callback( [ & ]( po::u64_t const& value ){ ++d_counter_1; d_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++d_counter_2; d_value_str = value; } );

	po::f32_t e_value{};
	po::string_t e_value_str{};
	std::size_t e_counter_1 = 0;
	std::size_t e_counter_2 = 0;
	auto&& e = parser[ "e" ]
		.type( po::f32 )
		.callback( [ & ]( po::f32_t const& value ){ ++e_counter_1; e_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++e_counter_2; e_value_str = value; } );

	po::f64_t f_value{};
	po::string_t f_value_str{};
	std::size_t f_counter_1 = 0;
	std::size_t f_counter_2 = 0;
	auto&& f = parser[ "f" ]
		.type( po::f64 )
		.callback( [ & ]( po::f64_t const& value ){ ++f_counter_1; f_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++f_counter_2; f_value_str = value; } );

	po::string_t g_value{};
	std::size_t g_counter_1 = 0;
	auto&& g = parser[ "g" ]
		.type( po::string )
		.callback( [ & ]( po::string_t const& value ){ ++g_counter_1; g_value = value; } );

	std::size_t h_counter_1 = 0;
	auto&& h = parser[ "h" ]
		.type( po::void_ )
		.callback( [ & ](){ ++h_counter_1; } );

	const arg_provider A {
		"/Test",
		"-a",
		"-65",
		"-b+14e12",
		"-c12",
		"-c0000000",
		"-d2",
		"-d4",
		"-d42",
		"-e0",
		"-f7.39",
		"-f",
		"-7.39000",
		"-g",
		"foo",
		"-g",
		"bar",
		"-hhhh"
	};
	CHECK( parser( A.argc, A.argv ) );

	CHECK( a_value == -65 );
	CHECK( a_value_str == "-65" );
	CHECK( a_counter_1 == 1 );
	CHECK( a_counter_2 == 1 );

	CHECK( b_value == 14000000000000 );
	CHECK( b_value_str == "+14e12" );
	CHECK( b_counter_1 == 1 );
	CHECK( b_counter_2 == 1 );

	CHECK( c_value == 0 );
	CHECK( c_value_str == "0000000" );
	CHECK( c_counter_1 == 2 );
	CHECK( c_counter_2 == 2 );

	CHECK( d_value == 42 );
	CHECK( d_value_str == "42" );
	CHECK( d_counter_1 == 3 );
	CHECK( d_counter_2 == 3 );

	CHECK( e_value == 0 );
	CHECK( e_value_str == "0" );
	CHECK( e_counter_1 == 1 );
	CHECK( e_counter_2 == 1 );

	CHECK( f_value == Approx( -7.39 ) );
	CHECK( f_value_str == "-7.39000" );
	CHECK( f_counter_1 == 2 );
	CHECK( f_counter_2 == 2 );

	CHECK( g_value == "bar" );
	CHECK( g_counter_1 == 2 );

	CHECK( h_counter_1 == 4 );
}
<commit_msg>remove unnecessary reference variables in callback.cxx<commit_after>#include <catch.hpp>
#include <ProgramOptions.hxx>
#include "arg_provider.hxx"

TEST_CASE( "callback", "[ProgramOptions]" ) {
	po::parser parser;
	parser.silent();

	po::i32_t a_value{};
	po::string_t a_value_str{};
	std::size_t a_counter_1 = 0;
	std::size_t a_counter_2 = 0;
	parser[ "a" ]
		.type( po::i32 )
		.callback( [ & ]( po::i32_t const& value ){ ++a_counter_1; a_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++a_counter_2; a_value_str = value; } );

	po::i64_t b_value{};
	po::string_t b_value_str{};
	std::size_t b_counter_1 = 0;
	std::size_t b_counter_2 = 0;
	parser[ "b" ]
		.type( po::i64 )
		.callback( [ & ]( po::i64_t const& value ){ ++b_counter_1; b_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++b_counter_2; b_value_str = value; } );

	po::u32_t c_value{};
	po::string_t c_value_str{};
	std::size_t c_counter_1 = 0;
	std::size_t c_counter_2 = 0;
	parser[ "c" ]
		.type( po::u32 )
		.callback( [ & ]( po::u32_t const& value ){ ++c_counter_1; c_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++c_counter_2; c_value_str = value; } );

	po::u64_t d_value{};
	po::string_t d_value_str{};
	std::size_t d_counter_1 = 0;
	std::size_t d_counter_2 = 0;
	parser[ "d" ]
		.type( po::u64 )
		.callback( [ & ]( po::u64_t const& value ){ ++d_counter_1; d_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++d_counter_2; d_value_str = value; } );

	po::f32_t e_value{};
	po::string_t e_value_str{};
	std::size_t e_counter_1 = 0;
	std::size_t e_counter_2 = 0;
	parser[ "e" ]
		.type( po::f32 )
		.callback( [ & ]( po::f32_t const& value ){ ++e_counter_1; e_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++e_counter_2; e_value_str = value; } );

	po::f64_t f_value{};
	po::string_t f_value_str{};
	std::size_t f_counter_1 = 0;
	std::size_t f_counter_2 = 0;
	parser[ "f" ]
		.type( po::f64 )
		.callback( [ & ]( po::f64_t const& value ){ ++f_counter_1; f_value = value; } )
		.callback( [ & ]( po::string_t const& value ){ ++f_counter_2; f_value_str = value; } );

	po::string_t g_value{};
	std::size_t g_counter_1 = 0;
	parser[ "g" ]
		.type( po::string )
		.callback( [ & ]( po::string_t const& value ){ ++g_counter_1; g_value = value; } );

	std::size_t h_counter_1 = 0;
	parser[ "h" ]
		.type( po::void_ )
		.callback( [ & ](){ ++h_counter_1; } );

	const arg_provider A {
		"/Test",
		"-a",
		"-65",
		"-b+14e12",
		"-c12",
		"-c0000000",
		"-d2",
		"-d4",
		"-d42",
		"-e0",
		"-f7.39",
		"-f",
		"-7.39000",
		"-g",
		"foo",
		"-g",
		"bar",
		"-hhhh"
	};
	CHECK( parser( A.argc, A.argv ) );

	CHECK( a_value == -65 );
	CHECK( a_value_str == "-65" );
	CHECK( a_counter_1 == 1 );
	CHECK( a_counter_2 == 1 );

	CHECK( b_value == 14000000000000 );
	CHECK( b_value_str == "+14e12" );
	CHECK( b_counter_1 == 1 );
	CHECK( b_counter_2 == 1 );

	CHECK( c_value == 0 );
	CHECK( c_value_str == "0000000" );
	CHECK( c_counter_1 == 2 );
	CHECK( c_counter_2 == 2 );

	CHECK( d_value == 42 );
	CHECK( d_value_str == "42" );
	CHECK( d_counter_1 == 3 );
	CHECK( d_counter_2 == 3 );

	CHECK( e_value == 0 );
	CHECK( e_value_str == "0" );
	CHECK( e_counter_1 == 1 );
	CHECK( e_counter_2 == 1 );

	CHECK( f_value == Approx( -7.39 ) );
	CHECK( f_value_str == "-7.39000" );
	CHECK( f_counter_1 == 2 );
	CHECK( f_counter_2 == 2 );

	CHECK( g_value == "bar" );
	CHECK( g_counter_1 == 2 );

	CHECK( h_counter_1 == 4 );
}
<|endoftext|>


<commit_before>#include "spec_helper.h"
#include "runtime/alloc.h"
#include "helpers/load_language.h"
#include "helpers/read_test_entries.h"
#include "helpers/spy_input.h"
#include "helpers/stderr_logger.h"
#include "helpers/point_helpers.h"
#include "helpers/encoding_helpers.h"
#include "helpers/record_alloc.h"
#include "helpers/random_helpers.h"
#include "helpers/scope_sequence.h"
#include <set>

static void assert_correct_tree_shape(const TSDocument *document, string tree_string) {
  TSNode root_node = ts_document_root_node(document);
  const char *node_string = ts_node_string(root_node, document);
  string result(node_string);
  ts_free((void *)node_string);
  AssertThat(result, Equals(tree_string));
}

static void assert_consistent_sizes(TSNode node) {
  size_t child_count = ts_node_child_count(node);
  size_t start_byte = ts_node_start_byte(node);
  size_t end_byte = ts_node_end_byte(node);
  TSPoint start_point = ts_node_start_point(node);
  TSPoint end_point = ts_node_end_point(node);
  bool some_child_has_changes = false;

  AssertThat(start_byte, !IsGreaterThan(end_byte));
  AssertThat(start_point, !IsGreaterThan(end_point));

  size_t last_child_end_byte = start_byte;
  TSPoint last_child_end_point = start_point;

  for (size_t i = 0; i < child_count; i++) {
    TSNode child = ts_node_child(node, i);
    size_t child_start_byte = ts_node_start_byte(child);
    TSPoint child_start_point = ts_node_start_point(child);

    AssertThat(child_start_byte, !IsLessThan(last_child_end_byte));
    AssertThat(child_start_point, !IsLessThan(last_child_end_point));
    assert_consistent_sizes(child);
    if (ts_node_has_changes(child))
      some_child_has_changes = true;

    last_child_end_byte = ts_node_end_byte(child);
    last_child_end_point = ts_node_end_point(child);
  }

  if (child_count > 0) {
    AssertThat(end_byte, !IsLessThan(last_child_end_byte));
    AssertThat(end_point, !IsLessThan(last_child_end_point));
  }

  if (some_child_has_changes) {
    AssertThat(ts_node_has_changes(node), IsTrue());
  }
}

static void assert_correct_tree_size(TSDocument *document, string content) {
  TSNode root_node = ts_document_root_node(document);
  size_t expected_size = content.size();

  // In the JSON grammar, the start rule (`_value`) is hidden, so the node
  // returned from `ts_document_root_node` (e.g. an `object` node), does not
  // actually point to the root of the tree. In this weird case, trailing
  // whitespace is not included in the root node's size.
  //
  // TODO: Fix this inconsistency. Maybe disallow the start rule being hidden?
  if (ts_document_language(document) == get_test_language("json") &&
      string(ts_node_type(root_node, document)) != "ERROR")
    expected_size = content.find_last_not_of("\n ") + 1;

  AssertThat(ts_node_end_byte(root_node), Equals(expected_size));
  assert_consistent_sizes(root_node);
}

START_TEST

describe("The Corpus", []() {
  vector<string> test_languages({
    "javascript",
    "json",
    "c",
    "cpp",
    "python",
  });

  for (auto &language_name : test_languages) {
    describe(("the " + language_name + " language").c_str(), [&]() {
      TSDocument *document;

      before_each([&]() {
        record_alloc::start();
        document = ts_document_new();
        ts_document_set_language(document, get_test_language(language_name));

        // ts_document_set_logger(document, stderr_logger_new(true));
        // ts_document_print_debugging_graphs(document, true);
      });

      after_each([&]() {
        ts_document_free(document);
        AssertThat(record_alloc::outstanding_allocation_indices(), IsEmpty());
      });

      for (auto &entry : read_corpus_entries(language_name)) {
        SpyInput *input;

        auto it_handles_edit_sequence = [&](string name, std::function<void()> edit_sequence){
          it(("parses " + entry.description + ": " + name).c_str(), [&]() {
            input = new SpyInput(entry.input, 3);
            ts_document_set_input(document, input->input());
            edit_sequence();
            assert_correct_tree_shape(document, entry.tree_string);
            assert_correct_tree_size(document, input->content);
            delete input;
          });
        };

        it_handles_edit_sequence("initial parse", [&]() {
          ts_document_parse(document);
        });

        std::set<std::pair<size_t, size_t>> deletions;
        std::set<std::pair<size_t, string>> insertions;

        for (size_t i = 0; i < 60; i++) {
          size_t edit_position = random() % utf8_char_count(entry.input);
          size_t deletion_size = random() % (utf8_char_count(entry.input) - edit_position);
          string inserted_text = random_words(random() % 4 + 1);

          if (language_name == "python") return;

          if (insertions.insert({edit_position, inserted_text}).second) {
            string description = "\"" + inserted_text + "\" at " + to_string(edit_position);

            it_handles_edit_sequence("repairing an insertion of " + description, [&]() {
              ts_document_edit(document, input->replace(edit_position, 0, inserted_text));
              ts_document_parse(document);
              assert_correct_tree_size(document, input->content);

              ts_document_edit(document, input->undo());
              assert_correct_tree_size(document, input->content);

              TSRange *ranges;
              uint32_t range_count;
              ScopeSequence old_scope_sequence = build_scope_sequence(document, input->content);
              ts_document_parse_and_get_changed_ranges(document, &ranges, &range_count);

              ScopeSequence new_scope_sequence = build_scope_sequence(document, input->content);
              verify_changed_ranges(old_scope_sequence, new_scope_sequence,
                                    input->content, ranges, range_count);
              ts_free(ranges);
            });
          }

          if (deletions.insert({edit_position, deletion_size}).second) {
            string desription = to_string(edit_position) + "-" + to_string(edit_position + deletion_size);

            it_handles_edit_sequence("repairing a deletion of " + desription, [&]() {
              ts_document_edit(document, input->replace(edit_position, deletion_size, ""));
              ts_document_parse(document);
              assert_correct_tree_size(document, input->content);

              ts_document_edit(document, input->undo());
              assert_correct_tree_size(document, input->content);

              TSRange *ranges;
              uint32_t range_count;
              ScopeSequence old_scope_sequence = build_scope_sequence(document, input->content);
              ts_document_parse_and_get_changed_ranges(document, &ranges, &range_count);

              ScopeSequence new_scope_sequence = build_scope_sequence(document, input->content);
              verify_changed_ranges(old_scope_sequence, new_scope_sequence,
                                    input->content, ranges, range_count);
              ts_free(ranges);
            });
          }
        }
      }
    });
  }
});

END_TEST
<commit_msg>Enable randomized incremental parsing tests for Python<commit_after>#include "spec_helper.h"
#include "runtime/alloc.h"
#include "helpers/load_language.h"
#include "helpers/read_test_entries.h"
#include "helpers/spy_input.h"
#include "helpers/stderr_logger.h"
#include "helpers/point_helpers.h"
#include "helpers/encoding_helpers.h"
#include "helpers/record_alloc.h"
#include "helpers/random_helpers.h"
#include "helpers/scope_sequence.h"
#include <set>

static void assert_correct_tree_shape(const TSDocument *document, string tree_string) {
  TSNode root_node = ts_document_root_node(document);
  const char *node_string = ts_node_string(root_node, document);
  string result(node_string);
  ts_free((void *)node_string);
  AssertThat(result, Equals(tree_string));
}

static void assert_consistent_sizes(TSNode node) {
  size_t child_count = ts_node_child_count(node);
  size_t start_byte = ts_node_start_byte(node);
  size_t end_byte = ts_node_end_byte(node);
  TSPoint start_point = ts_node_start_point(node);
  TSPoint end_point = ts_node_end_point(node);
  bool some_child_has_changes = false;

  AssertThat(start_byte, !IsGreaterThan(end_byte));
  AssertThat(start_point, !IsGreaterThan(end_point));

  size_t last_child_end_byte = start_byte;
  TSPoint last_child_end_point = start_point;

  for (size_t i = 0; i < child_count; i++) {
    TSNode child = ts_node_child(node, i);
    size_t child_start_byte = ts_node_start_byte(child);
    TSPoint child_start_point = ts_node_start_point(child);

    AssertThat(child_start_byte, !IsLessThan(last_child_end_byte));
    AssertThat(child_start_point, !IsLessThan(last_child_end_point));
    assert_consistent_sizes(child);
    if (ts_node_has_changes(child))
      some_child_has_changes = true;

    last_child_end_byte = ts_node_end_byte(child);
    last_child_end_point = ts_node_end_point(child);
  }

  if (child_count > 0) {
    AssertThat(end_byte, !IsLessThan(last_child_end_byte));
    AssertThat(end_point, !IsLessThan(last_child_end_point));
  }

  if (some_child_has_changes) {
    AssertThat(ts_node_has_changes(node), IsTrue());
  }
}

static void assert_correct_tree_size(TSDocument *document, string content) {
  TSNode root_node = ts_document_root_node(document);
  size_t expected_size = content.size();

  // In the JSON grammar, the start rule (`_value`) is hidden, so the node
  // returned from `ts_document_root_node` (e.g. an `object` node), does not
  // actually point to the root of the tree. In this weird case, trailing
  // whitespace is not included in the root node's size.
  //
  // TODO: Fix this inconsistency. Maybe disallow the start rule being hidden?
  if (ts_document_language(document) == get_test_language("json") &&
      string(ts_node_type(root_node, document)) != "ERROR")
    expected_size = content.find_last_not_of("\n ") + 1;

  AssertThat(ts_node_end_byte(root_node), Equals(expected_size));
  assert_consistent_sizes(root_node);
}

START_TEST

describe("The Corpus", []() {
  vector<string> test_languages({
    "javascript",
    "json",
    "c",
    "cpp",
    "python",
  });

  for (auto &language_name : test_languages) {
    describe(("the " + language_name + " language").c_str(), [&]() {
      TSDocument *document;

      before_each([&]() {
        record_alloc::start();
        document = ts_document_new();
        ts_document_set_language(document, get_test_language(language_name));

        // ts_document_set_logger(document, stderr_logger_new(true));
        // ts_document_print_debugging_graphs(document, true);
      });

      after_each([&]() {
        ts_document_free(document);
        AssertThat(record_alloc::outstanding_allocation_indices(), IsEmpty());
      });

      for (auto &entry : read_corpus_entries(language_name)) {
        SpyInput *input;

        auto it_handles_edit_sequence = [&](string name, std::function<void()> edit_sequence){
          it(("parses " + entry.description + ": " + name).c_str(), [&]() {
            input = new SpyInput(entry.input, 3);
            ts_document_set_input(document, input->input());
            edit_sequence();
            assert_correct_tree_shape(document, entry.tree_string);
            assert_correct_tree_size(document, input->content);
            delete input;
          });
        };

        it_handles_edit_sequence("initial parse", [&]() {
          ts_document_parse(document);
        });

        std::set<std::pair<size_t, size_t>> deletions;
        std::set<std::pair<size_t, string>> insertions;

        for (size_t i = 0; i < 60; i++) {
          size_t edit_position = random() % utf8_char_count(entry.input);
          size_t deletion_size = random() % (utf8_char_count(entry.input) - edit_position);
          string inserted_text = random_words(random() % 4 + 1);

          if (insertions.insert({edit_position, inserted_text}).second) {
            string description = "\"" + inserted_text + "\" at " + to_string(edit_position);

            it_handles_edit_sequence("repairing an insertion of " + description, [&]() {
              ts_document_edit(document, input->replace(edit_position, 0, inserted_text));
              ts_document_parse(document);
              assert_correct_tree_size(document, input->content);

              ts_document_edit(document, input->undo());
              assert_correct_tree_size(document, input->content);

              TSRange *ranges;
              uint32_t range_count;
              ScopeSequence old_scope_sequence = build_scope_sequence(document, input->content);
              ts_document_parse_and_get_changed_ranges(document, &ranges, &range_count);

              ScopeSequence new_scope_sequence = build_scope_sequence(document, input->content);
              verify_changed_ranges(old_scope_sequence, new_scope_sequence,
                                    input->content, ranges, range_count);
              ts_free(ranges);
            });
          }

          if (deletions.insert({edit_position, deletion_size}).second) {
            string desription = to_string(edit_position) + "-" + to_string(edit_position + deletion_size);

            it_handles_edit_sequence("repairing a deletion of " + desription, [&]() {
              ts_document_edit(document, input->replace(edit_position, deletion_size, ""));
              ts_document_parse(document);
              assert_correct_tree_size(document, input->content);

              ts_document_edit(document, input->undo());
              assert_correct_tree_size(document, input->content);

              TSRange *ranges;
              uint32_t range_count;
              ScopeSequence old_scope_sequence = build_scope_sequence(document, input->content);
              ts_document_parse_and_get_changed_ranges(document, &ranges, &range_count);

              ScopeSequence new_scope_sequence = build_scope_sequence(document, input->content);
              verify_changed_ranges(old_scope_sequence, new_scope_sequence,
                                    input->content, ranges, range_count);
              ts_free(ranges);
            });
          }
        }
      }
    });
  }
});

END_TEST
<|endoftext|>