/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2006,2007 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "ns3/core-module.h"
#include "ns3/mobility-module.h"
using namespace ns3;
/**
* Function called when there is a course change
* \param context event context
* \param position a pointer to the mobility model
*/
static void CourseChange(std::string context,
Ptr<const MobilityModel> position) {
Vector pos = position->GetPosition();
std::cout << "context:" << context << " ,time:" << Simulator::Now()
<< ", pos=" << position << ", x=" << pos.x << ", y=" << pos.y
<< ", z=" << pos.z << std::endl;
}
int main(int argc, char *argv[]) {
CommandLine cmd(__FILE__);
cmd.Parse(argc, argv);
NodeContainer c;
c.Create(100);
MobilityHelper mobility;
/*
* ns-3: ns3::RandomDiscPositionAllocator Class Reference
* https://www.nsnam.org/docs/release/3.35/doxygen/classns3_1_1_random_disc_position_allocator.html
* Rho:极坐标极径
* UniformRandomVariable:均匀分布随机数生成器
* 个人理解,是以X和Y为坐标原点,以该原点为圆心,以Rho(随机数)为半径的圆内随机生成节点。
*/
mobility.SetPositionAllocator("ns3::RandomDiscPositionAllocator", "X",
StringValue("100.0"), "Y", StringValue("100.0"), "Rho",
StringValue("ns3::UniformRandomVariable[Min=90|Max=100]"));
// mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
//2D随即游走模型
mobility.SetMobilityModel("ns3::RandomWalk2dMobilityModel", "Bounds",
RectangleValue(Rectangle(-5000, 5000, -5000, 5000)));
mobility.Install(c);
Config::Connect("/NodeList/*/$ns3::MobilityModel/CourseChange",
MakeCallback(&CourseChange));
Simulator::Stop(Seconds(100.0));
Simulator::Run();
Simulator::Destroy();
return 0;
}
源码出处:NS-3 3.35 源码包中的src/mobility/examples/main-random-topology.cc
个人按照标题理解该示例应该是想建立一个随机的拓扑图,如果目的是这个,那该例子无可厚非,做到了。但是,例子中有一段代码:
Config::Connect("/NodeList/*/$ns3::MobilityModel/CourseChange", MakeCallback(&CourseChange));
该代码应该是在节点位置或者运动速度发生变化时回调函数CourseChange 被调用
(参考:
(50条消息) NS-3学习笔记 5_hhhparty的博客-优快云博客
https://blog.youkuaiyun.com/hhhparty/article/details/78189789
)
但是,移动模型设置为mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");静态的,也就是说节点位置是固定的。所以,--vis 运行启动该例子后,发现根本没有触发CourseChange 函数。尝试将移动模型修改为2D 游走模型后,触发了CourseChange函数,同时可以从控制台输出看到每个节点的位置变化情况。
运行效果如图:
图中是随机生成的点,因为点的范围是从以(100,100)为圆心,以90到100为随机半径的圆环上生成,所以是这样的。点击开始仿真按钮Simulate(F3),图中的点是可以随机移动的。