<commit_before>/*
 * MLPLM.cpp
 *
 *  Created on: 20.11.2013
 *      Author: cls
 */

#include "PLM.h"
#include <omp.h>
#include "../coarsening/ParallelPartitionCoarsening.h"
#include "../coarsening/ClusteringProjector.h"
#include "../auxiliary/Log.h"
#include "../auxiliary/Timer.h"
#include "../auxiliary/SignalHandling.h"

#include <sstream>

namespace NetworKit {

PLM::PLM(const Graph& G, bool refine, double gamma, std::string par, count maxIter, bool turbo, bool recurse) : CommunityDetectionAlgorithm(G), parallelism(par), refine(refine), gamma(gamma), maxIter(maxIter), turbo(turbo), recurse(recurse) {

}

PLM::PLM(const Graph& G, const PLM& other) : CommunityDetectionAlgorithm(G), parallelism(other.parallelism), refine(other.refine), gamma(other.gamma), maxIter(other.maxIter), turbo(other.turbo), recurse(other.recurse) {

}

void PLM::run() {
	Aux::SignalHandler handler;
	DEBUG("calling run method on " , G.toString());

	count z = G.upperNodeIdBound();

	// init communities to singletons
	Partition zeta(z);
	zeta.allToSingletons();
	index o = zeta.upperBound();

	// init graph-dependent temporaries
	std::vector<double> volNode(z, 0.0);
	// $\omega(E)$
	edgeweight total = G.totalEdgeWeight();
	DEBUG("total edge weight: " , total);
	edgeweight divisor = (2 * total * total); // needed in modularity calculation

	G.parallelForNodes([&](node u) { // calculate and store volume of each node
		volNode[u] += G.weightedDegree(u);
		volNode[u] += G.weight(u, u); // consider self-loop twice
		// TRACE("init volNode[" , u , "] to " , volNode[u]);
	});

	// init community-dependent temporaries
	std::vector<double> volCommunity(o, 0.0);
	zeta.parallelForEntries([&](node u, index C) { 	// set volume for all communities
		if (C != none)
			volCommunity[C] = volNode[u];
	});

	// first move phase
	bool moved = false; // indicates whether any node has been moved in the last pass
	bool change = false; // indicates whether the communities have changed at all

	// stores the affinity for each neighboring community (index), one vector per thread
	std::vector<std::vector<edgeweight> > turboAffinity;
	// stores the list of neighboring communities, one vector per thread
	std::vector<std::vector<index> > neigh_comm;

	if (turbo) {
		if (this->parallelism != "none" && this->parallelism != "none randomized") { // initialize arrays for all threads only when actually needed
			turboAffinity.resize(omp_get_max_threads());
			neigh_comm.resize(omp_get_max_threads());
			for (auto &it : turboAffinity) {
				// resize to maximum community id
				it.resize(zeta.upperBound());
			}
			for (auto &it : neigh_comm) {
				// resize to maximum size so no further memory allocation is needed
				it.resize(G.upperNodeIdBound());
			}
		} else { // initialize array only for first thread
			turboAffinity.emplace_back(zeta.upperBound());
			neigh_comm.emplace_back(G.upperNodeIdBound());
		}
	}

	// try to improve modularity by moving a node to neighboring clusters
	auto tryMove = [&](node u) {
		// TRACE("trying to move node " , u);
		index tid = omp_get_thread_num();

		// collect edge weight to neighbor clusters
		std::map<index, edgeweight> affinity;
		// only for turbo mode, stores the number of neighbors
		index numNeighbors = 0;

		if (turbo) {
			G.forNeighborsOf(u, [&](node v) {
				turboAffinity[tid][zeta[v]] = -1; // set all to -1 so we can see when we get to it the first time
			});
			turboAffinity[tid][zeta[u]] = 0;
			G.forNeighborsOf(u, [&](node v, edgeweight weight) {
				if (u != v) {
					index C = zeta[v];
					if (turboAffinity[tid][C] == -1) {
						// found the neighbor for the first time, initialize to 0 and add to list of neighboring communities
						turboAffinity[tid][C] = 0;
						neigh_comm[tid][numNeighbors++] = C;
					}
					turboAffinity[tid][C] += weight;
				}
			});
		} else {
			G.forNeighborsOf(u, [&](node v, edgeweight weight) {
				if (u != v) {
					index C = zeta[v];
					affinity[C] += weight;
				}
			});
		}

		// sub-functions

		// $\vol(C \ {x})$ - volume of cluster C excluding node x
		auto volCommunityMinusNode = [&](index C, node x) {
			double volC = 0.0;
			double volN = 0.0;
			volC = volCommunity[C];
			if (zeta[x] == C) {
				volN = volNode[x];
				return volC - volN;
			} else {
				return volC;
			}
		};

		// // $\omega(u | C \ u)$
		// auto omegaCut = [&](node u, index C) {
		// 	return affinity[C];
		// };

		auto modGain = [&](node u, index C, index D, edgeweight affinityC, edgeweight affinityD) {
			double volN = 0.0;
			volN = volNode[u];
			double delta = (affinityD - affinityC) / total + this->gamma * ((volCommunityMinusNode(C, u) - volCommunityMinusNode(D, u)) * volN) / divisor;
			//TRACE("(" , affinity[D] , " - " , affinity[C] , ") / " , total , " + " , this->gamma , " * ((" , volCommunityMinusNode(C, u) , " - " , volCommunityMinusNode(D, u) , ") *" , volN , ") / 2 * " , (total * total));
			return delta;
		};

		index best = none;
		index C = none;
		index D = none;
		double deltaBest = -1;

		C = zeta[u];

		if (turbo) {
			edgeweight affinityC = turboAffinity[tid][C];

			for (index i = 0; i < numNeighbors; ++i) {
				D = neigh_comm[tid][i];

				if (D != C) { // consider only nodes in other clusters (and implicitly only nodes other than u)
					double delta = modGain(u, C, D, affinityC, turboAffinity[tid][D]);

					// TRACE("mod gain: " , delta);
					if (delta > deltaBest) {
						deltaBest = delta;
						best = D;
					}
				}
			}
		} else {
			edgeweight affinityC = affinity[C];

//			TRACE("Processing neighborhood of node " , u , ", which is in cluster " , C);
			for (auto it : affinity) {
				D = it.first;
				if (D != C) { // consider only nodes in other clusters (and implicitly only nodes other than u)
					double delta = modGain(u, C, D, affinityC, it.second);
					// TRACE("mod gain: " , delta);
					if (delta > deltaBest) {
						deltaBest = delta;
						best = D;
					}
				}
			}
		}

		// TRACE("deltaBest=" , deltaBest);
		if (deltaBest > 0) { // if modularity improvement possible
			assert (best != C && best != none);// do not "move" to original cluster

			zeta[u] = best; // move to best cluster
			// TRACE("node " , u , " moved");

			// mod update
			double volN = 0.0;
			volN = volNode[u];
			// update the volume of the two clusters
			#pragma omp atomic update
			volCommunity[C] -= volN;
			#pragma omp atomic update
			volCommunity[best] += volN;

			moved = true; // change to clustering has been made

		} else {
			// TRACE("node " , u , " not moved");
		}
	};

	// performs node moves
	auto movePhase = [&](){
		count iter = 0;
		do {
			moved = false;
			// apply node movement according to parallelization strategy
			if (this->parallelism == "none") {
				G.forNodes(tryMove);
			} else if (this->parallelism == "simple") {
				G.parallelForNodes(tryMove);
			} else if (this->parallelism == "balanced") {
				G.balancedParallelForNodes(tryMove);
			} else if (this->parallelism == "none randomized") {
				G.forNodesInRandomOrder(tryMove);
			} else {
				ERROR("unknown parallelization strategy: " , this->parallelism);
				throw std::runtime_error("unknown parallelization strategy");
			}
			if (moved) change = true;

			if (iter == maxIter) {
				WARN("move phase aborted after ", maxIter, " iterations");
			}
			iter += 1;
		} while (moved && (iter <= maxIter) && handler.isRunning());
		DEBUG("iterations in move phase: ", iter);
	};
	handler.assureRunning();
	// first move phase
	Aux::Timer timer;
	timer.start();
	//
	movePhase();
	//
	timer.stop();
	timing["move"].push_back(timer.elapsedMilliseconds());
	handler.assureRunning();
	if (recurse && change) {
		INFO("nodes moved, so begin coarsening and recursive call");

		timer.start();
		//
		std::pair<Graph, std::vector<node>> coarsened = coarsen(G, zeta);	// coarsen graph according to communitites
		//
		timer.stop();
		timing["coarsen"].push_back(timer.elapsedMilliseconds());

		PLM onCoarsened(coarsened.first, this->refine, this->gamma, this->parallelism, this->maxIter, this->turbo);
		onCoarsened.run();
		Partition zetaCoarse = onCoarsened.getPartition();

		// get timings
		auto tim = onCoarsened.getTiming();
		for (count t : tim["move"]) {
			timing["move"].push_back(t);
		}
		for (count t : tim["coarsen"]) {
			timing["coarsen"].push_back(t);
		}
		for (count t : tim["refine"]) {
			timing["refine"].push_back(t);
		}

		INFO("coarse graph has ", coarsened.first.numberOfNodes(), " nodes and ", coarsened.first.numberOfEdges(), " edges");
		zeta = prolong(coarsened.first, zetaCoarse, G, coarsened.second); // unpack communities in coarse graph onto fine graph
		// refinement phase
		if (refine) {
			DEBUG("refinement phase");
			// reinit community-dependent temporaries
			o = zeta.upperBound();
			volCommunity.clear();
			volCommunity.resize(o, 0.0);
			zeta.parallelForEntries([&](node u, index C) { 	// set volume for all communities
				if (C != none) {
					edgeweight volN = volNode[u];
					#pragma omp atomic update
					volCommunity[C] += volN;
				}
			});
			// second move phase
			timer.start();
			//
			movePhase();
			//
			timer.stop();
			timing["refine"].push_back(timer.elapsedMilliseconds());

		}
	}
	result = std::move(zeta);
	hasRun = true;
}

std::string NetworKit::PLM::toString() const {
	std::stringstream stream;
	stream << "PLM(";
	stream << parallelism;
	if (refine) {
		stream << "," << "refine";
	}
	stream << "," << "pc";
	if (turbo) {
		stream << "," << "turbo";
	}
	if (!recurse) {
		stream << "," << "non-recursive";
	}
	stream << ")";

	return stream.str();
}

std::pair<Graph, std::vector<node> > PLM::coarsen(const Graph& G, const Partition& zeta) {
	ParallelPartitionCoarsening parCoarsening(G, zeta);
	parCoarsening.run();
	return {parCoarsening.getCoarseGraph(),parCoarsening.getFineToCoarseNodeMapping()};
}

Partition PLM::prolong(const Graph& Gcoarse, const Partition& zetaCoarse, const Graph& Gfine, std::vector<node> nodeToMetaNode) {
	Partition zetaFine(Gfine.upperNodeIdBound());
	zetaFine.setUpperBound(zetaCoarse.upperBound());

	Gfine.forNodes([&](node v) {
		node mv = nodeToMetaNode[v];
		index cv = zetaCoarse[mv];
		zetaFine[v] = cv;
	});

	return zetaFine;
}

std::map<std::string, std::vector<count> > PLM::getTiming() {
	return timing;
}

} /* namespace NetworKit */
<commit_msg>PLM: use less memory when the maximum degree is small<commit_after>/*
 * MLPLM.cpp
 *
 *  Created on: 20.11.2013
 *      Author: cls
 */

