Exemple #1
0
/** Load (create) all objects from RDF into the engine.
 *
 * @param uri URI of machine (resolvable URI to an RDF document).
 * @return Loaded Machine.
 */
SPtr<Machine>
Loader::load(const Glib::ustring& uri)
{
	using Glib::ustring;

	ustring document_uri = uri;

	// If "URI" doesn't contain a colon, try to resolve as a filename
	if (uri.find(":") == ustring::npos) {
		document_uri = "file://" + document_uri;
	}

	cout << "Loading " << document_uri << endl;

	TimeUnit beats(TimeUnit::BEATS, MACHINA_PPQN);

	SPtr<Machine> machine(new Machine(beats));

	typedef std::map<Sord::Node, SPtr<Node> > Created;
	Created created;

	Sord::URI   base_uri(_rdf_world, document_uri);
	Sord::Model model(_rdf_world, document_uri);

	SerdEnv* env = serd_env_new(base_uri.to_serd_node());
	model.load_file(env, SERD_TURTLE, document_uri);
	serd_env_free(env);

	Sord::Node nil;

	Sord::URI machina_SelectorNode(_rdf_world, MACHINA_NS_SelectorNode);
	Sord::URI machina_duration(_rdf_world, MACHINA_NS_duration);
	Sord::URI machina_edge(_rdf_world, MACHINA_NS_arc);
	Sord::URI machina_head(_rdf_world, MACHINA_NS_head);
	Sord::URI machina_node(_rdf_world, MACHINA_NS_node);
	Sord::URI machina_onEnter(_rdf_world, MACHINA_NS_onEnter);
	Sord::URI machina_onExit(_rdf_world, MACHINA_NS_onExit);
	Sord::URI machina_probability(_rdf_world, MACHINA_NS_probability);
	Sord::URI machina_start(_rdf_world, MACHINA_NS_start);
	Sord::URI machina_tail(_rdf_world, MACHINA_NS_tail);
	Sord::URI rdf_type(_rdf_world, MACHINA_URI_RDF "type");

	Sord::Node subject = base_uri;

	// Get start node ID (but re-use existing start node)
	Sord::Iter i = model.find(subject, machina_start, nil);
	if (i.end()) {
		cerr << "error: Machine has no start node" << std::endl;
	}
	created[i.get_object()] = machine->initial_node();

	// Get remaining nodes
	for (Sord::Iter i = model.find(subject, machina_node, nil); !i.end(); ++i) {
		const Sord::Node& id = i.get_object();
		if (created.find(id) != created.end()) {
			cerr << "warning: Machine lists the same node twice" << std::endl;
			continue;
		}

		// Create node
		Sord::Iter d = model.find(id, machina_duration, nil);
		SPtr<Node> node(new Node(TimeStamp(beats, d.get_object().to_float())));
		machine->add_node(node);
		created[id] = node;

		node->set_enter_action(
			load_action(model, model.get(id, machina_onEnter, nil)));
		node->set_exit_action(
			load_action(model, model.get(id, machina_onExit, nil)));
	}

	// Get arcs
	for (Sord::Iter i = model.find(subject, machina_edge, nil); !i.end(); ++i) {
		Sord::Node edge = i.get_object();
		Sord::Iter t    = model.find(edge, machina_tail, nil);
		Sord::Iter h    = model.find(edge, machina_head, nil);
		Sord::Iter p    = model.find(edge, machina_probability, nil);

		Sord::Node tail        = t.get_object();
		Sord::Node head        = h.get_object();
		Sord::Node probability = p.get_object();

		float prob = probability.to_float();

		Created::iterator tail_i = created.find(tail);
		Created::iterator head_i = created.find(head);

		if (tail_i != created.end() && head_i != created.end()) {
			const SPtr<Node> tail = tail_i->second;
			const SPtr<Node> head = head_i->second;
			tail->add_edge(SPtr<Edge>(new Edge(tail, head, prob)));
		} else {
			cerr << "warning: Ignored edge between unknown nodes "
			     << tail << " -> " << head << endl;
		}
	}

	if (machine && !machine->nodes().empty()) {
		machine->reset(NULL, machine->time());
		return machine;
	} else {
		return SPtr<Machine>();
	}
}
void StateManager::buildStateChange(unsigned int &list, SPtr<StateProperties> previous_state, SPtr<StateProperties> next_state) {
  assert(m_initialised);
  assert (previous_state.isValid());
  assert (next_state.isValid());
  glNewList(list, GL_COMPILE);
  if (previous_state->alpha_test != next_state->alpha_test) {
    if (next_state->alpha_test) glEnable(GL_ALPHA_TEST);
    else glDisable(GL_ALPHA_TEST);
  }
  if (previous_state->blend != next_state->blend) {
    if (next_state->blend) glEnable(GL_BLEND);
    else glDisable(GL_BLEND);
  }
  if (previous_state->lighting != next_state->lighting) {
//    if (next_state->lighting && checkState(RENDER_LIGHTING)) glEnable(GL_LIGHTING);
    if (next_state->lighting) glEnable(GL_LIGHTING);
    else glDisable(GL_LIGHTING);
  }
  if (previous_state->two_sided_lighting != next_state->two_sided_lighting) {
//    if (next_state->lighting && checkState(RENDER_LIGHTING)) glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
    if (next_state->lighting) glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
    else glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
  }
 
  for (int i = MAX_UNITS - 1; i >= 0; --i) {
    glActiveTextureARB(GL_TEXTURE0_ARB + i);
    if (previous_state->textures[i] != next_state->textures[i]) {
//      if (next_state->textures && checkState(RENDER_TEXTURES)) glEnable(GL_TEXTURE_2D);
      if (next_state->textures[i]) glEnable(GL_TEXTURE_2D);
      else glDisable(GL_TEXTURE_2D);
    }
  }
  if (previous_state->colour_material != next_state->colour_material) {
    if (next_state->colour_material) glEnable(GL_COLOR_MATERIAL);
    else glDisable(GL_COLOR_MATERIAL);
  }
  if (previous_state->depth_test != next_state->depth_test) {
    if (next_state->depth_test) glEnable(GL_DEPTH_TEST);
    else glDisable(GL_DEPTH_TEST);
  }
  
  if (previous_state->depth_write != next_state->depth_write) {
    glDepthMask(next_state->depth_write);
  }
  
  if (previous_state->cull_face != next_state->cull_face) {
    if (next_state->cull_face) glEnable(GL_CULL_FACE);
    else glDisable(GL_CULL_FACE);
  }
  if (previous_state->cull_face_cw != next_state->cull_face_cw) {
    if (next_state->cull_face_cw) glFrontFace(GL_CW);
    else glFrontFace(GL_CCW);
  }
  if (previous_state->stencil != next_state->stencil) {
    if (next_state->stencil) glEnable(GL_STENCIL_TEST);
    else glDisable(GL_STENCIL_TEST);
  }
  if (previous_state->fog != next_state->fog) {
    if (next_state->fog) glEnable(GL_FOG);
    else glDisable(GL_FOG);
  }
  if (previous_state->rescale_normals != next_state->rescale_normals) {
    if (next_state->rescale_normals) glEnable(GL_RESCALE_NORMAL);
    else glDisable(GL_RESCALE_NORMAL);
  }
  if (previous_state->normalise != next_state->normalise) {
    if (next_state->normalise) glEnable(GL_NORMALIZE);
    else glDisable(GL_NORMALIZE);
  }
//  if ((next_state->alpha_function != previous_state->alpha_function) || (next_state->alpha_value != previous_state->alpha_value)) 
  glAlphaFunc(next_state->alpha_function, next_state->alpha_value);
  glBlendFunc(next_state->blend_src_function, next_state->blend_dest_function);
  glEndList();
}
Exemple #3
0
/**
 * match parsed interfaces with interfaces detected in system.
 * ClntCfgIface objects copied to CfgMgr.
 *
 * @param parser
 *
 * @return true if ok, false if interface definitions are incorrect
 */