#include "PLM.h"
#include <omp.h>
#include "../coarsening/ParallelPartitionCoarsening.h"
#include "../coarsening/ClusteringProjector.h"
#include "../auxiliary/Log.h"
#include "../auxiliary/Timer.h"
#include "../auxiliary/SignalHandling.h"

#include <sstream>

namespace NetworKit {

PLM::PLM(const Graph& G, bool refine, double gamma, std::string par, count maxIter, bool turbo, bool recurse) : CommunityDetectionAlgorithm(G), parallelism(par), refine(refine), gamma(gamma), maxIter(maxIter), turbo(turbo), recurse(recurse) {

}

PLM::PLM(const Graph& G, const PLM& other) : CommunityDetectionAlgorithm(G), parallelism(other.parallelism), refine(other.refine), gamma(other.gamma), maxIter(other.maxIter), turbo(other.turbo), recurse(other.recurse) {

}

void PLM::run() {
	Aux::SignalHandler handler;
	DEBUG("calling run method on " , G.toString());

	count z = G.upperNodeIdBound();

	// init communities to singletons
	Partition zeta(z);
	zeta.allToSingletons();
	index o = zeta.upperBound();

	// init graph-dependent temporaries
	std::vector<double> volNode(z, 0.0);
	// $\omega(E)$
	edgeweight total = G.totalEdgeWeight();
	DEBUG("total edge weight: " , total);
	edgeweight divisor = (2 * total * total); // needed in modularity calculation

	G.parallelForNodes([&](node u) { // calculate and store volume of each node
		volNode[u] += G.weightedDegree(u);
		volNode[u] += G.weight(u, u); // consider self-loop twice
		// TRACE("init volNode[" , u , "] to " , volNode[u]);
	});

	// init community-dependent temporaries
	std::vector<double> volCommunity(o, 0.0);
	zeta.parallelForEntries([&](node u, index C) { 	// set volume for all communities
		if (C != none)
			volCommunity[C] = volNode[u];
	});

	// first move phase
	bool moved = false; // indicates whether any node has been moved in the last pass
	bool change = false; // indicates whether the communities have changed at all

	// stores the affinity for each neighboring community (index), one vector per thread
	std::vector<std::vector<edgeweight> > turboAffinity;
	// stores the list of neighboring communities, one vector per thread
	std::vector<std::vector<index> > neigh_comm;

	if (turbo) {
		if (this->parallelism != "none" && this->parallelism != "none randomized") { // initialize arrays for all threads only when actually needed
			turboAffinity.resize(omp_get_max_threads());
			neigh_comm.resize(omp_get_max_threads());
			for (auto &it : turboAffinity) {
				// resize to maximum community id
				it.resize(zeta.upperBound());
			}
		} else { // initialize array only for first thread
			turboAffinity.emplace_back(zeta.upperBound());
			neigh_comm.emplace_back();
		}
	}

	// try to improve modularity by moving a node to neighboring clusters
	auto tryMove = [&](node u) {
		// TRACE("trying to move node " , u);
		index tid = omp_get_thread_num();

		// collect edge weight to neighbor clusters
		std::map<index, edgeweight> affinity;

		if (turbo) {
			neigh_comm[tid].clear();
			G.forNeighborsOf(u, [&](node v) {
				turboAffinity[tid][zeta[v]] = -1; // set all to -1 so we can see when we get to it the first time
			});
			turboAffinity[tid][zeta[u]] = 0;
			G.forNeighborsOf(u, [&](node v, edgeweight weight) {
				if (u != v) {
					index C = zeta[v];
					if (turboAffinity[tid][C] == -1) {
						// found the neighbor for the first time, initialize to 0 and add to list of neighboring communities
						turboAffinity[tid][C] = 0;
						neigh_comm[tid].push_back(C);
					}
					turboAffinity[tid][C] += weight;
				}
			});
		} else {
			G.forNeighborsOf(u, [&](node v, edgeweight weight) {
				if (u != v) {
					index C = zeta[v];
					affinity[C] += weight;
				}
			});
		}

		// sub-functions

		// $\vol(C \ {x})$ - volume of cluster C excluding node x
		auto volCommunityMinusNode = [&](index C, node x) {
			double volC = 0.0;
			double volN = 0.0;
			volC = volCommunity[C];
			if (zeta[x] == C) {
				volN = volNode[x];
				return volC - volN;
			} else {
				return volC;
			}
		};

		// // $\omega(u | C \ u)$
		// auto omegaCut = [&](node u, index C) {
		// 	return affinity[C];
		// };

		auto modGain = [&](node u, index C, index D, edgeweight affinityC, edgeweight affinityD) {
			double volN = 0.0;
			volN = volNode[u];
			double delta = (affinityD - affinityC) / total + this->gamma * ((volCommunityMinusNode(C, u) - volCommunityMinusNode(D, u)) * volN) / divisor;
			//TRACE("(" , affinity[D] , " - " , affinity[C] , ") / " , total , " + " , this->gamma , " * ((" , volCommunityMinusNode(C, u) , " - " , volCommunityMinusNode(D, u) , ") *" , volN , ") / 2 * " , (total * total));
			return delta;
		};

		index best = none;
		index C = none;
		double deltaBest = -1;

		C = zeta[u];

		if (turbo) {
			edgeweight affinityC = turboAffinity[tid][C];

			for (index D : neigh_comm[tid]) {
				if (D != C) { // consider only nodes in other clusters (and implicitly only nodes other than u)
					double delta = modGain(u, C, D, affinityC, turboAffinity[tid][D]);

					// TRACE("mod gain: " , delta);
					if (delta > deltaBest) {
						deltaBest = delta;
						best = D;
					}
				}
			}
		} else {
			edgeweight affinityC = affinity[C];

//			TRACE("Processing neighborhood of node " , u , ", which is in cluster " , C);
			for (auto it : affinity) {
				index D = it.first;
				if (D != C) { // consider only nodes in other clusters (and implicitly only nodes other than u)
					double delta = modGain(u, C, D, affinityC, it.second);
					// TRACE("mod gain: " , delta);
					if (delta > deltaBest) {
						deltaBest = delta;
						best = D;
					}
				}
			}
		}

		// TRACE("deltaBest=" , deltaBest);
		if (deltaBest > 0) { // if modularity improvement possible
			assert (best != C && best != none);// do not "move" to original cluster

			zeta[u] = best; // move to best cluster
			// TRACE("node " , u , " moved");

			// mod update
			double volN = 0.0;
			volN = volNode[u];
			// update the volume of the two clusters
			#pragma omp atomic update
			volCommunity[C] -= volN;
			#pragma omp atomic update
			volCommunity[best] += volN;

			moved = true; // change to clustering has been made

		} else {
			// TRACE("node " , u , " not moved");
		}
	};

	// performs node moves
	auto movePhase = [&](){
		count iter = 0;
		do {
			moved = false;
			// apply node movement according to parallelization strategy
			if (this->parallelism == "none") {
				G.forNodes(tryMove);
			} else if (this->parallelism == "simple") {
				G.parallelForNodes(tryMove);
			} else if (this->parallelism == "balanced") {
				G.balancedParallelForNodes(tryMove);
			} else if (this->parallelism == "none randomized") {
				G.forNodesInRandomOrder(tryMove);
			} else {
				ERROR("unknown parallelization strategy: " , this->parallelism);
				throw std::runtime_error("unknown parallelization strategy");
			}
			if (moved) change = true;

			if (iter == maxIter) {
				WARN("move phase aborted after ", maxIter, " iterations");
			}
			iter += 1;
		} while (moved && (iter <= maxIter) && handler.isRunning());
		DEBUG("iterations in move phase: ", iter);
	};
	handler.assureRunning();
	// first move phase
	Aux::Timer timer;
	timer.start();
	//
	movePhase();
	//
	timer.stop();
	timing["move"].push_back(timer.elapsedMilliseconds());
	handler.assureRunning();
	if (recurse && change) {
		INFO("nodes moved, so begin coarsening and recursive call");

		timer.start();
		//
		std::pair<Graph, std::vector<node>> coarsened = coarsen(G, zeta);	// coarsen graph according to communitites
		//
		timer.stop();
		timing["coarsen"].push_back(timer.elapsedMilliseconds());

		PLM onCoarsened(coarsened.first, this->refine, this->gamma, this->parallelism, this->maxIter, this->turbo);
		onCoarsened.run();
		Partition zetaCoarse = onCoarsened.getPartition();

		// get timings
		auto tim = onCoarsened.getTiming();
		for (count t : tim["move"]) {
			timing["move"].push_back(t);
		}
		for (count t : tim["coarsen"]) {
			timing["coarsen"].push_back(t);
		}
		for (count t : tim["refine"]) {
			timing["refine"].push_back(t);
		}

		INFO("coarse graph has ", coarsened.first.numberOfNodes(), " nodes and ", coarsened.first.numberOfEdges(), " edges");
		zeta = prolong(coarsened.first, zetaCoarse, G, coarsened.second); // unpack communities in coarse graph onto fine graph
		// refinement phase
		if (refine) {
			DEBUG("refinement phase");
			// reinit community-dependent temporaries
			o = zeta.upperBound();
			volCommunity.clear();
			volCommunity.resize(o, 0.0);
			zeta.parallelForEntries([&](node u, index C) { 	// set volume for all communities
				if (C != none) {
					edgeweight volN = volNode[u];
					#pragma omp atomic update
					volCommunity[C] += volN;
				}
			});
			// second move phase
			timer.start();
			//
			movePhase();
			//
			timer.stop();
			timing["refine"].push_back(timer.elapsedMilliseconds());

		}
	}
	result = std::move(zeta);
	hasRun = true;
}

std::string NetworKit::PLM::toString() const {
	std::stringstream stream;
	stream << "PLM(";
	stream << parallelism;
	if (refine) {
		stream << "," << "refine";
	}
	stream << "," << "pc";
	if (turbo) {
		stream << "," << "turbo";
	}
	if (!recurse) {
		stream << "," << "non-recursive";
	}
	stream << ")";

	return stream.str();
}

std::pair<Graph, std::vector<node> > PLM::coarsen(const Graph& G, const Partition& zeta) {
	ParallelPartitionCoarsening parCoarsening(G, zeta);
	parCoarsening.run();
	return {parCoarsening.getCoarseGraph(),parCoarsening.getFineToCoarseNodeMapping()};
}

Partition PLM::prolong(const Graph& Gcoarse, const Partition& zetaCoarse, const Graph& Gfine, std::vector<node> nodeToMetaNode) {
	Partition zetaFine(Gfine.upperNodeIdBound());
	zetaFine.setUpperBound(zetaCoarse.upperBound());

	Gfine.forNodes([&](node v) {
		node mv = nodeToMetaNode[v];
		index cv = zetaCoarse[mv];
		zetaFine[v] = cv;
	});

	return zetaFine;
}

std::map<std::string, std::vector<count> > PLM::getTiming() {
	return timing;
}

} /* namespace NetworKit */
<|endoftext|>


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