bool TClntCfgMgr::matchParsedSystemInterfaces(ClntParser *parser) {
    int cfgIfaceCnt;

    cfgIfaceCnt = parser->ClntCfgIfaceLst.count();
    Log(Debug) << cfgIfaceCnt << " interface(s) specified in " << CLNTCONF_FILE << LogEnd;

    SPtr<TClntCfgIface> cfgIface;
    SPtr<TIfaceIface> ifaceIface;

    if (cfgIfaceCnt) {
        // user specified some interfaces in config file
        parser->ClntCfgIfaceLst.first();
        while(cfgIface = parser->ClntCfgIfaceLst.get()) {
            // for each interface (from config file)
            if (cfgIface->getID()==-1) {
                ifaceIface = ClntIfaceMgr().getIfaceByName(cfgIface->getName());
            } else {
                ifaceIface = ClntIfaceMgr().getIfaceByID(cfgIface->getID());
            }

            if (!ifaceIface) {
                if (inactiveMode()) {
                    Log(Info) << "Interface " << cfgIface->getFullName()
                              << " is not currently available (that's ok, inactive-mode enabled)." << LogEnd;
                    continue;
                }
                Log(Error) << "Interface " << cfgIface->getFullName()
                           << " specified in " << CLNTCONF_FILE << " is not present or does not support IPv6."
                           << LogEnd;
                return false;
            }
            if (cfgIface->noConfig()) {
                Log(Info) << "Interface " << cfgIface->getFullName()
                          << " has flag no-config set, so it is ignored." << LogEnd;
                continue;
            }

#ifdef MOD_REMOTE_AUTOCONF
            if (RemoteAutoconf) {
                List(TIPv6Addr) emptyLst;
                SPtr<TOpt> optNeighbors = new TOptAddrLst(OPTION_NEIGHBORS, emptyLst, 0);
                Log(Debug) << "Enabled Neighbors option on " << cfgIface->getFullName() << LogEnd;
                cfgIface->addExtraOption(optNeighbors, false);
            }
#endif

            cfgIface->setIfaceName(ifaceIface->getName());
            cfgIface->setIfaceID(ifaceIface->getID());

            // setup default prefix length (used when IPv6 address is added to the interface)
            ifaceIface->setPrefixLength(cfgIface->getOnLinkPrefixLength());

            if (!ifaceIface->flagUp() || !ifaceIface->countLLAddress()) {
                if (inactiveMode()) {
                    Log(Notice) << "Interface " << ifaceIface->getFullName()
                                << " is not operational yet (does not have "
                                << "link-local address or is down), skipping it for now." << LogEnd;
                    addIface(cfgIface);
                    makeInactiveIface(cfgIface->getID(), true, true, true); // move it to InactiveLst
                    continue;
                }

                Log(Crit) << "Interface " << ifaceIface->getFullName()
                          << " is down or doesn't have any link-local address." << LogEnd;
                return false;
            }

            // Check if the interface is during bring-up phase
            // (i.e. DAD procedure for link-local addr is not complete yet)
            char tmp[64];
            if (cfgIface->getBindToAddr()) {
                inet_ntop6(cfgIface->getBindToAddr()->getPlain(), tmp);
            } else {
                ifaceIface->firstLLAddress();
                inet_ntop6(ifaceIface->getLLAddress(), tmp);
            }

            if (is_addr_tentative(ifaceIface->getName(), ifaceIface->getID(), tmp)
                == LOWLEVEL_TENTATIVE_YES) {
                Log(Notice) << "Interface " << ifaceIface->getFullName()
                            << " has link-local address " << tmp
                            << ", but it is currently tentative." << LogEnd;

                if (this->inactiveMode()) {
                    Log(Notice) << "Interface " << ifaceIface->getFullName()
                                << " is not operational yet (link-local address "
                                << "is not ready), skipping it for now." << LogEnd;
                    addIface(cfgIface);
                    makeInactiveIface(cfgIface->getID(), true, true, true); // move it to InactiveLst
                    continue;
                }

                Log(Crit) << "Interface " << ifaceIface->getFullName()
                          << " has tentative link-local address (and inactive-mode is disabled)." << LogEnd;
                return false;
            }

            if (obeyRaBits()) {
                if (!ifaceIface->getMBit() && !ifaceIface->getOBit()) {
                    Log(Info) << "Interface " << cfgIface->getFullName()
                              << " configuration loaded, but did not receive a Router "
                              << "Advertisement with M or O bits set, adding to inactive."
                              << LogEnd;
                    addIface(cfgIface);
                    makeInactiveIface(cfgIface->getID(), true, true, true); // move it to inactive list
                    continue;
                }
                cfgIface->setMbit(ifaceIface->getMBit());
                cfgIface->setObit(ifaceIface->getOBit());
            }

            addIface(cfgIface);
            Log(Info) << "Interface " << cfgIface->getFullName()
                      << " configuration has been loaded." << LogEnd;
        }
        return countIfaces() || (inactiveMode() && inactiveIfacesCnt());
    } else {
        // user didn't specified any interfaces in config file, so
        // we'll try to configure each interface we could find
        Log(Warning) << "Config file does not contain any interface definitions. Trying to autodetect."
                     << LogEnd;

        List(TIPv6Addr) dnsList;
        dnsList.clear();
        parser->ParserOptStack.getLast()->setDNSServerLst(&dnsList);

        // Try to add a hostname
        char hostname[255];
        if (get_hostname(hostname, 255) == LOWLEVEL_NO_ERROR) {
            parser->ParserOptStack.getLast()->setFQDN(string(hostname));
	    } else {
            parser->ParserOptStack.getLast()->setFQDN(string(""));
        }

        int cnt = 0;
        ClntIfaceMgr().firstIface();
        while ( ifaceIface = ClntIfaceMgr().getIface() ) {
            // for each interface present in the system...
            if (!inactiveMode()) {
                if (!ifaceIface->flagUp()) {
                    Log(Notice) << "Interface " << ifaceIface->getFullName() << " is down, ignoring." << LogEnd;
                    continue;
                }
                if (!ifaceIface->flagRunning()) {
                    Log(Notice) << "Interface " << ifaceIface->getFullName()
                                << " has flag RUNNING not set, ignoring." << LogEnd;
                    continue;
                }
                if (!ifaceIface->flagMulticast()) {
                    Log(Notice) << "Interface " << ifaceIface->getFullName()
                                << " is not multicast capable, ignoring." << LogEnd;
                    continue;
                }
            }
            if ( !(ifaceIface->getMacLen() > 5) ) {
                Log(Notice) << "Interface " << ifaceIface->getFullName()
                            << " has MAC address length " << ifaceIface->getMacLen()
                            << " (6 or more required), ignoring." << LogEnd;
                continue;
            }

            // ignore disabled Teredo pseudo-interface on Win (and other similar useless junk)
            const static unsigned char zeros[] = {0,0,0,0,0,0,0,0};
            const static unsigned char ones[] = {0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff};
            if ( (ifaceIface->getMacLen()<=8) &&
                 (!memcmp(zeros, ifaceIface->getMac(), min(8,ifaceIface->getMacLen())) ||
                  !memcmp(ones, ifaceIface->getMac(), min(8,ifaceIface->getMacLen()))) ) {
                Log(Notice) << "Interface " << ifaceIface->getFullName()
                            << " has invalid MAC address "
                            << hexToText((uint8_t*)ifaceIface->getMac(), ifaceIface->getMacLen(), true)
                            << ", ignoring." << LogEnd;
                continue;
            }

            if (!ifaceIface->countLLAddress()) {
                Log(Notice) << "Interface " << ifaceIface->getFullName()
                            << " has no link-local address, ignoring. "
                            << "(Disconnected? Not associated? No-link?)" << LogEnd;
                continue;
            }

            // One address...
            SPtr<TClntCfgAddr> addr(new TClntCfgAddr());
            addr->setOptions(parser->ParserOptStack.getLast());

            // ... is stored in one IA...
            SPtr<TClntCfgIA> ia = new TClntCfgIA();
            ia->setOptions(parser->ParserOptStack.getLast());
            ia->addAddr(addr);

            // ... on this newly created interface...
            cfgIface = SPtr<TClntCfgIface>(new TClntCfgIface(ifaceIface->getID()));
            cfgIface->setIfaceName(ifaceIface->getName());
            cfgIface->setIfaceID(ifaceIface->getID());
            cfgIface->addIA(ia);
            cfgIface->setOptions(parser->ParserOptStack.getLast());

            // ... which is added to ClntCfgMgr
            addIface(cfgIface);

            Log(Info) << "Interface " << cfgIface->getFullName()
                      << " has been added." << LogEnd;

            if (inactiveMode() && !ifaceIface->flagRunning() ) {
                makeInactiveIface(cfgIface->getID(), true, true, true); // move it to InactiveLst
                Log(Notice) << "Interface " << ifaceIface->getFullName()
                            << " is not operational yet"
                            << " (not running), made inactive." << LogEnd;
            }
            cnt ++;
        }
        if (!cnt) {
            Log(Crit) << "Unable to detect any suitable interfaces. If there are any interfaces that you"
                      << " want to have configured, please specify them in client.conf file." << LogEnd;
            return false;
        }
    }
    return true;
}
	/**
	 * Attempts to cook a triangle or convex mesh from the provided mesh data. Will log a warning and return false if it is
	 * unable to cook the mesh. If the method returns true the resulting convex mesh will be output in the @p data buffer,
	 * and its size in @p size. The data buffer will be allocated used the generic allocator and is up to the caller to 
	 * free it.
	 */
	bool cookMesh(const SPtr<MeshData>& meshData, PhysicsMeshType type, UINT8** data, UINT32& size)
	{
		if (meshData == nullptr)
			return false;

		PxCooking* cooking = gPhysX().getCooking();
		if (cooking == nullptr)
		{
			LOGWRN("Attempting to cook a physics mesh but cooking is not enabled globally.");
			return false;
		}

		SPtr<VertexDataDesc> vertexDesc = meshData->getVertexDesc();
		if (!vertexDesc->hasElement(VES_POSITION))
		{
			LOGWRN("Provided PhysicsMesh mesh data has no vertex positions.");
			return false;
		}

		if (type == PhysicsMeshType::Convex)
		{
			if(!cookConvex(cooking, meshData, data, size))
			{
				LOGWRN("Failed cooking a convex mesh. Perpahs it is too complex? Maximum number of convex vertices is 256.");
				return false;
			}
		}
		else
		{
			PxTriangleMeshDesc meshDesc;
			meshDesc.points.count = meshData->getNumVertices();
			meshDesc.points.stride = vertexDesc->getVertexStride();
			meshDesc.points.data = meshData->getElementData(VES_POSITION);

			meshDesc.triangles.count = meshData->getNumIndices() / 3;
			meshDesc.flags |= PxMeshFlag::eFLIPNORMALS;

			IndexType indexType = meshData->getIndexType();
			if (indexType == IT_32BIT)
			{
				meshDesc.triangles.stride = 3 * sizeof(PxU32);
				meshDesc.triangles.data = meshData->getIndices32();
			}
			else
			{
				meshDesc.triangles.stride = 3 * sizeof(PxU16);
				meshDesc.triangles.data = meshData->getIndices16();
				meshDesc.flags |= PxMeshFlag::e16_BIT_INDICES;
			}

			PxDefaultMemoryOutputStream output;
			if (!cooking->cookTriangleMesh(meshDesc, output))
				return false;

			size = output.getSize();
			*data = (UINT8*)bs_alloc(size);

			memcpy(*data, output.getData(), size);
		}

		return true;
	}