#include <precomp.h>
#include "hi_linkhelper.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_module.hxx>

const ary::idl::Module *
LinkHelper::Search_CurModule() const
{
    return Search_Module( rEnv.CurPosition().RelatedNode() );
}

const ary::idl::Module *
LinkHelper::Search_Module( output::Node & i_node ) const
{
    static StringVector aNames_;

    output::Node::relative_id
        nId = i_node.RelatedNameRoom();
    if (nId == 0)
    {
        csv::erase_container(aNames_);
        i_node.Get_Chain(aNames_);
        const ary::idl::Module *  pModule =
            rEnv.Data().Search_Module(aNames_);
        if ( pModule == 0 )
            return 0;
        nId = static_cast<output::Node::relative_id>(pModule->Id());
        rEnv.CurPosition().RelatedNode().Set_RelatedNameRoom(nId);
    }

    return & rEnv.Data().Find_Module( ary::idl::Ce_id(nId) );
}

LinkHelper::OutPosition
LinkHelper::PositionOf_Ce(const CE & i_ce) const
{
    static StringVector aModule_;
    csv::erase_container(aModule_);
    String sCe;
    String sMember;
    rEnv.Data().Get_CeText(aModule_, sCe, sMember, i_ce);
    output::Node &
        rNode = rEnv.OutputTree().RootNode().Provide_Child(aModule_);
    return OutPosition(rNode,sCe);
}

namespace
{
    const String C_sXrefsSuffix("-xref");
}

LinkHelper::OutPosition
LinkHelper::PositionOf_CurXRefs( const String & i_ceName ) const
{
    return OutPosition( rEnv.CurPosition(),
                        StreamLock(100)() << i_ceName
                                              << C_sXrefsSuffix
                                              << ".html"
                                              << c_str );
}

const String &
LinkHelper::XrefsSuffix() const
{
    return C_sXrefsSuffix;
}

String
nameChainLinker( const char * )
{
    static const String
        sModuleFileName_( output::ModuleFileName() );
    return sModuleFileName_;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.98); FILE MERGED 2005/09/05 13:11:10 rt 1.2.98.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hi_linkhelper.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 17:52:33 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include "hi_linkhelper.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_module.hxx>

const ary::idl::Module *
LinkHelper::Search_CurModule() const
{
    return Search_Module( rEnv.CurPosition().RelatedNode() );
}

const ary::idl::Module *
LinkHelper::Search_Module( output::Node & i_node ) const
{
    static StringVector aNames_;

    output::Node::relative_id
        nId = i_node.RelatedNameRoom();
    if (nId == 0)
    {
        csv::erase_container(aNames_);
        i_node.Get_Chain(aNames_);
        const ary::idl::Module *  pModule =
            rEnv.Data().Search_Module(aNames_);
        if ( pModule == 0 )
            return 0;
        nId = static_cast<output::Node::relative_id>(pModule->Id());
        rEnv.CurPosition().RelatedNode().Set_RelatedNameRoom(nId);
    }

    return & rEnv.Data().Find_Module( ary::idl::Ce_id(nId) );
}

LinkHelper::OutPosition
LinkHelper::PositionOf_Ce(const CE & i_ce) const
{
    static StringVector aModule_;
    csv::erase_container(aModule_);
    String sCe;
    String sMember;
    rEnv.Data().Get_CeText(aModule_, sCe, sMember, i_ce);
    output::Node &
        rNode = rEnv.OutputTree().RootNode().Provide_Child(aModule_);
    return OutPosition(rNode,sCe);
}

namespace
{
    const String C_sXrefsSuffix("-xref");
}

LinkHelper::OutPosition
LinkHelper::PositionOf_CurXRefs( const String & i_ceName ) const
{
    return OutPosition( rEnv.CurPosition(),
                        StreamLock(100)() << i_ceName
                                              << C_sXrefsSuffix
                                              << ".html"
                                              << c_str );
}

const String &
LinkHelper::XrefsSuffix() const
{
    return C_sXrefsSuffix;
}

String
nameChainLinker( const char * )
{
    static const String
        sModuleFileName_( output::ModuleFileName() );
    return sModuleFileName_;
}
<|endoftext|>


<commit_before>#include "RobotCamera.h"

RobotCamera::RobotCamera(GLint viewWidth, GLint viewHeight, GLfloat viewNearPlane, GLfloat viewFarPlane)
{
	Camera::initialize(viewWidth, viewHeight, viewNearPlane, viewFarPlane);
	hasRobot = false;
	//camera location

	locX = 0.0f;
	locY = 0.0f;
	locZ = 0.0f;
	lookAt[0] = 0.0f;
	lookAt[1] = 0.0f;
	lookAt[2] = 0.0f;
	fovy = DEFAULT_FOVY;
	robot = NULL;

}

void RobotCamera::view(){
	if(hasRobot){
		glMatrixMode(GL_PROJECTION); //why?
		glLoadIdentity();
		gluPerspective(fovy,viewWidth/viewHeight, viewNearPlane, viewFarPlane);
		gluLookAt(locX, locY, locZ,lookAt[0], lookAt[1], lookAt[2],0,1,0);
		//updateFog();
	}
}

void RobotCamera::updateFog()
{
        GLfloat flowLight[] = {0.5, 0.5, 0.5, 1};
        glEnable(GL_FOG);
        glFogfv(GL_FOG_COLOR, flowLight);
        glFogf(GL_FOG_START, locZ);
        glFogf(GL_FOG_END, locZ + 10);
        glFogf(GL_FOG_DENSITY, 0.4f);
        glFogi(GL_FOG_MODE, GL_LINEAR);
}

//----------------------------------------------------------------
//							ORIENTATION
//----------------------------------------------------------------
void RobotCamera::moveCameraForwards(bool negateTheValue){
	if(robot != NULL){
			robot->incrementPitchAngle(!negateTheValue);
	}
}

void RobotCamera::modifyYaw(bool negateTheValue, int x, int y){
	if(robot != NULL){
			robot->incrementYawAngle(!negateTheValue);
	}
}

void RobotCamera::moveCameraStrafe(bool negateTheValue){
	if(robot != NULL){
			robot->incrementSpinDegrees(negateTheValue);
	}
}

void RobotCamera::resetCameraAngle(){
	if(robot != NULL){
		robot->resetOrientation();
	}
}

//----------------------------------------------------------------
//							LIGHTING
//----------------------------------------------------------------

void RobotCamera::toggleLight()
{
	robot->toggleLight();
}

//----------------------------------------------------------------
//			ROBOT ATTACHMENT AND SYNCHRONIZATION
//----------------------------------------------------------------
// FUTURE IDEAS: Eventually to to prepare for deleting robots (ie. detach)

void RobotCamera::attachToRobot(Robot* r){
	if(r != NULL){
		robot = r;
		hasRobot = true;
		robot->attachToCamera(this);
		synchEyePosition();
		synchLookAtPosition();
	}
}

void RobotCamera::synchEyePosition(){
	locX = robot->getEyeX();
	locY = robot->getEyeY();
	locZ = robot->getEyeZ();
}

void RobotCamera::synchLookAtPosition(){
	GLfloat* i = robot->getLookAt();
	lookAt[0] = i[0];
	lookAt[1] = i[1];
	lookAt[2] = i[2];
	delete [] i;
}

void RobotCamera::update(){
	synchEyePosition();
	synchLookAtPosition();
}

<commit_msg>fixed the see through the walls bug in deathmatch<commit_after>#include "RobotCamera.h"

RobotCamera::RobotCamera(GLint viewWidth, GLint viewHeight, GLfloat viewNearPlane, GLfloat viewFarPlane)
{
	Camera::initialize(viewWidth, viewHeight, viewNearPlane, viewFarPlane);
	hasRobot = false;
	//camera location

	locX = 0.0f;
	locY = 0.0f;
	locZ = 0.0f;
	lookAt[0] = 0.0f;
	lookAt[1] = 0.0f;
	lookAt[2] = 0.0f;
	fovy = DEFAULT_FOVY;
	robot = NULL;

}

void RobotCamera::view(){
	if(hasRobot){
		glMatrixMode(GL_PROJECTION); //why?
		glLoadIdentity();
		gluPerspective(fovy,viewWidth/viewHeight, 0.1, viewFarPlane);
		gluLookAt(locX, locY, locZ,lookAt[0], lookAt[1], lookAt[2],0,1,0);
		//updateFog();
	}
}

void RobotCamera::updateFog()
{
        GLfloat flowLight[] = {0.5, 0.5, 0.5, 1};
        glEnable(GL_FOG);
        glFogfv(GL_FOG_COLOR, flowLight);
        glFogf(GL_FOG_START, locZ);
        glFogf(GL_FOG_END, locZ + 10);
        glFogf(GL_FOG_DENSITY, 0.4f);
        glFogi(GL_FOG_MODE, GL_LINEAR);
}

//----------------------------------------------------------------
//							ORIENTATION
//----------------------------------------------------------------
void RobotCamera::moveCameraForwards(bool negateTheValue){
	if(robot != NULL){
			robot->incrementPitchAngle(!negateTheValue);
	}
}

void RobotCamera::modifyYaw(bool negateTheValue, int x, int y){
	if(robot != NULL){
			robot->incrementYawAngle(!negateTheValue);
	}
}

void RobotCamera::moveCameraStrafe(bool negateTheValue){
	if(robot != NULL){
			robot->incrementSpinDegrees(negateTheValue);
	}
}

void RobotCamera::resetCameraAngle(){
	if(robot != NULL){
		robot->resetOrientation();
	}
}

//----------------------------------------------------------------
//							LIGHTING
//----------------------------------------------------------------

void RobotCamera::toggleLight()
{
	robot->toggleLight();
}

//----------------------------------------------------------------
//			ROBOT ATTACHMENT AND SYNCHRONIZATION
//----------------------------------------------------------------
// FUTURE IDEAS: Eventually to to prepare for deleting robots (ie. detach)

void RobotCamera::attachToRobot(Robot* r){
	if(r != NULL){
		robot = r;
		hasRobot = true;
		robot->attachToCamera(this);
		synchEyePosition();
		synchLookAtPosition();
	}
}

void RobotCamera::synchEyePosition(){
	locX = robot->getEyeX();
	locY = robot->getEyeY();
	locZ = robot->getEyeZ();
}

void RobotCamera::synchLookAtPosition(){
	GLfloat* i = robot->getLookAt();
	lookAt[0] = i[0];
	lookAt[1] = i[1];
	lookAt[2] = i[2];
	delete [] i;
}

void RobotCamera::update(){
	synchEyePosition();
	synchLookAtPosition();
}

<|endoftext|>


<commit_before>//===-- ThreadList.cpp ------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>

#include <algorithm>

#include "lldb/Target/ThreadList.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/ThreadPlan.h"
#include "lldb/Target/Process.h"

using namespace lldb;
using namespace lldb_private;

ThreadList::ThreadList (Process *process) :
    m_process (process),
    m_stop_id (0),
    m_threads(),
    m_threads_mutex (Mutex::eMutexTypeRecursive),
    m_current_tid (LLDB_INVALID_THREAD_ID)
{
}

ThreadList::ThreadList (const ThreadList &rhs) :
    m_process (),
    m_stop_id (),
    m_threads (),
    m_threads_mutex (Mutex::eMutexTypeRecursive),
    m_current_tid ()
{
    // Use the assignment operator since it uses the mutex
    *this = rhs;
}

const ThreadList&
ThreadList::operator = (const ThreadList& rhs)
{
    if (this != &rhs)
    {
        // Lock both mutexes to make sure neither side changes anyone on us
        // while the assignement occurs
        Mutex::Locker locker_lhs(m_threads_mutex);
        Mutex::Locker locker_rhs(rhs.m_threads_mutex);
        m_process = rhs.m_process;
        m_stop_id = rhs.m_stop_id;
        m_threads = rhs.m_threads;
        m_current_tid = rhs.m_current_tid;
    }
    return *this;
}

ThreadList::~ThreadList()
{
}

uint32_t
ThreadList::GetStopID () const
{
    return m_stop_id;
}

void
ThreadList::SetStopID (uint32_t stop_id)
{
    m_stop_id = stop_id;
}

void
ThreadList::AddThread (ThreadSP &thread_sp)
{
    Mutex::Locker locker(m_threads_mutex);
    m_threads.push_back(thread_sp);
}

uint32_t
ThreadList::GetSize (bool can_update)
{
    Mutex::Locker locker(m_threads_mutex);
    if (can_update)
        m_process->UpdateThreadListIfNeeded();
    return m_threads.size();
}

ThreadSP
ThreadList::GetThreadAtIndex (uint32_t idx, bool can_update)
{
    Mutex::Locker locker(m_threads_mutex);
    if (can_update)
        m_process->UpdateThreadListIfNeeded();

    ThreadSP thread_sp;
    if (idx < m_threads.size())
        thread_sp = m_threads[idx];
    return thread_sp;
}

ThreadSP
ThreadList::FindThreadByID (lldb::tid_t tid, bool can_update)
{
    Mutex::Locker locker(m_threads_mutex);

    if (can_update)
        m_process->UpdateThreadListIfNeeded();

    ThreadSP thread_sp;
    uint32_t idx = 0;
    const uint32_t num_threads = m_threads.size();
    for (idx = 0; idx < num_threads; ++idx)
    {
        if (m_threads[idx]->GetID() == tid)
        {
            thread_sp = m_threads[idx];
            break;
        }
    }
    return thread_sp;
}

ThreadSP
ThreadList::GetThreadSPForThreadPtr (Thread *thread_ptr)
{
    ThreadSP thread_sp;
    if (thread_ptr)
    {
        Mutex::Locker locker(m_threads_mutex);

        uint32_t idx = 0;
        const uint32_t num_threads = m_threads.size();
        for (idx = 0; idx < num_threads; ++idx)
        {
            if (m_threads[idx].get() == thread_ptr)
            {
                thread_sp = m_threads[idx];
                break;
            }
        }
    }
    return thread_sp;
}

ThreadSP
ThreadList::FindThreadByIndexID (uint32_t index_id, bool can_update)
{
    Mutex::Locker locker(m_threads_mutex);

    if (can_update)
        m_process->UpdateThreadListIfNeeded();

    ThreadSP thread_sp;
    const uint32_t num_threads = m_threads.size();
    for (uint32_t idx = 0; idx < num_threads; ++idx)
    {
        if (m_threads[idx]->GetIndexID() == index_id)
        {
            thread_sp = m_threads[idx];
            break;
        }
    }
    return thread_sp;
}

bool
ThreadList::ShouldStop (Event *event_ptr)
{
    Mutex::Locker locker(m_threads_mutex);

    // Running events should never stop, obviously...

    bool should_stop = false;
    m_process->UpdateThreadListIfNeeded();

    collection::iterator pos, end = m_threads.end();

    // Run through the threads and ask whether we should stop.  Don't ask
    // suspended threads, however, it makes more sense for them to preserve their
    // state across the times the process runs but they don't get a chance to.
    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        ThreadSP thread_sp(*pos);
        if ((thread_sp->GetResumeState () != eStateSuspended) && (thread_sp->ThreadStoppedForAReason()))
        {
            should_stop |=  thread_sp->ShouldStop(event_ptr);
        }
    }

    if (should_stop)
    {
        for (pos = m_threads.begin(); pos != end; ++pos)
        {
            ThreadSP thread_sp(*pos);
            thread_sp->WillStop ();
        }
    }

    return should_stop;
}

Vote
ThreadList::ShouldReportStop (Event *event_ptr)
{
    Vote result = eVoteNoOpinion;
    m_process->UpdateThreadListIfNeeded();
    collection::iterator pos, end = m_threads.end();

    // Run through the threads and ask whether we should report this event.
    // For stopping, a YES vote wins over everything.  A NO vote wins over NO opinion.
    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        ThreadSP thread_sp(*pos);
        if (thread_sp->ThreadStoppedForAReason() && (thread_sp->GetResumeState () != eStateSuspended))
        {
            switch (thread_sp->ShouldReportStop (event_ptr))
            {
                case eVoteNoOpinion:
                    continue;
                case eVoteYes:
                    result = eVoteYes;
                    break;
                case eVoteNo:
                    if (result == eVoteNoOpinion)
                        result = eVoteNo;
                    break;
            }
        }
    }
    return result;
}