void StateManager::varconf_callback(const std::string &section, const std::string &key, varconf::Config &config) {
  StateID sID = m_state_name_map[section];

  SPtr<StateProperties> record = SPtr<StateProperties>();
  bool create_record = false;
  if (sID > 0) {
    // Record ID already exists, lets see if the record is valid.
    record = m_states[sID];
    if (record.isValid()) {
      // Record already exists, all good
    } else {
      // Record does not exist, lets make a new one.
      create_record = true;
    }
  } else {
    // Not seen this record name yet, so need to fill in all the data structures.
    sID = m_state_counter++;
    create_record = true;
  }
  
  // If record does not exist, create it.
  if (create_record) {
      record = SPtr<StateProperties> (new StateProperties());
      record->state = section;
      // Setup default values
      record->alpha_test = false;
      record->blend = false;
      record->lighting = false;
      record->two_sided_lighting = false;
      for (unsigned int i = 0; i < MAX_UNITS; ++i)
        record->textures[i] = false;
      record->colour_material = false;
      record->depth_test = false;
      record->depth_write = true;
      record->cull_face = false;
      record->cull_face_cw = false;
      record->stencil = false;
      record->fog = false;
      record->rescale_normals = false;
      record->normalise = false;
      record->alpha_function = GL_GREATER;
      record->alpha_value = 0.1f;
      record->blend_src_function = GL_SRC_ALPHA;
      record->blend_dest_function = GL_ONE_MINUS_SRC_ALPHA;
  
      m_states[sID] = record;
      m_state_name_map[record->state] = sID;
      m_name_state_vector[sID] = record->state;

      if (debug) printf("[StateManager] Adding State: %s\n", section.c_str());
  }

  if (key == ALPHA_TEST) record->alpha_test = (bool)config.getItem(section, key);
  else if (key == BLEND) record->blend = (bool)config.getItem(section, key);
  else if (key == LIGHTING) record->lighting = (bool)config.getItem(section, key);
  else if (key == TWO_SIDED_LIGHTING) record->two_sided_lighting = (bool)config.getItem(section, key);
  else if (key == COLOUR_MATERIAL) record->colour_material = (bool)config.getItem(section, key);
  else if (key == DEPTH_TEST) record->depth_test = (bool)config.getItem(section, key);
  else if (key == DEPTH_WRITE) record->depth_write = (bool)config.getItem(section, key);
  else if (key == CULL_FACE) record->cull_face = (bool)config.getItem(section, key);
  else if (key == CULL_FACE_CW) record->cull_face_cw = (bool)config.getItem(section, key);
  else if (key == STENCIL) record->stencil = (bool)config.getItem(section, key);
  else if (key == FOG) record->fog = (bool)config.getItem(section, key);
  else if (key == RESCALE_NORMALS) record->rescale_normals = (bool)config.getItem(section, key);
  else if (key == NORMALISE) record->normalise = (bool)config.getItem(section, key);
  else if (key == ALPHA_FUNCTION) record->alpha_function = getAlphaFunction((std::string)config.getItem(section, key));
  else if (key == ALPHA_VALUE) record->alpha_value = (double)config.getItem(section, key);
  else if (key == BLEND_SRC_FUNCTION) record->blend_src_function = getBlendFunction((std::string)config.getItem(section, key));
  else if (key == BLEND_DEST_FUNCTION) record->blend_dest_function = getBlendFunction((std::string)config.getItem(section, key));
  else if (key.substr(0, TEXTURE.size()) == TEXTURE) {
    unsigned int unit;
    cast_stream(key.substr(TEXTURE.size()), unit);
    if (unit < MAX_UNITS) {
      record->textures[unit] = (bool)config.getItem(section, key);
    }
  }
}
	void VulkanTexture::copyImpl(const SPtr<Texture>& target, const TEXTURE_COPY_DESC& desc, 
			const SPtr<CommandBuffer>& commandBuffer)
	{
		VulkanTexture* other = static_cast<VulkanTexture*>(target.get());

		const TextureProperties& srcProps = mProperties;
		const TextureProperties& dstProps = other->getProperties();

		bool srcHasMultisample = srcProps.getNumSamples() > 1;
		bool destHasMultisample = dstProps.getNumSamples() > 1;

		if ((srcProps.getUsage() & TU_DEPTHSTENCIL) != 0 || (dstProps.getUsage() & TU_DEPTHSTENCIL) != 0)
		{
			LOGERR("Texture copy/resolve isn't supported for depth-stencil textures.");
			return;
		}

		bool needsResolve = srcHasMultisample && !destHasMultisample;
		bool isMSCopy = srcHasMultisample || destHasMultisample;
		if (!needsResolve && isMSCopy)
		{
			if (srcProps.getNumSamples() != dstProps.getNumSamples())
			{
				LOGERR("When copying textures their multisample counts must match. Ignoring copy.");
				return;
			}
		}

		VkImageLayout transferSrcLayout = mDirectlyMappable ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL;
		VkImageLayout transferDstLayout = other->mDirectlyMappable ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;

		UINT32 mipWidth, mipHeight, mipDepth;

		bool copyEntireSurface = desc.srcVolume.getWidth() == 0 || 
			desc.srcVolume.getHeight() == 0 || 
			desc.srcVolume.getDepth() == 0;

		if(copyEntireSurface)
		{
			PixelUtil::getSizeForMipLevel(
				srcProps.getWidth(),
				srcProps.getHeight(),
				srcProps.getDepth(),
				desc.srcMip,
				mipWidth,
				mipHeight,
				mipDepth);
		}
		else
		{
			mipWidth = desc.srcVolume.getWidth();
			mipHeight = desc.srcVolume.getHeight();
			mipDepth = desc.srcVolume.getDepth();
		}

		VkImageResolve resolveRegion;
		resolveRegion.srcOffset = { (INT32)desc.srcVolume.left, (INT32)desc.srcVolume.top, (INT32)desc.srcVolume.front };
		resolveRegion.dstOffset = { desc.dstPosition.x, desc.dstPosition.y, desc.dstPosition.z };
		resolveRegion.extent = { mipWidth, mipHeight, mipDepth };
		resolveRegion.srcSubresource.baseArrayLayer = desc.srcFace;
		resolveRegion.srcSubresource.layerCount = 1;
		resolveRegion.srcSubresource.mipLevel = desc.srcMip;
		resolveRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
		resolveRegion.dstSubresource.baseArrayLayer = desc.dstFace;
		resolveRegion.dstSubresource.layerCount = 1;
		resolveRegion.dstSubresource.mipLevel = desc.dstMip;
		resolveRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;

		VkImageCopy imageRegion;
		imageRegion.srcOffset = { (INT32)desc.srcVolume.left, (INT32)desc.srcVolume.top, (INT32)desc.srcVolume.front };
		imageRegion.dstOffset = { desc.dstPosition.x, desc.dstPosition.y, desc.dstPosition.z };
		imageRegion.extent = { mipWidth, mipHeight, mipDepth };
		imageRegion.srcSubresource.baseArrayLayer = desc.srcFace;
		imageRegion.srcSubresource.layerCount = 1;
		imageRegion.srcSubresource.mipLevel = desc.srcMip;
		imageRegion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
		imageRegion.dstSubresource.baseArrayLayer = desc.dstFace;
		imageRegion.dstSubresource.layerCount = 1;
		imageRegion.dstSubresource.mipLevel = desc.dstMip;
		imageRegion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;

		VkImageSubresourceRange srcRange;
		srcRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
		srcRange.baseArrayLayer = desc.srcFace;
		srcRange.layerCount = 1;
		srcRange.baseMipLevel = desc.srcMip;
		srcRange.levelCount = 1;

		VkImageSubresourceRange dstRange;
		dstRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
		dstRange.baseArrayLayer = desc.dstFace;
		dstRange.layerCount = 1;
		dstRange.baseMipLevel = desc.dstMip;
		dstRange.levelCount = 1;

		VulkanRenderAPI& rapi = static_cast<VulkanRenderAPI&>(RenderAPI::instance());

		VulkanCmdBuffer* vkCB;
		if (commandBuffer != nullptr)
			vkCB = static_cast<VulkanCommandBuffer*>(commandBuffer.get())->getInternal();
		else
			vkCB = rapi._getMainCommandBuffer()->getInternal();

		UINT32 deviceIdx = vkCB->getDeviceIdx();

		VulkanImage* srcImage = mImages[deviceIdx];
		VulkanImage* dstImage = other->getResource(deviceIdx);

		if (srcImage == nullptr || dstImage == nullptr)
			return;

		VkImageLayout srcLayout = vkCB->getCurrentLayout(srcImage, srcRange, false);
		VkImageLayout dstLayout = vkCB->getCurrentLayout(dstImage, dstRange, false);

		VkCommandBuffer vkCmdBuf = vkCB->getHandle();

		VkAccessFlags srcAccessMask = srcImage->getAccessFlags(srcLayout);
		VkAccessFlags dstAccessMask = dstImage->getAccessFlags(dstLayout);

		if (vkCB->isInRenderPass())
			vkCB->endRenderPass();

		// Transfer textures to a valid layout
		vkCB->setLayout(srcImage->getHandle(), srcAccessMask, VK_ACCESS_TRANSFER_READ_BIT, srcLayout,
								transferSrcLayout, srcRange);

		vkCB->setLayout(dstImage->getHandle(), dstAccessMask, VK_ACCESS_TRANSFER_WRITE_BIT,
								dstLayout, transferDstLayout, dstRange);

		if (srcHasMultisample && !destHasMultisample) // Resolving from MS to non-MS texture
		{
			vkCmdResolveImage(vkCmdBuf, srcImage->getHandle(), transferSrcLayout, dstImage->getHandle(), transferDstLayout, 
				1, &resolveRegion);
		}
		else // Just a normal copy
		{
			vkCmdCopyImage(vkCmdBuf, srcImage->getHandle(), transferSrcLayout, dstImage->getHandle(), transferDstLayout, 
				1, &imageRegion);
		}

		// Transfer back to optimal layouts
		srcLayout = srcImage->getOptimalLayout();

		// Notify the command buffer that these resources are being used on it
		vkCB->registerResource(srcImage, srcRange, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VulkanUseFlag::Read, ResourceUsage::Transfer);
		vkCB->registerResource(dstImage, dstRange, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VulkanUseFlag::Write, ResourceUsage::Transfer);
	}
	/**
	 * Attempts to cook a convex mesh from the provided mesh data. Assumes the mesh data is not null and contains vertex
	 * positions as well as face indices. If the method returns true the resulting convex mesh will be output in the @p
	 * data buffer, and its size in @p size. The data buffer will be allocated used the generic allocator and is up to the
	 * caller to free it.
	 */
	bool cookConvex(PxCooking* cooking, const SPtr<MeshData>& meshData, UINT8** data, UINT32& size)
	{
		SPtr<VertexDataDesc> vertexDesc = meshData->getVertexDesc();
		
		// Try to create hull from points
		PxConvexMeshDesc convexDesc;
		convexDesc.points.count = meshData->getNumVertices();
		convexDesc.points.stride = vertexDesc->getVertexStride();
		convexDesc.points.data = meshData->getElementData(VES_POSITION);
		convexDesc.flags |= PxConvexFlag::eCOMPUTE_CONVEX;

		PxDefaultMemoryOutputStream output;
		if (cooking->cookConvexMesh(convexDesc, output))
		{
			size = output.getSize();
			*data = (UINT8*)bs_alloc(size);

			memcpy(*data, output.getData(), size);
			return true;
		}

		// Try inflating the convex mesh
		convexDesc.flags |= PxConvexFlag::eINFLATE_CONVEX;
		if (cooking->cookConvexMesh(convexDesc, output))
		{
			size = output.getSize();
			*data = (UINT8*)bs_alloc(size);

			memcpy(*data, output.getData(), size);
			return true;
		}

		// Nothing works, just compute an AABB
		AABox box;

		auto vertIter = meshData->getVec3DataIter(VES_POSITION);
		do
		{
			box.merge(vertIter.getValue());
		}
		while (vertIter.moveNext());

		Vector3 aabbVerts[8];
		aabbVerts[0] = box.getCorner(AABox::FAR_LEFT_BOTTOM);
		aabbVerts[1] = box.getCorner(AABox::FAR_RIGHT_BOTTOM);
		aabbVerts[2] = box.getCorner(AABox::FAR_RIGHT_TOP);
		aabbVerts[3] = box.getCorner(AABox::FAR_LEFT_TOP);

		aabbVerts[4] = box.getCorner(AABox::NEAR_LEFT_BOTTOM);
		aabbVerts[5] = box.getCorner(AABox::NEAR_RIGHT_BOTTOM);
		aabbVerts[6] = box.getCorner(AABox::NEAR_RIGHT_TOP);
		aabbVerts[7] = box.getCorner(AABox::NEAR_LEFT_TOP);

		convexDesc.points.count = 8;
		convexDesc.points.stride = sizeof(Vector3);
		convexDesc.points.data = &aabbVerts[0];
		convexDesc.flags &= ~PxConvexFlag::eINFLATE_CONVEX;

		if (cooking->cookConvexMesh(convexDesc, output))
		{
			size = output.getSize();
			*data = (UINT8*)bs_alloc(size);

			memcpy(*data, output.getData(), size);
			return true;
		}

		return false;
	}
	GUIToggle::GUIToggle(const String& styleName, const GUIContent& content, SPtr<GUIToggleGroup> toggleGroup, const GUIDimensions& dimensions)
		:GUIButtonBase(styleName, content, dimensions), mToggleGroup(nullptr), mIsToggled(false)
	{
		if(toggleGroup != nullptr)
			toggleGroup->_add(this);
	}