Vote
ThreadList::ShouldReportRun (Event *event_ptr)
{
    Vote result = eVoteNoOpinion;
    m_process->UpdateThreadListIfNeeded();
    collection::iterator pos, end = m_threads.end();

    // Run through the threads and ask whether we should report this event.
    // The rule is NO vote wins over everything, a YES vote wins over no opinion.

    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        ThreadSP thread_sp(*pos);
        if (thread_sp->GetResumeState () != eStateSuspended)

        switch (thread_sp->ShouldReportRun (event_ptr))
        {
            case eVoteNoOpinion:
                continue;
            case eVoteYes:
                if (result == eVoteNoOpinion)
                    result = eVoteYes;
                break;
            case eVoteNo:
                result = eVoteNo;
                break;
        }
    }
    return result;
}

void
ThreadList::Clear()
{
    m_stop_id = 0;
    m_threads.clear();
    m_current_tid = LLDB_INVALID_THREAD_ID;
}

void
ThreadList::RefreshStateAfterStop ()
{
    Mutex::Locker locker(m_threads_mutex);

    m_process->UpdateThreadListIfNeeded();

    collection::iterator pos, end = m_threads.end();
    for (pos = m_threads.begin(); pos != end; ++pos)
        (*pos)->RefreshStateAfterStop ();
}

void
ThreadList::DiscardThreadPlans ()
{
    // You don't need to update the thread list here, because only threads
    // that you currently know about have any thread plans.
    Mutex::Locker locker(m_threads_mutex);

    collection::iterator pos, end = m_threads.end();
    for (pos = m_threads.begin(); pos != end; ++pos)
        (*pos)->DiscardThreadPlans (true);

}

bool
ThreadList::WillResume ()
{
    // Run through the threads and perform their momentary actions.
    // But we only do this for threads that are running, user suspended
    // threads stay where they are.
    bool success = true;

    Mutex::Locker locker(m_threads_mutex);
    m_process->UpdateThreadListIfNeeded();

    collection::iterator pos, end = m_threads.end();

    // Give all the threads a last chance to set up their state before we
    // negotiate who is actually going to get a chance to run...

    for (pos = m_threads.begin(); pos != end; ++pos)
        (*pos)->SetupForResume ();

    // Now go through the threads and see if any thread wants to run just itself.
    // if so then pick one and run it.
    ThreadList run_me_only_list (m_process);

    run_me_only_list.SetStopID(m_process->GetStopID());

    ThreadSP immediate_thread_sp;
    bool run_only_current_thread = false;

    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        ThreadSP thread_sp(*pos);
        if (thread_sp->GetCurrentPlan()->IsImmediate())
        {
            // We first do all the immediate plans, so if we find one, set
            // immediate_thread_sp and break out, and we'll pick it up first thing
            // when we're negotiating which threads get to run.
            immediate_thread_sp = thread_sp;
            break;
        }
        else if (thread_sp->GetResumeState() != eStateSuspended &&
                 thread_sp->GetCurrentPlan()->StopOthers())
        {
            // You can't say "stop others" and also want yourself to be suspended.
            assert (thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);

            if (thread_sp == GetCurrentThread())
            {
                run_only_current_thread = true;
                run_me_only_list.Clear();
                run_me_only_list.AddThread (thread_sp);
                break;
            }

            run_me_only_list.AddThread (thread_sp);
        }

    }

    if (immediate_thread_sp)
    {
        for (pos = m_threads.begin(); pos != end; ++pos)
        {
            ThreadSP thread_sp(*pos);
            if (thread_sp.get() == immediate_thread_sp.get())
                thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
            else
                thread_sp->WillResume (eStateSuspended);
        }
    }
    else if (run_me_only_list.GetSize (false) == 0)
    {
        // Everybody runs as they wish:
        for (pos = m_threads.begin(); pos != end; ++pos)
        {
            ThreadSP thread_sp(*pos);
            thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
        }
    }
    else
    {
        ThreadSP thread_to_run;

        if (run_only_current_thread)
        {
            thread_to_run = GetCurrentThread();
        }
        else if (run_me_only_list.GetSize (false) == 1)
        {
            thread_to_run = run_me_only_list.GetThreadAtIndex (0);
        }
        else
        {
            int random_thread = (int)
                    ((run_me_only_list.GetSize (false) * (double) rand ()) / (RAND_MAX + 1.0));
            thread_to_run = run_me_only_list.GetThreadAtIndex (random_thread);
        }

        for (pos = m_threads.begin(); pos != end; ++pos)
        {
            ThreadSP thread_sp(*pos);
            if (thread_sp == thread_to_run)
                thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
            else
                thread_sp->WillResume (eStateSuspended);
        }
    }

    return success;
}

void
ThreadList::DidResume ()
{
    collection::iterator pos, end = m_threads.end();
    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        // Don't clear out threads that aren't going to get a chance to run, rather
        // leave their state for the next time around.
        ThreadSP thread_sp(*pos);
        if (thread_sp->GetResumeState() != eStateSuspended)
            thread_sp->DidResume ();
    }
}

ThreadSP
ThreadList::GetCurrentThread ()
{
    Mutex::Locker locker(m_threads_mutex);
    return FindThreadByID(m_current_tid);
}

bool
ThreadList::SetCurrentThreadByID (lldb::tid_t tid)
{
    Mutex::Locker locker(m_threads_mutex);
    if  (FindThreadByID(tid).get())
        m_current_tid = tid;
    else
        m_current_tid = LLDB_INVALID_THREAD_ID;

    return m_current_tid != LLDB_INVALID_THREAD_ID;
}

bool
ThreadList::SetCurrentThreadByIndexID (uint32_t index_id)
{
    Mutex::Locker locker(m_threads_mutex);
    ThreadSP thread_sp (FindThreadByIndexID(index_id));
    if  (thread_sp.get())
        m_current_tid = thread_sp->GetID();
    else
        m_current_tid = LLDB_INVALID_THREAD_ID;

    return m_current_tid != LLDB_INVALID_THREAD_ID;
}

<commit_msg>Don't call PrepareForResume on threads that aren't going to get a chance to run this time around.<commit_after>//===-- ThreadList.cpp ------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <stdlib.h>

#include <algorithm>

#include "lldb/Target/ThreadList.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/ThreadPlan.h"
#include "lldb/Target/Process.h"

using namespace lldb;
using namespace lldb_private;

ThreadList::ThreadList (Process *process) :
    m_process (process),
    m_stop_id (0),
    m_threads(),
    m_threads_mutex (Mutex::eMutexTypeRecursive),
    m_current_tid (LLDB_INVALID_THREAD_ID)
{
}

ThreadList::ThreadList (const ThreadList &rhs) :
    m_process (),
    m_stop_id (),
    m_threads (),
    m_threads_mutex (Mutex::eMutexTypeRecursive),
    m_current_tid ()
{
    // Use the assignment operator since it uses the mutex
    *this = rhs;
}

const ThreadList&
ThreadList::operator = (const ThreadList& rhs)
{
    if (this != &rhs)
    {
        // Lock both mutexes to make sure neither side changes anyone on us
        // while the assignement occurs
        Mutex::Locker locker_lhs(m_threads_mutex);
        Mutex::Locker locker_rhs(rhs.m_threads_mutex);
        m_process = rhs.m_process;
        m_stop_id = rhs.m_stop_id;
        m_threads = rhs.m_threads;
        m_current_tid = rhs.m_current_tid;
    }
    return *this;
}

ThreadList::~ThreadList()
{
}

uint32_t
ThreadList::GetStopID () const
{
    return m_stop_id;
}

void
ThreadList::SetStopID (uint32_t stop_id)
{
    m_stop_id = stop_id;
}

void
ThreadList::AddThread (ThreadSP &thread_sp)
{
    Mutex::Locker locker(m_threads_mutex);
    m_threads.push_back(thread_sp);
}

uint32_t
ThreadList::GetSize (bool can_update)
{
    Mutex::Locker locker(m_threads_mutex);
    if (can_update)
        m_process->UpdateThreadListIfNeeded();
    return m_threads.size();
}

ThreadSP
ThreadList::GetThreadAtIndex (uint32_t idx, bool can_update)
{
    Mutex::Locker locker(m_threads_mutex);
    if (can_update)
        m_process->UpdateThreadListIfNeeded();

    ThreadSP thread_sp;
    if (idx < m_threads.size())
        thread_sp = m_threads[idx];
    return thread_sp;
}

ThreadSP
ThreadList::FindThreadByID (lldb::tid_t tid, bool can_update)
{
    Mutex::Locker locker(m_threads_mutex);

    if (can_update)
        m_process->UpdateThreadListIfNeeded();

    ThreadSP thread_sp;
    uint32_t idx = 0;
    const uint32_t num_threads = m_threads.size();
    for (idx = 0; idx < num_threads; ++idx)
    {
        if (m_threads[idx]->GetID() == tid)
        {
            thread_sp = m_threads[idx];
            break;
        }
    }
    return thread_sp;
}

ThreadSP
ThreadList::GetThreadSPForThreadPtr (Thread *thread_ptr)
{
    ThreadSP thread_sp;
    if (thread_ptr)
    {
        Mutex::Locker locker(m_threads_mutex);

        uint32_t idx = 0;
        const uint32_t num_threads = m_threads.size();
        for (idx = 0; idx < num_threads; ++idx)
        {
            if (m_threads[idx].get() == thread_ptr)
            {
                thread_sp = m_threads[idx];
                break;
            }
        }
    }
    return thread_sp;
}

ThreadSP
ThreadList::FindThreadByIndexID (uint32_t index_id, bool can_update)
{
    Mutex::Locker locker(m_threads_mutex);

    if (can_update)
        m_process->UpdateThreadListIfNeeded();

    ThreadSP thread_sp;
    const uint32_t num_threads = m_threads.size();
    for (uint32_t idx = 0; idx < num_threads; ++idx)
    {
        if (m_threads[idx]->GetIndexID() == index_id)
        {
            thread_sp = m_threads[idx];
            break;
        }
    }
    return thread_sp;
}

bool
ThreadList::ShouldStop (Event *event_ptr)
{
    Mutex::Locker locker(m_threads_mutex);

    // Running events should never stop, obviously...

    bool should_stop = false;
    m_process->UpdateThreadListIfNeeded();

    collection::iterator pos, end = m_threads.end();

    // Run through the threads and ask whether we should stop.  Don't ask
    // suspended threads, however, it makes more sense for them to preserve their
    // state across the times the process runs but they don't get a chance to.
    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        ThreadSP thread_sp(*pos);
        if ((thread_sp->GetResumeState () != eStateSuspended) && (thread_sp->ThreadStoppedForAReason()))
        {
            should_stop |=  thread_sp->ShouldStop(event_ptr);
        }
    }

    if (should_stop)
    {
        for (pos = m_threads.begin(); pos != end; ++pos)
        {
            ThreadSP thread_sp(*pos);
            thread_sp->WillStop ();
        }
    }

    return should_stop;
}

Vote
ThreadList::ShouldReportStop (Event *event_ptr)
{
    Vote result = eVoteNoOpinion;
    m_process->UpdateThreadListIfNeeded();
    collection::iterator pos, end = m_threads.end();

    // Run through the threads and ask whether we should report this event.
    // For stopping, a YES vote wins over everything.  A NO vote wins over NO opinion.
    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        ThreadSP thread_sp(*pos);
        if (thread_sp->ThreadStoppedForAReason() && (thread_sp->GetResumeState () != eStateSuspended))
        {
            switch (thread_sp->ShouldReportStop (event_ptr))
            {
                case eVoteNoOpinion:
                    continue;
                case eVoteYes:
                    result = eVoteYes;
                    break;
                case eVoteNo:
                    if (result == eVoteNoOpinion)
                        result = eVoteNo;
                    break;
            }
        }
    }
    return result;
}

Vote
ThreadList::ShouldReportRun (Event *event_ptr)
{
    Vote result = eVoteNoOpinion;
    m_process->UpdateThreadListIfNeeded();
    collection::iterator pos, end = m_threads.end();

    // Run through the threads and ask whether we should report this event.
    // The rule is NO vote wins over everything, a YES vote wins over no opinion.

    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        ThreadSP thread_sp(*pos);
        if (thread_sp->GetResumeState () != eStateSuspended)

        switch (thread_sp->ShouldReportRun (event_ptr))
        {
            case eVoteNoOpinion:
                continue;
            case eVoteYes:
                if (result == eVoteNoOpinion)
                    result = eVoteYes;
                break;
            case eVoteNo:
                result = eVoteNo;
                break;
        }
    }
    return result;
}

void
ThreadList::Clear()
{
    m_stop_id = 0;
    m_threads.clear();
    m_current_tid = LLDB_INVALID_THREAD_ID;
}

void
ThreadList::RefreshStateAfterStop ()
{
    Mutex::Locker locker(m_threads_mutex);

    m_process->UpdateThreadListIfNeeded();

    collection::iterator pos, end = m_threads.end();
    for (pos = m_threads.begin(); pos != end; ++pos)
        (*pos)->RefreshStateAfterStop ();
}

void
ThreadList::DiscardThreadPlans ()
{
    // You don't need to update the thread list here, because only threads
    // that you currently know about have any thread plans.
    Mutex::Locker locker(m_threads_mutex);

    collection::iterator pos, end = m_threads.end();
    for (pos = m_threads.begin(); pos != end; ++pos)
        (*pos)->DiscardThreadPlans (true);

}

bool
ThreadList::WillResume ()
{
    // Run through the threads and perform their momentary actions.
    // But we only do this for threads that are running, user suspended
    // threads stay where they are.
    bool success = true;

    Mutex::Locker locker(m_threads_mutex);
    m_process->UpdateThreadListIfNeeded();

    collection::iterator pos, end = m_threads.end();

    // See if any thread wants to run stopping others.  If it does, then we won't
    // setup the other threads for resume, since they aren't going to get a chance
    // to run.  This is necessary because the SetupForResume might add "StopOthers"
    // plans which would then get to be part of the who-gets-to-run negotiation, but
    // they're coming in after the fact, and the threads that are already set up should
    // take priority.

    bool wants_solo_run = false;

    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        if ((*pos)->GetResumeState() != eStateSuspended &&
                 (*pos)->GetCurrentPlan()->StopOthers())
        {
            wants_solo_run = true;
            break;
        }
    }

    // Give all the threads that are likely to run a last chance to set up their state before we
    // negotiate who is actually going to get a chance to run...
    // Don't set to resume suspended threads, and if any thread wanted to stop others, only
    // call setup on the threads that request StopOthers...

    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        if ((*pos)->GetResumeState() != eStateSuspended
            && (!wants_solo_run || (*pos)->GetCurrentPlan()->StopOthers()))
        {
            (*pos)->SetupForResume ();
        }
    }

    // Now go through the threads and see if any thread wants to run just itself.
    // if so then pick one and run it.

    ThreadList run_me_only_list (m_process);

    run_me_only_list.SetStopID(m_process->GetStopID());

    ThreadSP immediate_thread_sp;
    bool run_only_current_thread = false;

    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        ThreadSP thread_sp(*pos);
        if (thread_sp->GetCurrentPlan()->IsImmediate())
        {
            // We first do all the immediate plans, so if we find one, set
            // immediate_thread_sp and break out, and we'll pick it up first thing
            // when we're negotiating which threads get to run.
            immediate_thread_sp = thread_sp;
            break;
        }
        else if (thread_sp->GetResumeState() != eStateSuspended &&
                 thread_sp->GetCurrentPlan()->StopOthers())
        {
            // You can't say "stop others" and also want yourself to be suspended.
            assert (thread_sp->GetCurrentPlan()->RunState() != eStateSuspended);

            if (thread_sp == GetCurrentThread())
            {
                run_only_current_thread = true;
                run_me_only_list.Clear();
                run_me_only_list.AddThread (thread_sp);
                break;
            }

            run_me_only_list.AddThread (thread_sp);
        }

    }

    if (immediate_thread_sp)
    {
        for (pos = m_threads.begin(); pos != end; ++pos)
        {
            ThreadSP thread_sp(*pos);
            if (thread_sp.get() == immediate_thread_sp.get())
                thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
            else
                thread_sp->WillResume (eStateSuspended);
        }
    }
    else if (run_me_only_list.GetSize (false) == 0)
    {
        // Everybody runs as they wish:
        for (pos = m_threads.begin(); pos != end; ++pos)
        {
            ThreadSP thread_sp(*pos);
            thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
        }
    }
    else
    {
        ThreadSP thread_to_run;

        if (run_only_current_thread)
        {
            thread_to_run = GetCurrentThread();
        }
        else if (run_me_only_list.GetSize (false) == 1)
        {
            thread_to_run = run_me_only_list.GetThreadAtIndex (0);
        }
        else
        {
            int random_thread = (int)
                    ((run_me_only_list.GetSize (false) * (double) rand ()) / (RAND_MAX + 1.0));
            thread_to_run = run_me_only_list.GetThreadAtIndex (random_thread);
        }

        for (pos = m_threads.begin(); pos != end; ++pos)
        {
            ThreadSP thread_sp(*pos);
            if (thread_sp == thread_to_run)
                thread_sp->WillResume(thread_sp->GetCurrentPlan()->RunState());
            else
                thread_sp->WillResume (eStateSuspended);
        }
    }

    return success;
}

void
ThreadList::DidResume ()
{
    collection::iterator pos, end = m_threads.end();
    for (pos = m_threads.begin(); pos != end; ++pos)
    {
        // Don't clear out threads that aren't going to get a chance to run, rather
        // leave their state for the next time around.
        ThreadSP thread_sp(*pos);
        if (thread_sp->GetResumeState() != eStateSuspended)
            thread_sp->DidResume ();
    }
}

ThreadSP
ThreadList::GetCurrentThread ()
{
    Mutex::Locker locker(m_threads_mutex);
    return FindThreadByID(m_current_tid);
}

bool
ThreadList::SetCurrentThreadByID (lldb::tid_t tid)
{
    Mutex::Locker locker(m_threads_mutex);
    if  (FindThreadByID(tid).get())
        m_current_tid = tid;
    else
        m_current_tid = LLDB_INVALID_THREAD_ID;

    return m_current_tid != LLDB_INVALID_THREAD_ID;
}

bool
ThreadList::SetCurrentThreadByIndexID (uint32_t index_id)
{
    Mutex::Locker locker(m_threads_mutex);
    ThreadSP thread_sp (FindThreadByIndexID(index_id));
    if  (thread_sp.get())
        m_current_tid = thread_sp->GetID();
    else
        m_current_tid = LLDB_INVALID_THREAD_ID;

    return m_current_tid != LLDB_INVALID_THREAD_ID;
}

<|endoftext|>


<commit_before>/**
 * 	Loop.cpp
 *
 * 	Implementation of the event loop
 *
 * 	@copyright 2014 Copernica BV
 */

/**
 *  Dependencies
 */
#include <iostream>
#include "loop.h"
#include "timeoutwatcher.h"
#include "intervalwatcher.h"
#include "readwatcher.h"
#include "writewatcher.h"
#include "synchronizewatcher.h"

/**
 * Set up namespace
 */