Exemple #9
0
bool TClntTransMgr::openSockets(SPtr<TClntCfgIface> iface) {

    if (iface->noConfig())       
        return true;
    
    // open socket
    SPtr<TIfaceIface> realIface = ClntIfaceMgr().getIfaceByID(iface->getID());
    if (!realIface) {
            Log(Error) << "Interface " << iface->getFullName()
                           << " not present in system." << LogEnd;
        return false;
    }
    if (!realIface->flagUp()) {
        Log(Error) << "Interface " << realIface->getFullName()
                   << " is down. Unable to open socket." << LogEnd;
        return false;
    }
    if (!realIface->flagRunning()) {
        Log(Error) << "Interface " << realIface->getFullName()
                   << " is not running." << LogEnd;
        return false;
    }
    
    // get link-local address
    char* llAddr;
    realIface->firstLLAddress();
    llAddr=realIface->getLLAddress();
    if (!llAddr) {
        Log(Error) << "Interface " << realIface->getFullName()
                   << " does not have link-layer address. Weird." << LogEnd;
        return false;
    }

    SPtr<TIPv6Addr> addr = new TIPv6Addr(llAddr);

    // it's very important to open unicast socket first as it will be used for
    // unicast communication
    if (iface->getUnicast()) {
        Log(Notice) << "Creating socket for unicast communication on " << iface->getFullName()
                    << LogEnd;
        SPtr<TIPv6Addr> anyaddr = new TIPv6Addr("::", true); // don't bind to a specific address
        if (!realIface->addSocket(anyaddr, DHCPCLIENT_PORT, false, this->BindReuse)) {
            Log(Crit) << "Unicast socket creation (addr=" << anyaddr->getPlain() << ") on " 
                      << iface->getFullName() << " interface failed." << LogEnd;
            return false;
        }

    }

    Log(Notice) << "Creating socket (addr=" << *addr << ") on " 
                << iface->getFullName() << " interface." << LogEnd;
    if (!realIface->addSocket(addr,DHCPCLIENT_PORT,true, this->BindReuse)) {
        Log(Crit) << "Socket creation (addr=" << *addr << ") on " 
                  << iface->getFullName() << " interface failed." << LogEnd;
        return false;
    }

    if (llAddr) {
            char buf[48];
            inet_ntop6(llAddr,buf);
            // Log(Info) << "Socket bound to " << buf << "/port=" << DHCPCLIENT_PORT << LogEnd;
            this->ctrlIface = realIface->getID();
            strncpy(this->ctrlAddr,buf,48);
    } 

    return true;
}
SPtr<TClntMsg> TClntIfaceMgr::select(unsigned int timeout)
{
    int bufsize=4096;
    static char buf[4096];
    SPtr<TIPv6Addr> peer(new TIPv6Addr());
    int sockid;
    int msgtype;
    int ifaceid;

    sockid = TIfaceMgr::select(timeout, buf, bufsize, peer);

    if (sockid>0) {
        if (bufsize<4) {
            if (buf[0]!=CONTROL_MSG) {
                Log(Warning) << "Received message is too short (" << bufsize
                             << ") bytes." << LogEnd;
            } else {
                Log(Warning) << "Control message received." << LogEnd;
            }
            return 0; // NULL
        }
        msgtype = buf[0];
        SPtr<TClntMsg> ptr;
        SPtr<TIfaceIface> ptrIface;
        ptrIface = this->getIfaceBySocket(sockid);
        ifaceid = ptrIface->getID();
        Log(Debug) << "Received " << bufsize << " bytes on interface " << ptrIface->getName() << "/"
                   << ptrIface->getID() << " (socket=" << sockid << ", addr=" << *peer << "."
                   << ")." << LogEnd;

        switch (msgtype) {
        case ADVERTISE_MSG:
            ptr = new TClntMsgAdvertise(ifaceid,peer,buf,bufsize);
#ifndef MOD_DISABLE_AUTH
            if (!ptr->validateAuthInfo(buf, bufsize, ClntCfgMgr().getAuthAcceptMethods())) {
                    Log(Error) << "Message dropped, authentication validation failed." << LogEnd;
                    return 0;
            }
#endif
            return ptr;
        case SOLICIT_MSG:
        case REQUEST_MSG:
        case CONFIRM_MSG:
        case RENEW_MSG:
        case REBIND_MSG:
        case RELEASE_MSG:
        case DECLINE_MSG:
        case INFORMATION_REQUEST_MSG:
            Log(Warning) << "Illegal message type " << msgtype << " received." << LogEnd;
            return 0; // NULL
        case REPLY_MSG:
            ptr = new TClntMsgReply(ifaceid, peer, buf, bufsize);
#ifndef MOD_DISABLE_AUTH
            if (!ptr->validateAuthInfo(buf, bufsize, ClntCfgMgr().getAuthAcceptMethods())) {
                    Log(Error) << "Message dropped, authentication validation failed." << LogEnd;
                    return 0;
            }
#endif
            return ptr;

        case RECONFIGURE_MSG:
            Log(Warning) << "Reconfigure Message is currently not supported." << LogEnd;
            return 0; // NULL
        case RELAY_FORW_MSG: // those two msgs should not be visible for client
        case RELAY_REPL_MSG:
        default:
            Log(Warning) << "Message type " << msgtype << " is not supposed to "
                         << "be received by client. Check your relay/server configuration." << LogEnd;
            return 0;
        }
    } else {
        return 0;
    }
}
	SelectionRendererCore::~SelectionRendererCore()
	{
		SPtr<CoreRenderer> activeRenderer = RendererManager::instance().getActive();
		if (mCamera != nullptr)
			activeRenderer->unregisterRenderCallback(mCamera.get(), 10);
	}