namespace ReactPhp {

/**
 * Function which is called the moment a file descriptor becomes readable
 * @param	fd		The file descriptor
 * @param	callback	Function that is called when the file descriptor is readable
 * @return	object		ReadWatcher object that can be used for cancelling the timer
 */
Php::Value Loop::onReadable(Php::Parameters &parameters)
{
	// the filedescriptor and the callback function
	int fd = parameters[0];
	Php::Value callback = parameters[1];

	//call the Loop::onReadable function
	auto reader = _loop.onReadable(fd, [callback]() {

		//call the PHP callback
		callback();
	});

	// create a new PHP object, and return that
	return Php::Object("Async\\ReadWatcher", new ReadWatcher(reader));
}

/**
 * Function which is called the moment a file descriptor becomes writable
 * @param	fd		The file descriptor
 * @param	callback	Function that is called when the file descriptor is readable
 * @return	object		WriteWatcher object that can be used for cancelling the timer
 */
Php::Value Loop::onWritable(Php::Parameters &parameters)
{
	// the filedescriptor and the callback function
	int fd = parameters[0];
	Php::Value callback = parameters[1];

	//call the Loop::onReadable function
	auto writer = _loop.onWritable(fd, [callback]() {

		//call the PHP callback
		callback();
	});

	// create a new PHP object, and return that
	return Php::Object("Async\\WriteWatcher", new WriteWatcher(writer));
}

/**
 * Register a synchronize function
 * @param	callback	Function that is called when the file descriptor is readable
 * @return	object		SynchronizeWatcher object that can be used for cancelling the timer
 */
Php::Value Loop::onSynchronize(Php::Parameters &parameters)
{
	// the callback function
	Php::Value callback = parameters[0];

	//call the Loop::onReadable function
	auto synchronizer = _loop.onSynchronize([callback]() {

		//call the PHP callback
		callback();
	});

	// create a new PHP object, and return that
	return Php::Object("Async\\SynchronizeWatcher", new SynchronizeWatcher(synchronizer));
}

/**
 *  Run a timeout after a while
 *  @param	timeout		Number of seconds (as a float) to wait for the timer to be called
 *  @param	callback	Function that is called when timer expires
 *  @return	object		TimeoutWatcher object that can be used for cancelling the timer
 */
Php::Value Loop::onTimeout(Php::Parameters &parameters)
{
	// the timeout, and the callback function
	React::Timestamp timeout = parameters[0];
	Php::Value callback = parameters[1];

	// call the Loop::onTimeout function
	auto timer = _loop.onTimeout(timeout, [callback]() {

		// call the PHP callback
		callback();
	});

	// create a new PHP object, and return that
	return Php::Object("Async\\TimeoutWatcher", new TimeoutWatcher(timer));
}

/**
 *  Call a callback with a certain interval
 *  @param	interval	Number of seconds for each iteration
 *  @param	callback	Function that is called every timeout seconds
 *  @return	object		IntervalWatcher object that can be used for cancelling the timer
 */
Php::Value Loop::onInterval(Php::Parameters &parameters)
{
	// the interval, and the callback function
	React::Timestamp interval = parameters[0];
	Php::Value callback = parameters[1];

	// call the Loop::onInterval function
	auto watcher = _loop.onInterval(interval, interval, [callback]() {

		// call the PHP callback
		callback();
	});

	// create a new PHP object, and return that
	return Php::Object("Async\\IntervalWatcher", new IntervalWatcher(watcher));
}

/**
 *  End of namespace
 */
}

<commit_msg>Event Loop implementation<commit_after>/**
 *  Loop.cpp
 *
 *  Implementation of the event loop
 *
 *  @copyright 2014 Copernica BV
 */

/**
 *  Dependencies
 */
#include <iostream>
#include "loop.h"
#include "timeoutwatcher.h"
#include "intervalwatcher.h"
#include "readwatcher.h"
#include "writewatcher.h"
#include "synchronizewatcher.h"

/**
 *  Set up namespace
 */
namespace ReactPhp {

/**
 * Function which is called the moment a file descriptor becomes readable
 * @param	fd		The file descriptor
 * @param	callback	Function that is called when the file descriptor is readable
 * @return	object		ReadWatcher object that can be used for cancelling the timer
 */
Php::Value Loop::onReadable(Php::Parameters &parameters)
{
	// the filedescriptor and the callback function
	int fd = parameters[0];
	Php::Value callback = parameters[1];

	//call the Loop::onReadable function
	auto reader = _loop.onReadable(fd, [callback]() {

		//call the PHP callback
		callback();
	});

	// create a new PHP object, and return that
	return Php::Object("Async\\ReadWatcher", new ReadWatcher(reader));
}

/**
 * Function which is called the moment a file descriptor becomes writable
 * @param	fd		The file descriptor
 * @param	callback	Function that is called when the file descriptor is readable
 * @return	object		WriteWatcher object that can be used for cancelling the timer
 */
Php::Value Loop::onWritable(Php::Parameters &parameters)
{
	// the filedescriptor and the callback function
	int fd = parameters[0];
	Php::Value callback = parameters[1];

	//call the Loop::onReadable function
	auto writer = _loop.onWritable(fd, [callback]() {

		//call the PHP callback
		callback();
	});

	// create a new PHP object, and return that
	return Php::Object("Async\\WriteWatcher", new WriteWatcher(writer));
}

/**
 *  Register a synchronize function
 *  @param	callback	Function that is called when the file descriptor is readable
 *  @return	object		SynchronizeWatcher object that can be used for cancelling the timer
 */
Php::Value Loop::onSynchronize(Php::Parameters &parameters)
{
	// the callback function
	Php::Value callback = parameters[0];

	//call the Loop::onReadable function
	auto synchronizer = _loop.onSynchronize([callback]() {

		//call the PHP callback
		callback();
	});

	// create a new PHP object, and return that
	return Php::Object("Async\\SynchronizeWatcher", new SynchronizeWatcher(synchronizer));
}

/**
 *  Run a timeout after a while
 *  @param	timeout		Number of seconds (as a float) to wait for the timer to be called
 *  @param	callback	Function that is called when timer expires
 *  @return	object		TimeoutWatcher object that can be used for cancelling the timer
 */
Php::Value Loop::onTimeout(Php::Parameters &parameters)
{
	// the timeout, and the callback function
	React::Timestamp timeout = parameters[0];
	Php::Value callback = parameters[1];

	// call the Loop::onTimeout function
	auto timer = _loop.onTimeout(timeout, [callback]() {

		// call the PHP callback
		callback();
	});

	// create a new PHP object, and return that
	return Php::Object("Async\\TimeoutWatcher", new TimeoutWatcher(timer));
}

/**
 *  Call a callback with a certain interval
 *  @param	interval	Number of seconds for each iteration
 *  @param	callback	Function that is called every timeout seconds
 *  @return	object		IntervalWatcher object that can be used for cancelling the timer
 */
Php::Value Loop::onInterval(Php::Parameters &parameters)
{
	// the interval, and the callback function
	React::Timestamp interval = parameters[0];
	Php::Value callback = parameters[1];

	// call the Loop::onInterval function
	auto watcher = _loop.onInterval(interval, interval, [callback]() {

		// call the PHP callback
		callback();
	});

	// create a new PHP object, and return that
	return Php::Object("Async\\IntervalWatcher", new IntervalWatcher(watcher));
}

/**
 *  End of namespace
 */
}

<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: message.C,v 1.23 2004/09/14 13:43:15 amoll Exp $

#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/COMMON/rtti.h>

using namespace std;

namespace BALL
{
	namespace VIEW
	{

Message::Message()
	throw()
	: connection_object_(0),
		deletable_(true)
{
}

Message::Message(const Message& message)
	throw()
	: connection_object_(message.connection_object_),
		deletable_(message.deletable_)
{
}

Message::~Message()
	throw()
{
}

CompositeMessage::CompositeMessage()
	throw()
	: Message(),
		type_(UNDEFINED),
		composite_(0),
		composite_name_(),
		update_representations_(true)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new CompositeMessage " << type_ << std::endl;
	#endif
}

CompositeMessage::CompositeMessage(const Composite& composite, CompositeMessageType type, bool update_representations)
	throw()
	: Message(),
		type_(type),
		composite_((Composite*)&composite),
		composite_name_(),
		update_representations_(update_representations)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new CompositeMessage " << type_ << std::endl;
	#endif
}

CompositeMessage::CompositeMessage(const CompositeMessage& message)
	throw()
	: Message(message),
		type_(message.type_),
		composite_(message.composite_),
		composite_name_(message.composite_name_),
		update_representations_(message.update_representations_)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new CompositeMessage " << type_ << std::endl;
	#endif
}

CompositeMessage::~CompositeMessage()
	throw()
{
}

SceneMessage::SceneMessage(SceneMessageType type)
	throw()
	: Message(),
		type_(type),
		stage_()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new SceneMessage" << std::endl;
	#endif
}

SceneMessage::SceneMessage(const SceneMessage& message)
	throw()
	: Message(message),
		type_(message.type_),
		stage_(message.stage_)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new SceneMessage" << type_ << std::endl;
	#endif
}

SceneMessage::~SceneMessage()
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "Destructing object " << (void *)this
								<< " of class " << RTTI::getName<SceneMessage>() << endl;
	#endif
}

void SceneMessage::setType(SceneMessageType type)
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "SceneMessage::setType " << type << std::endl;
	#endif

	type_ = type;
}

GenericSelectionMessage::GenericSelectionMessage()
	throw()
	: Message(),
		selection_()
{
}

GenericSelectionMessage::GenericSelectionMessage(const GenericSelectionMessage& message)
	throw()
	: Message(message),
		selection_(message.selection_)
{
}

GenericSelectionMessage::~GenericSelectionMessage()
	throw()
{
}

GeometricObjectSelectionMessage::GeometricObjectSelectionMessage()
	throw()
	: Message()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new GeometricObjectSelectionMessage" << std::endl;
	#endif
}

GeometricObjectSelectionMessage::~GeometricObjectSelectionMessage()
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "Destructing object " << (void *)this
								<< " of class " << RTTI::getName<GeometricObjectSelectionMessage>() << endl;
	#endif
}

ControlSelectionMessage::ControlSelectionMessage()
	throw()
	: GenericSelectionMessage()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new ControlSelectionMessage" << std::endl;
	#endif
}

NewSelectionMessage::NewSelectionMessage()
	throw()
	: Message(),
		open_(false)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new NewSelectionMessage" << std::endl;
	#endif
}

RepresentationMessage::RepresentationMessage()
	throw()
	: representation_(0),
		type_(UNDEFINED)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new RepresentationMessage" << std::endl;
	#endif
}

RepresentationMessage::RepresentationMessage(Representation& rep, RepresentationMessageType type)
	throw()
	: representation_(&rep),
		type_(type)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new RepresentationMessage" << std::endl;
	#endif
}

void RepresentationMessage::setType(RepresentationMessageType type)
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "RepresentationMessage::setType " << type << std::endl;
	#endif

	type_ = type;
}

MolecularTaskMessage::MolecularTaskMessage(MolecularTaskMessageType type)
	throw()
	: type_(type)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new MolecularTaskMessage" << std::endl;
	#endif
}

void MolecularTaskMessage::setType(MolecularTaskMessageType type)
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "MolecularTaskMessage::setType " << type << std::endl;
	#endif

	type_ = type;
}

NewTrajectoryMessage::NewTrajectoryMessage()
	throw()
	: CompositeMessage(),
		file_(0)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new NewTrajectoryMessage" << std::endl;
	#endif
}

// ================ Regular Data Messages ===========================
RegularDataMessage::RegularDataMessage()
	throw()
	: CompositeMessage()
{
	setType((CompositeMessageType)UNDEFINED);
}

RegularData1DMessage::RegularData1DMessage(RegularDataMessageType type)
	throw()
	: RegularDataMessage(),
		data_(0)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new RegularData1DMessage" << std::endl;
	#endif
	setType((CompositeMessageType)type);
}

RegularData2DMessage::RegularData2DMessage(RegularDataMessageType type)
	throw()
	: RegularDataMessage(),
		data_(0)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new RegularData2DMessage" << std::endl;
	#endif
	setType((CompositeMessageType)type);
}

RegularData3DMessage::RegularData3DMessage(RegularDataMessageType type)
	throw()
	: RegularDataMessage(),
		data_(0)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new RegularData3DMessage" << std::endl;
	#endif
	setType((CompositeMessageType)type);
}

CreateRepresentationMessage::CreateRepresentationMessage()
	throw()
	: Message(),
		composites_(),
		model_type_(MODEL_UNKNOWN),
		coloring_method_(COLORING_UNKNOWN)
{
}

CreateRepresentationMessage::CreateRepresentationMessage(const List<Composite*>& composites,
		ModelType model_type, ColoringMethod coloring_method)
 	throw()
	: Message(),
		composites_(composites),
		model_type_(model_type),
		coloring_method_(coloring_method)
{
}

TransformationMessage::TransformationMessage()
	throw()
	: Message(),
		matrix_()
{
}

TransformationMessage::TransformationMessage(const Matrix4x4& m)
	throw()
	: Message(),
		matrix_(m)
{
}

#	ifdef BALL_NO_INLINE_FUNCTIONS
#		include <BALL/VIEW/KERNEL/message.iC>
#	endif

} } // namespaces
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: message.C,v 1.24 2004/11/13 10:09:12 amoll Exp $

#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/COMMON/rtti.h>

using namespace std;

// #define BALL_VIEW_DEBUG

namespace BALL
{
	namespace VIEW
	{

Message::Message()
	throw()
	: connection_object_(0),
		deletable_(true)
{
}

Message::Message(const Message& message)
	throw()
	: connection_object_(message.connection_object_),
		deletable_(message.deletable_)
{
}

Message::~Message()
	throw()
{
}

CompositeMessage::CompositeMessage()
	throw()
	: Message(),
		type_(UNDEFINED),
		composite_(0),
		composite_name_(),
		update_representations_(true)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new CompositeMessage " << type_ << std::endl;
	#endif
}

CompositeMessage::CompositeMessage(const Composite& composite, CompositeMessageType type, bool update_representations)
	throw()
	: Message(),
		type_(type),
		composite_((Composite*)&composite),
		composite_name_(),
		update_representations_(update_representations)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new CompositeMessage " << type_ << std::endl;
	#endif
}

CompositeMessage::CompositeMessage(const CompositeMessage& message)
	throw()
	: Message(message),
		type_(message.type_),
		composite_(message.composite_),
		composite_name_(message.composite_name_),
		update_representations_(message.update_representations_)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new CompositeMessage " << type_ << std::endl;
	#endif
}

CompositeMessage::~CompositeMessage()
	throw()
{
}

SceneMessage::SceneMessage(SceneMessageType type)
	throw()
	: Message(),
		type_(type),
		stage_()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new SceneMessage" << std::endl;
	#endif
}

SceneMessage::SceneMessage(const SceneMessage& message)
	throw()
	: Message(message),
		type_(message.type_),
		stage_(message.stage_)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new SceneMessage" << type_ << std::endl;
	#endif
}

SceneMessage::~SceneMessage()
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "Destructing object " << (void *)this
								<< " of class " << RTTI::getName<SceneMessage>() << endl;
	#endif
}

void SceneMessage::setType(SceneMessageType type)
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "SceneMessage::setType " << type << std::endl;
	#endif

	type_ = type;
}

GenericSelectionMessage::GenericSelectionMessage()
	throw()
	: Message(),
		selection_()
{
}

GenericSelectionMessage::GenericSelectionMessage(const GenericSelectionMessage& message)
	throw()
	: Message(message),
		selection_(message.selection_)
{
}

GenericSelectionMessage::~GenericSelectionMessage()
	throw()
{
}

GeometricObjectSelectionMessage::GeometricObjectSelectionMessage()
	throw()
	: Message()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new GeometricObjectSelectionMessage" << std::endl;
	#endif
}

GeometricObjectSelectionMessage::~GeometricObjectSelectionMessage()
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "Destructing object " << (void *)this
								<< " of class " << RTTI::getName<GeometricObjectSelectionMessage>() << endl;
	#endif
}

ControlSelectionMessage::ControlSelectionMessage()
	throw()
	: GenericSelectionMessage()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new ControlSelectionMessage" << std::endl;
	#endif
}

NewSelectionMessage::NewSelectionMessage()
	throw()
	: Message(),
		open_(false)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new NewSelectionMessage" << std::endl;
	#endif
}

RepresentationMessage::RepresentationMessage()
	throw()
	: representation_(0),
		type_(UNDEFINED)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new RepresentationMessage" << std::endl;
	#endif
}

RepresentationMessage::RepresentationMessage(Representation& rep, RepresentationMessageType type)
	throw()
	: representation_(&rep),
		type_(type)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new RepresentationMessage" << std::endl;
	#endif
}

void RepresentationMessage::setType(RepresentationMessageType type)
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "RepresentationMessage::setType " << type << std::endl;
	#endif

	type_ = type;
}

MolecularTaskMessage::MolecularTaskMessage(MolecularTaskMessageType type)
	throw()
	: type_(type)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new MolecularTaskMessage" << std::endl;
	#endif
}

void MolecularTaskMessage::setType(MolecularTaskMessageType type)
	throw()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "MolecularTaskMessage::setType " << type << std::endl;
	#endif

	type_ = type;
}

NewTrajectoryMessage::NewTrajectoryMessage()
	throw()
	: CompositeMessage(),
		file_(0)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new NewTrajectoryMessage" << std::endl;
	#endif
}

// ================ Regular Data Messages ===========================
RegularDataMessage::RegularDataMessage()
	throw()
	: CompositeMessage()
{
	setType((CompositeMessageType)UNDEFINED);
}

RegularData1DMessage::RegularData1DMessage(RegularDataMessageType type)
	throw()
	: RegularDataMessage(),
		data_(0)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new RegularData1DMessage" << std::endl;
	#endif
	setType((CompositeMessageType)type);
}

RegularData2DMessage::RegularData2DMessage(RegularDataMessageType type)
	throw()
	: RegularDataMessage(),
		data_(0)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new RegularData2DMessage" << std::endl;
	#endif
	setType((CompositeMessageType)type);
}

RegularData3DMessage::RegularData3DMessage(RegularDataMessageType type)
	throw()
	: RegularDataMessage(),
		data_(0)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new RegularData3DMessage" << std::endl;
	#endif
	setType((CompositeMessageType)type);
}

CreateRepresentationMessage::CreateRepresentationMessage()
	throw()
	: Message(),
		composites_(),
		model_type_(MODEL_UNKNOWN),
		coloring_method_(COLORING_UNKNOWN)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new CreateRepresentationMessage" << std::endl;
	#endif
}

CreateRepresentationMessage::CreateRepresentationMessage(const List<Composite*>& composites,
		ModelType model_type, ColoringMethod coloring_method)
 	throw()
	: Message(),
		composites_(composites),
		model_type_(model_type),
		coloring_method_(coloring_method)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new CreateRepresentationMessage" << std::endl;
	#endif
}

TransformationMessage::TransformationMessage()
	throw()
	: Message(),
		matrix_()
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new TransformationMessage" << std::endl;
	#endif
}

TransformationMessage::TransformationMessage(const Matrix4x4& m)
	throw()
	: Message(),
		matrix_(m)
{
	#ifdef BALL_VIEW_DEBUG
		Log.error() << "new TransformationMessage" << std::endl;
	#endif
}

#	ifdef BALL_NO_INLINE_FUNCTIONS
#		include <BALL/VIEW/KERNEL/message.iC>
#	endif

} } // namespaces
<|endoftext|>