bool TClntIfaceMgr::modifyPrefix(int iface, SPtr<TIPv6Addr> prefix, int prefixLen,
                                 unsigned int pref, unsigned int valid,
                                 PrefixModifyMode mode)
{
    SPtr<TClntIfaceIface> ptrIface = (Ptr*)getIfaceByID(iface);
    if (!ptrIface) {
        Log(Error) << "Unable to find interface with ifindex=" << iface
                   << ", prefix add/modify operation failed." << LogEnd;
        return false;
    }

    string action;
    int conf = 0; // number of successfully configured prefixes
    int status = -1;

    switch (mode) {
    case PREFIX_MODIFY_ADD:
            action = "Adding";
            break;
    case PREFIX_MODIFY_UPDATE:
            action = "Updating";
            break;
    case PREFIX_MODIFY_DEL:
            action = "Deleting";
            break;
    }

    // option: split this prefix and add it to all interfaces
    Log(Notice) << "PD: " << action << " prefix " << prefix->getPlain() << "/" << (int)prefixLen
                << " to all interfaces (prefix will be split to /"
                << int(prefixLen+8) << " prefixes if necessary)." << LogEnd;

    if (prefixLen>120) {
        Log(Error) << "PD: Unable to perform prefix operation: prefix /" << prefixLen
                   << " can't be split. At least /120 prefix is required." << LogEnd;
        return false;
    }

    // get a list of interfaces that we will assign prefixes to
    TIfaceIfaceLst ifaceLst;
    vector<string> ifaceNames = ClntCfgMgr().getDownlinkPrefixIfaces();
    for (vector<string>::const_iterator name = ifaceNames.begin(); name != ifaceNames.end(); ++name) {
        SPtr<TIfaceIface> x = getIfaceByName(*name);
        if (x)
            ifaceLst.push_back(x);
        else
            Log(Warning) << "Interface " << *name << " specified in downlink-prefix-ifaces is missing." << LogEnd;
    }

    if (ifaceLst.size() == 0) {
        SPtr<TIfaceIface> x;
        firstIface();
        while ( x = (Ptr*)getIface() ) {
            if (x->getID() == ptrIface->getID()) {
                Log(Debug) << "PD: Interface " << x->getFullName()
                           << " is the interface, where prefix has been obtained, skipping." << LogEnd;
                continue;
            }

            // for each interface present in the system...
            if (!x->flagUp()) {
                Log(Debug) << "PD: Interface " << x->getFullName() << " is down, ignoring." << LogEnd;
            continue;
            }
            if (!x->flagRunning()) {
                Log(Debug) << "PD: Interface " << x->getFullName()
                           << " has flag RUNNING not set, ignoring." << LogEnd;
                continue;
            }
            if (!x->flagMulticast()) {
                Log(Debug) << "PD: Interface " << x->getFullName()
                           << " is not multicast capable, ignoring." << LogEnd;
                continue;
            }
            if ( !(x->getMacLen() > 5) ) {
                Log(Debug) << "PD: Interface " << x->getFullName()
                           << " has MAC address length " << x->getMacLen()
                           << " (6 or more required), ignoring." << LogEnd;
                continue;
            }
            x->firstLLAddress();
            if (!x->getLLAddress()) {
                Log(Debug) << "PD: Interface " << x->getFullName()
                           << " has no link-local address, ignoring. (Disconnected? Not associated? No-link?)" << LogEnd;
                continue;
            }

            ifaceLst.push_back(x);
        }
    }

    Log(Info) << "PD: Using " << ifaceLst.size() << " suitable interface(s):";
    TIfaceIfaceLst::const_iterator i;
    for (TIfaceIfaceLst::const_iterator i=ifaceLst.begin(); i!=ifaceLst.end(); ++i) {
        Log(Cont) << (*i)->getName() << " ";
    }
    Log(Cont) << LogEnd;

    if (ifaceLst.size() == 0) {
        Log(Warning) << "Suitable interfaces not found. Delegated prefix not split." << LogEnd;
        return true;
    }

    for (TIfaceIfaceLst::const_iterator i=ifaceLst.begin(); i!=ifaceLst.end(); ++i) {

        char buf[16];
        int subprefixLen;
        memmove(buf, prefix->getAddr(), 16);

        if (ifaceLst.size() == 1) {
            // just one interface - use delegated prefix as is
            subprefixLen = prefixLen;
        } else if (ifaceLst.size()<256) {
            subprefixLen = prefixLen + 8;
            int offset = prefixLen/8;
            if (prefixLen%8 == 0) {
                // that's easy, just put ID in the next octet
                buf[offset] = (*i)->getID();
            } else {
                // here's fun
                uint16_t existing = readUint16(buf+offset);
                uint16_t bitmask = 0xff00;
                uint16_t infixmask = ((uint8_t)(*i)->getID()) << 8;
                bitmask = bitmask >> (prefixLen%8);
                infixmask = infixmask >> (prefixLen%8);

                // clear out if there is anything there, i.e. server assigned prefix
                // with garbage in host section
                existing = existing & (~bitmask);
                existing = existing | (bitmask & infixmask);
                writeUint16(buf+offset, existing);
            }

        } else {
bool TClntIfaceMgr::fqdnDel(SPtr<TClntIfaceIface> iface, SPtr<TAddrIA> ia, string fqdn)
{
    SPtr<TIPv6Addr> dns = ia->getFQDNDnsServer();

    // let's do deleting update
    SPtr<TIPv6Addr> clntAddr;
    ia->firstAddr();
    SPtr<TAddrAddr> tmpAddr = ia->getAddr();
    if (!tmpAddr) {
        Log(Error) << "FQDN: Unable to delete FQDN: IA (IAID=" << ia->getIAID()
                   << ") does not have any addresses." << LogEnd;
        return false;
    }
    SPtr<TIPv6Addr> myAddr = tmpAddr->get();

    SPtr<TClntCfgIface> ptrIface = ClntCfgMgr().getIface(iface->getID());

    TCfgMgr::DNSUpdateProtocol proto = ClntCfgMgr().getDDNSProtocol();
    DNSUpdate::DnsUpdateProtocol proto2 = DNSUpdate::DNSUPDATE_TCP;
    if (proto == TCfgMgr::DNSUPDATE_UDP)
        proto2 = DNSUpdate::DNSUPDATE_UDP;
    if (proto == TCfgMgr::DNSUPDATE_ANY)
        proto2 = DNSUpdate::DNSUPDATE_ANY;
    unsigned int timeout = ClntCfgMgr().getDDNSTimeout();

    Log(Debug) << "FQDN: Cleaning up DNS AAAA record in server " << *dns << ", for IP=" << *myAddr
               << " and FQDN=" << fqdn << LogEnd;
#ifndef MOD_CLNT_DISABLE_DNSUPDATE
    DNSUpdate *act = new DNSUpdate(dns->getPlain(), "", fqdn, myAddr->getPlain(),
                                   DNSUPDATE_AAAA_CLEANUP, proto2);
    int result = act->run(timeout);
    act->showResult(result);
    delete act;

#else
    Log(Error) << "This Dibbler version is compiled without DNS Update support." << LogEnd;
#endif

    return false;
}
bool TClntIfaceMgr::fqdnAdd(SPtr<TClntIfaceIface> iface, string fqdn)
{
    SPtr<TIPv6Addr> DNSAddr;
    SPtr<TIPv6Addr> addr;

    SPtr<TClntCfgIface> cfgIface;
    cfgIface = ClntCfgMgr().getIface(iface->getID());
    if (!cfgIface) {
        Log(Error) << "Unable to find interface with ifindex=" << iface->getID() << "." << LogEnd;
        return false;
    }

    // For the moment, we just take the first DNS entry.
    List(TIPv6Addr) DNSSrvLst = iface->getDNSServerLst();
    if (!DNSSrvLst.count()) {
        Log(Error) << "Unable to find DNS Server. FQDN add failed." << LogEnd;
        return false;
    }
    DNSSrvLst.first();
    DNSAddr = DNSSrvLst.get();

    // And the first IP address
    SPtr<TAddrIA> ptrAddrIA;
    ClntAddrMgr().firstIA();
    ptrAddrIA = ClntAddrMgr().getIA();

    if (ptrAddrIA->countAddr() > 0) {
        ptrAddrIA->firstAddr();
        addr = ptrAddrIA->getAddr()->get();

        Log(Notice) << "FQDN: About to perform DNS Update: DNS server=" << *DNSAddr
                    << ", IP=" << *addr << " and FQDN=" << fqdn << LogEnd;

        // remember DNS Address (used during address release)
        ptrAddrIA->setFQDNDnsServer(DNSAddr);

        TCfgMgr::DNSUpdateProtocol proto = ClntCfgMgr().getDDNSProtocol();
        DNSUpdate::DnsUpdateProtocol proto2 = DNSUpdate::DNSUPDATE_TCP;
        if (proto == TCfgMgr::DNSUPDATE_UDP)
            proto2 = DNSUpdate::DNSUPDATE_UDP;
        if (proto == TCfgMgr::DNSUPDATE_ANY)
            proto2 = DNSUpdate::DNSUPDATE_ANY;
        unsigned int timeout = ClntCfgMgr().getDDNSTimeout();

#ifndef MOD_CLNT_DISABLE_DNSUPDATE
        /* add AAAA record */
        DNSUpdate *act = new DNSUpdate(DNSAddr->getPlain(), "", fqdn, addr->getPlain(),
                                       DNSUPDATE_AAAA, proto2);
        int result = act->run(timeout);
        act->showResult(result);
        delete act;
#else
        Log(Error) << "This version is compiled without DNS Update support." << LogEnd;
        return false;
#endif
    }
    return true;
}
Exemple #15
0
bool TAddrMgr::updatePrefix(SPtr<TAddrClient> client, SPtr<TDUID> duid , SPtr<TIPv6Addr> clntAddr,
                            int iface, unsigned long IAID, unsigned long T1, unsigned long T2,
                            SPtr<TIPv6Addr> prefix, unsigned long pref, unsigned long valid,
                            int length, bool quiet)
{
    if (!prefix) {
        Log(Error) << "Attempt to update null prefix failed." << LogEnd;
        return false;
    }
    if (!client) {
        Log(Error) << "Unable to update prefix, client not defined." << LogEnd;
        return false;
    }

    // for that client, find IA
    SPtr <TAddrIA> pd;
    client->firstPD();
    while ( pd = client->getPD() ) {
        if ( pd->getIAID() == IAID)
            break;
    }
    // have we found this PD?
    if (!pd) {
        Log(Error) << "Unable to find PD (iaid=" << IAID << ") for client " << duid->getPlain() << "." << LogEnd;
        return false;
    }
    pd->setTimestamp();
    pd->setT1(T1);
    pd->setT2(T2);

    SPtr <TAddrPrefix> ptrPrefix;
    pd->firstPrefix();
    while ( ptrPrefix = pd->getPrefix() ) {
        if (*ptrPrefix->get()==*prefix)
            break;
    }

    // address already exists
    if (!ptrPrefix) {
        Log(Warning) << "PD: Prefix " << prefix->getPlain() << " is not known. Unable to update." << LogEnd;
        return false;
    }

    ptrPrefix->setTimestamp();
    ptrPrefix->setPref(pref);
    ptrPrefix->setValid(pref);

    return true;
}
Exemple #16
0
/** this function removes expired addresses from interface and from database
 *  It must be called before AddrMgr::doDuties() is called.
 */
void TClntTransMgr::removeExpired() {

    if (ClntAddrMgr().getValidTimeout())
        return;

    SPtr<TAddrIA> ptrIA;
    SPtr<TAddrAddr> ptrAddr;
    SPtr<TIfaceIface> ptrIface;

    ClntAddrMgr().firstIA();
    while (ptrIA = ClntAddrMgr().getIA()) {
        if (ptrIA->getValidTimeout())
            continue;

        ptrIA->firstAddr();
        while (ptrAddr = ptrIA->getAddr()) {
            if (ptrAddr->getValidTimeout())
                continue;
            ptrIface = ClntIfaceMgr().getIfaceByID(ptrIA->getIface());
            Log(Warning) << "Address " << ptrAddr->get()->getPlain() << " assigned to the "
                         << ptrIface->getName() << "/" << ptrIface->getID() 
                         << " interface (in IA " << ptrIA->getIAID() <<") has expired." << LogEnd;

            // remove that address from the physical interace
            ptrIface->delAddr(ptrAddr->get(), ptrIface->getPrefixLength());
        }
    }
}
Exemple #17
0
/*
 *  Frees prefix (also deletes IA and/or client, if this was last address)
 */
bool TAddrMgr::delPrefix(SPtr<TDUID> clntDuid,
                            unsigned long IAID, SPtr<TIPv6Addr> prefix,
                            bool quiet) {

    Log(Debug) << "PD: Deleting prefix " << prefix->getPlain() << ", DUID=" << clntDuid->getPlain() << ", iaid=" << IAID << LogEnd;
    // find this client
    SPtr <TAddrClient> ptrClient;
    this->firstClient();
    while ( ptrClient = this->getClient() ) {
        if ( (*ptrClient->getDUID()) == (*clntDuid) )
            break;
    }

    // have we found this client?
    if (!ptrClient) {
        Log(Warning) << "PD: Client (DUID=" << clntDuid->getPlain()
                     << ") not found in addrDB, cannot delete address and/or client." << LogEnd;
        return false;
    }

    // find this IA
    SPtr <TAddrIA> ptrPD;
    ptrClient->firstPD();
    while ( ptrPD = ptrClient->getPD() ) {
        if ( ptrPD->getIAID() == IAID)
            break;
    }

    // have we found this IA?
    if (!ptrPD) {
        Log(Warning) << "PD: iaid=" << IAID << " not assigned to client, cannot delete address and/or PD."
                     << LogEnd;
        return false;
    }

    SPtr <TAddrPrefix> ptrPrefix;
    ptrPD->firstPrefix();
    while ( ptrPrefix = ptrPD->getPrefix() ) {
        if (*ptrPrefix->get()==*prefix)
            break;
    }

    // address already exists
    if (!ptrPrefix) {
        Log(Warning) << "PD: Prefix " << *prefix << " not assigned, cannot delete." << LogEnd;
        return false;
    }

    ptrPD->delPrefix(prefix);

    /// @todo: Cache for prefixes this->addCachedAddr(clntDuid, clntAddr);
    if (!quiet)
        Log(Debug) << "PD: Deleted prefix " << *prefix << " from addrDB." << LogEnd;

    if (!ptrPD->countPrefix()) {
        if (!quiet)
            Log(Debug) << "PD: Deleted PD (iaid=" << IAID << ") from addrDB." << LogEnd;
        ptrClient->delPD(IAID);
    }

    if (!ptrClient->countIA() && !ptrClient->countTA() && !ptrClient->countPD() && DeleteEmptyClient) {
        if (!quiet)
            Log(Debug) << "PD: Deleted client (DUID=" << clntDuid->getPlain()
                       << ") from addrDB." << LogEnd;
        this->delClient(clntDuid);
    }

    return true;
}
Exemple #18
0
/** 
 * checks if loaded Address database is sanite (i.e. does not reffer to non-existing interface)
 * 
 */
void TClntTransMgr::checkDB()
{
    SPtr<TClntCfgIface> iface;
    SPtr <TAddrIA> ptrIA;
    SPtr<TAddrAddr> ptrAddr;

    ClntAddrMgr().doDuties();
    ClntAddrMgr().firstIA();
    while ( ptrIA = ClntAddrMgr().getIA()) {
        iface = ClntCfgMgr().getIface( ptrIA->getIface() );
        if (!iface) {
            Log(Warning) << "IA (iaid=" << ptrIA->getIAID() 
                         << ") loaded from old file, but currently there is no iface with ifindex="
                                 << ptrIA->getIface();
            // IA with non-existent iface, purge iface
            ptrIA->firstAddr();
            while (ptrAddr = ptrIA->getAddr())
                ptrIA->delAddr( ptrAddr->get() );
            ptrIA->setState(STATE_NOTCONFIGURED);
            ClntAddrMgr().delIA(ptrIA->getIAID());
        }
    }
}
	void EditorWindowBase::construct(const SPtr<RenderWindow>& renderWindow)
	{
		mRenderWindow = renderWindow;
		mSceneObject = SceneObject::create("EditorWindow", SOF_Internal | SOF_Persistent | SOF_DontSave);

		mCamera = mSceneObject->addComponent<CCamera>();
		mCamera->getViewport()->setTarget(renderWindow);
		mCamera->setNearClipDistance(5);
		mCamera->setAspectRatio(1.0f);
		mCamera->setLayers(0);

		SPtr<RenderSettings> settings = mCamera->getRenderSettings();
		settings->overlayOnly = true;

		mGUI = mSceneObject->addComponent<CGUIWidget>(mCamera);
		mGUI->setDepth(128);

		mGUI->setSkin(BuiltinEditorResources::instance().getSkin());

		mWindowFrame = mSceneObject->addComponent<WindowFrameWidget>(!mIsModal, mCamera->_getCamera(), renderWindow.get(), BuiltinEditorResources::instance().getSkin());
		mWindowFrame->setDepth(129);

		mResizedConn = renderWindow->onResized.connect(std::bind(&EditorWindowBase::resized, this));
	}
Exemple #20
0
/*
 * this method is called, when no message has been received, but some
 * action should be taken, e.g. RENEW transmission
 */
void TClntTransMgr::doDuties()
{
    // for each message on list, let it do its duties, if timeout is reached
    SPtr <TClntMsg> msg;
    Transactions.first();
    while(msg=Transactions.get())
    {
        if ((!msg->getTimeout())&&(!msg->isDone())) {
            Log(Info) << "Processing msg (" << msg->getName() << ",transID=0x"
                 << hex << msg->getTransID() << dec << ",opts:";
            SPtr<TOpt> ptrOpt;
            msg->firstOption();
            while (ptrOpt = msg->getOption()) {
                Log(Cont) << " " << ptrOpt->getOptType();
            }
            Log(Cont) << ")" << LogEnd;
            msg->doDuties();
        }
    }

    // now delete messages which are marked as done
    Transactions.first();
    while (msg = Transactions.get() ) {
        if (msg->isDone())
            Transactions.del();
    }

    if (ClntCfgMgr().inactiveMode())
    {
        SPtr<TClntCfgIface> x;
        x = ClntCfgMgr().checkInactiveIfaces();
        if (x) {
            if (!openSockets(x)) {
                Log(Crit) << "Attempt to bind activates interfaces failed."
                          << " Following operation may be unstable!" << LogEnd;
            }
        }
    }

    removeExpired();
    ClntAddrMgr().doDuties();

    ClntAddrMgr().dump();
    ClntIfaceMgr().dump();
    ClntCfgMgr().dump();

    if (!this->Shutdown && !this->IsDone) {

        // did we switched links lately?
        // are there any IAs to confirm?
        checkConfirm();
        
        // are there any tentative addrs?
        checkDecline();

        // are there any IAs or TAs to configure?
        checkSolicit();

        //is there any IA in Address manager, which has not sufficient number 
        //of addresses
        checkRequest();

        // are there any aging IAs or PDs?
        checkRenew();

        //Maybe we require only infromations concernig link
        checkInfRequest();

#ifdef MOD_REMOTE_AUTOCONF
        checkRemoteSolicits();
#endif

    } 
    
    // This method launch the DNS update, so the checkDecline has to be done before to ensure the ip address is valid
    ClntIfaceMgr().doDuties();

    if (this->Shutdown && !Transactions.count())
        this->IsDone = true;
}
	SPtr<MeshData> FPhysXMesh::getMeshData() const
	{
		SPtr<VertexDataDesc> vertexDesc = VertexDataDesc::create();
		vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION);

		if (mConvexMesh == nullptr && mTriangleMesh == nullptr)
			return MeshData::create(0, 0, vertexDesc);

		UINT32 numVertices = 0;
		UINT32 numIndices = 0;

		if(mConvexMesh != nullptr)
		{
			numVertices = mConvexMesh->getNbVertices();

			UINT32 numPolygons = mConvexMesh->getNbPolygons();
			for (UINT32 i = 0; i < numPolygons; i++)
			{
				PxHullPolygon face;
				bool status = mConvexMesh->getPolygonData(i, face);
				assert(status);

				numIndices += (face.mNbVerts - 2) * 3;
			}
		}
		else // Triangle
		{
			numVertices = mTriangleMesh->getNbVertices();
			numIndices = mTriangleMesh->getNbTriangles() * 3;
		}

		SPtr<MeshData> meshData = MeshData::create(numVertices, numIndices, vertexDesc);

		auto posIter = meshData->getVec3DataIter(VES_POSITION);
		UINT32* outIndices = meshData->getIndices32();

		if (mConvexMesh != nullptr)
		{
			const PxVec3* convexVertices = mConvexMesh->getVertices();
			const UINT8* convexIndices = mConvexMesh->getIndexBuffer();

			for (UINT32 i = 0; i < numVertices; i++)
				posIter.addValue(fromPxVector(convexVertices[i]));

			UINT32 numPolygons = mConvexMesh->getNbPolygons();
			for (UINT32 i = 0; i < numPolygons; i++)
			{
				PxHullPolygon face;
				bool status = mConvexMesh->getPolygonData(i, face);
				assert(status);

				const PxU8* faceIndices = convexIndices + face.mIndexBase;
				for (UINT32 j = 2; j < face.mNbVerts; j++)
				{
					*outIndices++ = faceIndices[0];
					*outIndices++ = faceIndices[j];
					*outIndices++ = faceIndices[j - 1];
				}
			}
		}
		else
		{
			const PxVec3* vertices = mTriangleMesh->getVertices();
			for (UINT32 i = 0; i < numVertices; i++)
				posIter.addValue(fromPxVector(vertices[i]));

			if(mTriangleMesh->getTriangleMeshFlags() & PxTriangleMeshFlag::e16_BIT_INDICES)
			{
				const UINT16* indices = (const UINT16*)mTriangleMesh->getTriangles();

				UINT32 numTriangles = numIndices / 3;
				for (UINT32 i = 0; i < numTriangles; i++)
				{
					// Flip triangles as PhysX keeps them opposite to what Banshee expects
					outIndices[i * 3 + 0] = (UINT32)indices[i * 3 + 0];
					outIndices[i * 3 + 1] = (UINT32)indices[i * 3 + 2];
					outIndices[i * 3 + 2] = (UINT32)indices[i * 3 + 1];
				}
			}
			else
			{
				const UINT32* indices = (const UINT32*)mTriangleMesh->getTriangles();

				UINT32 numTriangles = numIndices / 3;
				for (UINT32 i = 0; i < numTriangles; i++)
				{
					// Flip triangles as PhysX keeps them opposite to what Banshee expects
					outIndices[i * 3 + 0] = indices[i * 3 + 0];
					outIndices[i * 3 + 1] = indices[i * 3 + 2];
					outIndices[i * 3 + 2] = indices[i * 3 + 1];
				}
			}
		}

		return meshData;
	}
Exemple #22
0
void TClntTransMgr::shutdown()
{
    SPtr<TAddrIA> ptrFirstIA;
    SPtr<TAddrIA> ptrNextIA;
    SPtr<TAddrIA> ta;
    SPtr<TAddrIA> pd;
    SPtr<TClntCfgIface> iface;
    List(TAddrIA) releasedIAs;
    List(TAddrIA) releasedPDs;

    Transactions.clear(); // delete all transactions
    this->Shutdown = true;
    Log(Notice) << "Shutting down entire client." << LogEnd;
        
    // delete all weird-state/innormal-state and address-free IAs 
    ClntAddrMgr().firstIA();
    while (ptrFirstIA = ClntAddrMgr().getIA()) {
        if ( (ptrFirstIA->getState() != STATE_CONFIGURED && ptrFirstIA->getState() != STATE_INPROCESS) ||
            !ptrFirstIA->countAddr() )
            ClntAddrMgr().delIA(ptrFirstIA->getIAID()); 
    }

    // normal IAs are to be released
    while (ClntAddrMgr().countIA()) {
        // clear the list
        releasedIAs.clear();

        // get first IA
        ClntAddrMgr().firstIA();
        ptrFirstIA = ClntAddrMgr().getIA();
        releasedIAs.append(ptrFirstIA);
        ClntAddrMgr().delIA( ptrFirstIA->getIAID() );

        // find similar IAs 
        while (ptrNextIA = ClntAddrMgr().getIA()) {
            if ((*(ptrFirstIA->getDUID())==*(ptrNextIA->getDUID())) &&
                (ptrFirstIA->getIface() == ptrNextIA->getIface() ) ) 
            {
                // IA serviced via this same server, add it do the list
                releasedIAs.append(ptrNextIA);

                // delete addressess from IfaceMgr
                SPtr<TAddrAddr> ptrAddr;
                SPtr<TIfaceIface> ptrIface;
                ptrIface = ClntIfaceMgr().getIfaceByID(ptrNextIA->getIface());
                if (!ptrIface) {
                            Log(Error) << "Unable to find " << ptrNextIA->getIface()
                               << " interface while releasing address." << LogEnd;
                    break;
                }
                ptrNextIA->firstAddr();

                // delete IA from AddrMgr
                ClntAddrMgr().delIA( ptrNextIA->getIAID() );
            }
        }

        ta = 0;
        if (releasedIAs.count()) { 
                // check if there are TA to release
                releasedIAs.first();
                iface = ClntCfgMgr().getIface(releasedIAs.get()->getIface());
                if (iface && iface->countTA()) {
                    iface->firstTA();
                    SPtr<TClntCfgTA> cfgTA = iface->getTA();
                        ta = ClntAddrMgr().getTA(cfgTA->getIAID());
                        cfgTA->setState(STATE_DISABLED);
                }

        }
            pd = 0;
            ClntAddrMgr().firstPD();
            while (pd = ClntAddrMgr().getPD()) {
                releasedPDs.append(pd);
                SPtr<TClntCfgPD> cfgPD = ClntCfgMgr().getPD(pd->getIAID());
                if (cfgPD)
                    cfgPD->setState(STATE_DISABLED);
            }
            sendRelease(releasedIAs,ta, releasedPDs);
    }

    // now check if there are any TA left
    ClntCfgMgr().firstIface();
    while (iface = ClntCfgMgr().getIface()) {
        if (iface->countTA()) {
            iface->firstTA();
            SPtr<TClntCfgTA> cfgTA = iface->getTA();
            ta = ClntAddrMgr().getTA(cfgTA->getIAID());
            releasedIAs.clear();
            if (!ta) {
                Log(Warning) << "Unable to find TA(taid=" << cfgTA->getIAID() <<"). " << LogEnd;
                continue;
            }
            if (cfgTA->getState()==STATE_CONFIGURED) {
                this->sendRelease(releasedIAs, ta, releasedPDs);
                cfgTA->setState(STATE_DISABLED);
            }
        }

    }

    // are there any PDs left to release?
    pd = 0;
    ClntAddrMgr().firstPD();
    releasedIAs.clear();
    releasedPDs.clear();
    while (pd = ClntAddrMgr().getPD()) {
        releasedPDs.append(pd);
        SPtr<TClntCfgPD> cfgPD = ClntCfgMgr().getPD(pd->getIAID());
        if (cfgPD)
            cfgPD->setState(STATE_DISABLED);
    }
    if (releasedPDs.count())
        this->sendRelease(releasedIAs, 0, releasedPDs);
    
    //CHANGED:the following two lines are uncommented.
    doDuties(); // just to send RELEASE msg
    Transactions.clear(); // delete all transactions

    // clean up options
    ClntIfaceMgr().removeAllOpts();
}
SPtr<PhysicalObject> GridSceneGraph::mouseCollides(double xPos, double yPos) {
	SPtr<PhysicalObject> obj;
	glm::mat4 view, proj;
	glm::vec3 objPos, near, far, objRay, mouseRay, mousePos;
	glm::vec4 viewP;

	double minDist = 0.0, newDist = 0.0;
   bool minDistSet = false;

	SPtr<Scene> s = scene.lock();
	if (!s) {
		return SPtr<PhysicalObject>();
	}
	SPtr<Camera> c = s->getCamera().lock();
	if (!c) {
		return SPtr<PhysicalObject>();
	}

	proj = c->getProjectionMatrix();
	view = c->getViewMatrix();
	viewP = glm::vec4(0, 0, c->getWindowWidth(), c->getWindowHeight());
	mousePos = glm::vec3(xPos, c->getWindowHeight() - yPos, 0.0);

	near = glm::unProject(mousePos, view, proj, viewP);
	mousePos.z = 1.0;
	far = glm::unProject(mousePos, view, proj, viewP);
	mouseRay = far - near;

   std::vector<GridElement<SPtr<PhysicalObject>>>& staticElements = staticPhysObjects.getElements();
   std::vector<GridElement<SPtr<PhysicalObject>>>& movableElements = movablePhysObjects.getElements();

   for (GridElement<SPtr<PhysicalObject>> physElement : staticElements) {
      objPos = physElement.element->getPosition();
		objRay = objPos - near;
		glm::vec3 rayIntersect = glm::normalize(mouseRay) * glm::length(objRay) + c->getPosition();

		if ((physElement.element->getBounds()).contains(rayIntersect)) {
			if (!minDistSet|| (newDist = glm::length(objRay)) < minDist) {
            minDistSet = true;
				minDist = newDist;
				obj = physElement.element;
			}
		}
   }

   for (GridElement<SPtr<PhysicalObject>> physElement : movableElements) {
      objPos = physElement.element->getPosition();
		objRay = objPos - near;
		glm::vec3 rayIntersect = glm::normalize(mouseRay) * glm::length(objRay) + c->getPosition();

		if ((physElement.element->getBounds()).contains(rayIntersect)) {
			if (!minDistSet|| glm::length(objRay) < minDist) {
				newDist = glm::length(objRay);
				minDistSet = true;
				minDist = newDist;
				obj = physElement.element;
			}
		}
   }

	return obj;
}
Exemple #24
0
void TClntTransMgr::relayMsg(SPtr<TClntMsg> msgAnswer)
{
    SPtr<TIfaceIface> ifaceQuestion;
    SPtr<TIfaceIface> ifaceAnswer;

    // is message valid?
    if (!msgAnswer->check())
        return ;

#ifdef MOD_REMOTE_AUTOCONF
    if (neighborInfoGet(msgAnswer->getTransID())) {
        processRemoteReply(msgAnswer);
        return;
    }
#endif 
    
    // find which message this is answer for
    bool found = false;
    SPtr<TClntMsg> msgQuestion;
    Transactions.first();
    while(msgQuestion=(Ptr*)Transactions.get()) {
        if (msgQuestion->getTransID()==msgAnswer->getTransID()) {
            found =true;
            if (msgQuestion->getIface()!=msgAnswer->getIface()) {
                ifaceQuestion = ClntIfaceMgr().getIfaceByID(msgQuestion->getIface());
                ifaceAnswer   = ClntIfaceMgr().getIfaceByID(msgAnswer->getIface());
                Log(Warning) << "Reply for transaction 0x" << hex << msgQuestion->getTransID() << dec
                             << " sent on " << ifaceQuestion->getFullName() << " was received on interface " 
                             << ifaceAnswer->getFullName() << "." << LogEnd;
                // return; // don't return, just fix interface ID
                // useful, when sending thru eth0, but receiving via loopback
                msgAnswer->setIface(msgQuestion->getIface());
            }

            handleResponse(msgQuestion, msgAnswer);
            break;
        }
    }

    if (!found) 
    {
        if (!Shutdown)
            Log(Warning) << "Message with wrong transID (0x" << hex << msgAnswer->getTransID() << dec
                         << ") received. Ignoring." << LogEnd;
        else
            Log(Debug) << "Message with transID=0x" << hex << msgAnswer->getTransID() << dec
                       << " received, but ignored during shutdown." << LogEnd;
    } 
    ClntCfgMgr().dump();
    ClntAddrMgr().dump();
}
Exemple #25
0
void StateManager::stateChange(StateID state) {
  assert(m_initialised == true);
  if (m_current_state == state) return; // No need to do anything

  assert (state < (int)m_states.size());
  SPtr<StateProperties> sp = m_states[state];
  // If state doesn't exist, take first one

  if (!sp) {
    std::cerr << "bad state found - " << state <<  std::endl;
    sp = m_states[1];
    state = 1;
  }
  assert(sp.isValid());
  // First time round, we have no states
  if (m_current_state != -1) {
    unsigned int list = m_state_change_vector[m_current_state][state];
    // Check whether we need to generate a display list
    if (!glIsList(list)) {
      list = glGenLists(1);
      buildStateChange(list, m_states[m_current_state], sp);
      m_state_change_vector[m_current_state][state] = list;
    }
    glCallList(list);
  } else {
    // We can't build up a transition, so we just go ahead directly	  
    if (sp->alpha_test) glEnable(GL_ALPHA_TEST);
    else glDisable(GL_ALPHA_TEST);
    if (sp->blend) glEnable(GL_BLEND);
    else glDisable(GL_BLEND);
//    if (sp->lighting && checkState(RENDER_LIGHTING)) glEnable(GL_LIGHTING);
    if (sp->lighting) glEnable(GL_LIGHTING);
    else glDisable(GL_LIGHTING);
//    if (sp->two_sided_lighting && checkState(RENDER_LIGHTING)) glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
    if (sp->two_sided_lighting) glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
    else glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
//    if (sp->textures && checkState(RENDER_TEXTURES)) glEnable(GL_TEXTURE_2D);
    for (int i = MAX_UNITS - 1; i >= 0; --i) {
      glActiveTextureARB(GL_TEXTURE0_ARB + i);
      if (sp->textures[i]) glEnable(GL_TEXTURE_2D);
      else glDisable(GL_TEXTURE_2D);
    }
    if (sp->colour_material) glEnable(GL_COLOR_MATERIAL);
    else glDisable(GL_COLOR_MATERIAL);
    
    if (sp->depth_test) glEnable(GL_DEPTH_TEST);
    else glDisable(GL_DEPTH_TEST);
    glDepthMask(sp->depth_write);
        
    if (sp->cull_face) glEnable(GL_CULL_FACE);
    else glDisable(GL_CULL_FACE);
    if (sp->cull_face_cw) glFrontFace(GL_CW);
    else glFrontFace(GL_CCW);
    if (sp->stencil) glEnable(GL_STENCIL_TEST);
    else glDisable(GL_STENCIL_TEST);
    if (sp->fog) glEnable(GL_FOG);
    else glDisable(GL_FOG);
    if (sp->rescale_normals) glEnable(GL_RESCALE_NORMAL);
    else glDisable(GL_RESCALE_NORMAL);
    if (sp->normalise) glEnable(GL_NORMALIZE);
    else glDisable(GL_NORMALIZE);
    // TODO is this broken? 0 could be a valid state....
//    if (sp->alpha_function != 0) {
      glAlphaFunc(sp->alpha_function, sp->alpha_value);
//    }
//    if (sp->blend_src_function != 0) {
      glBlendFunc(sp->blend_src_function, sp->blend_dest_function);
  //  }
  }
  m_current_state = state;
}
Exemple #26
0
bool TClntTransMgr::populateAddrMgr(SPtr<TClntCfgIface> iface)
{
    // create IAs in AddrMgr corresponding to those specified in CfgMgr.
    SPtr<TClntCfgIA> ia;
    iface->firstIA();
    while(ia = iface->getIA()) {
        if (ClntAddrMgr().getIA(ia->getIAID()))
            continue; // there is such IA already - read from disk cache (client-AddrMgr.xml)
        SPtr<TAddrIA> addrIA = new TAddrIA(iface->getID(), TAddrIA::TYPE_IA,
                                           0, 0, ia->getT1(), ia->getT2(),
                                           ia->getIAID());
        ClntAddrMgr().addIA(addrIA);
    }

    SPtr<TClntCfgTA> ta;
    iface->firstTA();
    if ( (ta = iface->getTA()) &&  (!ClntAddrMgr().getTA(ta->getIAID())))
    {
        // if there is such TA already, then skip adding it
        SPtr<TAddrIA> addrTA = new TAddrIA(iface->getID(), TAddrIA::TYPE_TA,
                                           0, 0, DHCPV6_INFINITY, DHCPV6_INFINITY,
                                           ta->getIAID());
        ClntAddrMgr().addTA(addrTA);
    }

    SPtr<TClntCfgPD> pd;
    iface->firstPD();
    while (pd = iface->getPD()) {
        if (ClntAddrMgr().getPD(pd->getIAID()))
            continue; // there is such IA already - read from disk cache (client-AddrMgr.xml)
        SPtr<TAddrIA> addrPD = new TAddrIA(iface->getID(), TAddrIA::TYPE_PD,
                                           0, 0, pd->getT1(), pd->getT2(),
                                           pd->getIAID());
        ClntAddrMgr().addPD(addrPD);
    }

    return true;
}
Exemple #27
0
void TDHCPServer::run()
{
    bool silent = false;
    while ( (!isDone()) && (!SrvTransMgr().isDone()) ) {
        if (serviceShutdown)
            SrvTransMgr().shutdown();

        SrvTransMgr().doDuties();
        unsigned int timeout = SrvTransMgr().getTimeout();
        if (timeout == 0)        timeout = 1;
        if (serviceShutdown)     timeout = 0;

        if (!silent)
            Log(Notice) << "Accepting connections. Next event in " << timeout
                        << " second(s)." << LogEnd;
#ifdef WIN32
        // There's no easy way to break select under Windows, so just don't sleep for too long.
        if (timeout>5) {
            silent = true;
            timeout = 5;
        }
#endif

        SPtr<TSrvMsg> msg=SrvIfaceMgr().select(timeout);
        if (!msg)
            continue;
        silent = false;
        SPtr<TIfaceIface>  physicalIface = SrvIfaceMgr().getIfaceByID(msg->getPhysicalIface());
        SPtr<TSrvCfgIface> logicalIface = SrvCfgMgr().getIfaceByID(msg->getIface());
        if (!physicalIface) {
            Log(Error) << "Received data over unknown physical interface: ifindex="
                       << msg->getPhysicalIface() << LogEnd;
            continue;
        }
        if (!logicalIface) {
            Log(Error) << "Received data over unknown logical interface: ifindex="
                       << msg->getIface() << LogEnd;
            continue;
        }
        Log(Notice) << "Received " << msg->getName() << " on " << physicalIface->getFullName()
                    << hex << ", trans-id=0x" << msg->getTransID() << dec
                    << ", " << msg->countOption() << " opts:";
        SPtr<TOpt> ptrOpt;
        msg->firstOption();
        while (ptrOpt = msg->getOption() )
            Log(Cont) << " " << ptrOpt->getOptType();
        if (msg->RelayInfo_.size()) {
            Log(Cont) << " (" << logicalIface->getFullName() << ", "
                      << msg->RelayInfo_.size() << " relay(s)." << LogEnd;
        } else {
            Log(Cont) << " (non-relayed)" << LogEnd;
        }

        if (SrvCfgMgr().stateless() && ( (msg->getType()!=INFORMATION_REQUEST_MSG) &&
                                         (msg->getType()!=RELAY_FORW_MSG))) {
            Log(Warning)
                << "Stateful configuration message received while running in "
                << "the stateless mode. Message ignored." << LogEnd;
            continue;
        }
        SrvTransMgr().relayMsg(msg);
    }

    SrvCfgMgr().setPerformanceMode(false);
    SrvAddrMgr().dump();

    SrvIfaceMgr().closeSockets();
    Log(Notice) << "Bye bye." << LogEnd;
}
Exemple #28
0
bool TAddrMgr::addPrefix(SPtr<TAddrClient> client, SPtr<TDUID> duid , SPtr<TIPv6Addr> addr,
                          const std::string& ifname, int ifindex, unsigned long IAID,
                         unsigned long T1, unsigned long T2,
                         SPtr<TIPv6Addr> prefix, unsigned long pref, unsigned long valid,
                         int length, bool quiet) {
    if (!prefix) {
        Log(Error) << "Attempt to add null prefix failed." << LogEnd;
        return false;
    }

    if (!client) {
        Log(Error) << "Unable to add prefix, client not defined." << LogEnd;
        return false;
    }

    // find this PD
    SPtr <TAddrIA> ptrPD;
    client->firstPD();
    while ( ptrPD = client->getPD() ) {
        if ( ptrPD->getIAID() == IAID)
            break;
    }

    // have we found this PD?
    if (!ptrPD) {
        ptrPD = new TAddrIA(ifname, ifindex, IATYPE_PD, addr, duid, T1, T2, IAID);

        /// @todo: This setState() was used on reconfigure branch, but not on master
        ptrPD->setState(STATE_CONFIGURED);

        client->addPD(ptrPD);
        if (!quiet)
            Log(Debug) << "PD: Adding PD (iaid=" << IAID << ") to addrDB." << LogEnd;
    }

    ptrPD->setT1(T1);
    ptrPD->setT2(T2);

    SPtr <TAddrPrefix> ptrPrefix;
    ptrPD->firstPrefix();
    while ( ptrPrefix = ptrPD->getPrefix() ) {
        if (*ptrPrefix->get()==*prefix)
            break;
    }

    // address already exists
    if (ptrPrefix) {
        Log(Warning) << "PD: Prefix " << ptrPrefix->get()->getPlain() << "/" << ptrPrefix->getLength()
                     << " is already assigned to this PD." << LogEnd;
        return false;
    }

    // add address
    ptrPD->addPrefix(prefix, pref, valid, length);
    if (!quiet)
        Log(Debug) << "PD: Adding " << prefix->getPlain()
                   << " prefix to PD (iaid=" << IAID
                   << ") to addrDB." << LogEnd;
    ptrPD->setDUID(duid);
    return true;
}
Exemple #29
0
bool TClntCfgMgr::validateAddr(SPtr<TClntCfgIface> ptrIface,
                               SPtr<TClntCfgIA> ptrIA,
                               SPtr<TClntCfgAddr> ptrAddr) {
    SPtr<TIPv6Addr> addr = ptrAddr->get();
    if ( addr && addr->linkLocal()) {
        Log(Crit) << "Address " << ptrAddr->get()->getPlain() << " specified in IA "
                  << ptrIA->getIAID() << " on the " << ptrIface->getName() << "/" << ptrIface->getID()
                  << " interface is link local." << LogEnd;
        return false;
    }
    if( ptrAddr->getPref()>ptrAddr->getValid() ) {
        Log(Crit) << "Prefered time " << ptrAddr->getPref() << " can't be lower than valid lifetime "
                  << ptrAddr->getValid() << " for IA " << ptrIA->getIAID() << " on the "
                  << ptrIface->getName() << "/" << ptrIface->getID() << " interface." << LogEnd;
        return false;
    }
    if ((unsigned long)ptrIA->getT1()>(unsigned long)ptrAddr->getValid()) {
        Log(Crit) << "Valid lifetime " << ptrAddr->getValid() << " can't be lower than T1 " <<ptrIA->getT1()
                  << "(address can't be renewed) in IA " << ptrIA->getIAID() << " on the "
                  << ptrIface->getName() << "/" << ptrIface->getName() << " interface." << LogEnd;
        return false;
    }

    return true;
}
Exemple #30
0
/*
 * opens proper (multicast or unicast) socket on interface
 */
bool TRelTransMgr::openSocket(SPtr<TRelCfgIface> cfgIface) {

    SPtr<TIfaceIface> iface = RelIfaceMgr().getIfaceByID(cfgIface->getID());
    if (!iface) {
	Log(Crit) << "Unable to find " << cfgIface->getName() << "/" << cfgIface->getID()
		  << " interface in the IfaceMgr." << LogEnd;
	return false;
    }

    SPtr<TIPv6Addr> srvUnicast = cfgIface->getServerUnicast();
    SPtr<TIPv6Addr> clntUnicast = cfgIface->getClientUnicast();
    SPtr<TIPv6Addr> addr;

    if (cfgIface->getServerMulticast() || srvUnicast) {

	iface->firstGlobalAddr();
	addr = iface->getGlobalAddr();
	if (!addr) {
	    Log(Warning) << "No global address defined on the " << iface->getFullName() << " interface."
			 << " Trying to bind link local address, but expect troubles with relaying." << LogEnd;
	    iface->firstLLAddress();
	    addr = new TIPv6Addr(iface->getLLAddress());
	}
	Log(Notice) << "Creating srv unicast (" << addr->getPlain() << ") socket on the "
		    << iface->getName() << "/" << iface->getID() << " interface." << LogEnd;
	if (!iface->addSocket(addr, DHCPSERVER_PORT, true, false)) {
	    Log(Crit) << "Proper socket creation failed." << LogEnd;
	    return false;
	}
    }

    if (cfgIface->getClientMulticast()) {
	addr = new TIPv6Addr(ALL_DHCP_RELAY_AGENTS_AND_SERVERS, true);
	Log(Notice) << "Creating clnt multicast (" << addr->getPlain() << ") socket on the "
		    << iface->getName() << "/" << iface->getID() << " interface." << LogEnd;
	if (!iface->addSocket(addr, DHCPSERVER_PORT, true, false)) {
	    Log(Crit) << "Proper socket creation failed." << LogEnd;
	    return false;
	}
    }

    if (clntUnicast) {
	addr = new TIPv6Addr(ALL_DHCP_RELAY_AGENTS_AND_SERVERS, true);
	Log(Notice) << "Creating clnt unicast (" << clntUnicast->getPlain() << ") socket on the "
		    << iface->getName() << "/" << iface->getID() << " interface." << LogEnd;
	if (!iface->addSocket(clntUnicast, DHCPSERVER_PORT, true, false)) {
	    Log(Crit) << "Proper socket creation failed." << LogEnd;
	    return false;
	}
    }

    return true;
}