Пример #1
0
int main(int argc, char **argv) {
	char * image = NULL;
	char * activity = NULL;
	switch(argc){
		case 3:
			if (strcmp(argv[1],"-in")==0){
				image= argv[2];
				activity = NULL;
			}else{
				perror("Wrong parameters");
				exit(-1);
			}
			break;
		case 5:
			if (strcmp(argv[1],"-in")==0 && strcmp(argv[3],"-z")==0){
				image= argv[2];
				activity = argv[4];
			}else{
				if (strcmp(argv[1],"-z")==0 && strcmp(argv[3],"-in")==0){
					activity = argv[2];
					image= argv[4];
				}else{
					perror("Wrong parameters");
					exit(-1);
				}
			}
			break;
		default:
			perror("Wrong parameters");
			exit(-1);
			break;
	}

	QApplication app(argc, argv);

	RenderWidget *widget = new RenderWidget(image, activity);


	QPushButton front("vorn");
	QObject::connect( &front, SIGNAL( clicked() ),
			widget, SLOT( setCameraFront() ) );
	front.show();

	QPushButton back("hinten");
	QObject::connect( &back, SIGNAL( clicked() ),
			widget, SLOT( setCameraBack() ) );
	back.show();

	QPushButton right("rechts");
	QObject::connect( &right, SIGNAL( clicked() ),
			widget, SLOT( setCameraRight() ) );
	right.show();

	QPushButton left("links");
	QObject::connect( &left, SIGNAL( clicked() ),
			widget, SLOT( setCameraLeft() ) );
	left.show();

	QPushButton top("oben");
	QObject::connect( &top, SIGNAL( clicked() ),
			widget, SLOT( setCameraTop() ) );
	top.show();

	QPushButton bottom("unten");
	QObject::connect( &bottom, SIGNAL( clicked() ),
			widget, SLOT( setCameraBottom() ) );
	bottom.show();

	widget->show();	
	return app.exec();
}
Пример #2
0
std::vector<std::experimental::filesystem::path> scan(Window& window, const std::vector<ComPtr<IShellItem>>& shell_items) {
    window.add_edge(0);
    window.add_edge(0);
    window.add_edge(1);
    window.add_edge(1);
    window.add_edge(0.5f);
    window.add_edge();
    window.add_edge();
    window.add_edge();

    const auto mx = 12.0f;
    const auto my = 8.0f;
    const auto margin = D2D1::RectF(mx, my, mx, my);
    const auto background = Colour{0xfff8f8f8};

    window.add_pane(0, 5, 2, 4, margin, false, true, background);
    window.set_progressbar_progress(0, -1.0f);

    window.add_pane(0, 4, 2, 6, margin, false, true, background);
    window.set_text(1, L"Scanning folders for images", {}, true);

    window.add_pane(0, 6, 2, 7, margin, false, true, background);
    window.add_button(2, 0, L"Cancel");

    window.add_pane(0, 1, 2, 5, margin, false, false, background);
    window.add_pane(0, 7, 2, 3, margin, false, false, background);

    std::vector<std::experimental::filesystem::path> paths;
    auto items = shell_items;

    while (!items.empty()) {
        auto item = items.back();
        items.pop_back();

        SFGAOF a;
        er = item->GetAttributes(
                 SFGAO_HIDDEN | SFGAO_FILESYSANCESTOR | SFGAO_FOLDER | SFGAO_FILESYSTEM, &a);

        // skip if not file or folder or if hidden
        if (!(a & SFGAO_FILESYSTEM || a & SFGAO_FILESYSANCESTOR) || a & SFGAO_HIDDEN)
            continue;

        if (a & SFGAO_FOLDER) {
            // folder
            ComPtr<IEnumShellItems> item_enum;
            er = item->BindToHandler(nullptr, BHID_EnumItems, IID_PPV_ARGS(&item_enum));
            ComPtr<IShellItem> i;
            while (item_enum->Next(1, &i, nullptr) == S_OK)
                items.push_back(i);
        } else {
            // file
            LPWSTR path;
            er = item->GetDisplayName(SIGDN_FILESYSPATH, &path);
            if (is_image(path))
                paths.push_back(path);
            CoTaskMemFree(path);
        }

        while (window.has_event()) {
            auto e = window.get_event();
            if (e.type == Event::Type::quit || e.type == Event::Type::button)
                return {};
        }
    }

    window.set_text(1, L"Removing duplicate paths", {}, true);
    window.has_event();

    std::sort(paths.begin(), paths.end());
    paths.erase(std::unique(paths.begin(), paths.end()), paths.end());

    window.set_text(1, L"", {}, true);
    window.has_event();

    return paths;
}
Пример #3
0
void DataTreeView::showPopup(const QPoint & pos)
{
    DataTreeViewItem * item = 0 ;
    auto items = selectedItems ();
    if(items.count() == 0) 
        return;

    QMenu menu(this);
    QMenu addMenu(this);
    vector<Action*> actions;

    if(items.count() == 1)
    {
        item = static_cast<DataTreeViewItem*>(items.back());
        uint guid = item->getGuid();
        serialization::Node* pNode = m_pDataBase->getNode(guid);

        if(pNode == nullptr)
        {
            const phantom::data& d = m_pDataBase->getData(guid);
            reflection::Class* pClass = d.type()->asClass();
            const phantom::data& owner = m_pDataBase->getComponentDataOwner(d);
            if(owner.isNull())
            {
                // Data directly removed from a Node
                //menu.addAction(new RemoveDataAction(&menu, m_pDataBase->getNode(d), d));
            }
            else
            {
                // Data first removed from its owner
                o_assert(owner.type()->asClass());

            }

            // Display/Hide action
            /*if (d.type()->isKindOf(phantom::typeOf<physic::CollisionShape>()))
            {
            menu.addAction(new DisplayDataAction(&menu, d, this));
            menu.addAction(new HideDataAction(&menu, d, this));
            }*/
        }
        else
        {
            if(pNode->getState() == serialization::Node::e_Loaded)
            {
                addMenu.setTitle("add");
                addMenu.setIcon(QIcon("resources/icons/famfamfam/add.png"));
                menu.addMenu(&addMenu);
                Action* pAction = o_new(AddNodeAction)(this, pNode, m_AddNodeActionDelegate, this);
                addMenu.addAction(pAction);
                actions.push_back(pAction);
                if(pNode != m_pDataBase->rootNode()) 
                {
                    addMenu.addSeparator();
                    for(auto it = phantom::beginModules(); it != phantom::endModules(); ++it)
                    {
                        reflection::Module* pModule = it->second;
                        for(auto it = pModule->beginPackages(); it != pModule->endPackages(); ++it)
                        {
                            QMenu* packageMenu = new QMenu;
                            reflection::Package* pPackage = *it;
                            for(auto it = pPackage->beginSources(); it != pPackage->endSources(); ++it)
                            {
                                reflection::Source* pSource = *it;
                                for(auto it = pSource->beginElements(); it != pSource->endElements(); ++it)
                                {
                                    packageMenu->setTitle(pPackage->getName().c_str());
                                    reflection::Class* pClass = (*it)->asClass();
                                    if(pClass 
                                        AND pClass->isPublic()
                                        AND NOT(pClass->testModifiers(o_private_visibility)) 
                                        AND NOT(pClass->isAbstract())
                                        AND pClass->isDefaultConstructible()
                                        AND pClass->getSingleton() == nullptr)
                                    {
                                        Action* pAction = o_new(AddDataAction)(this, pNode, pClass, m_AddDataActionDelegate, packageMenu);
                                        packageMenu->addAction(pAction);
                                        actions.push_back(pAction);
                                    }
                                }
                            }
                            if(!packageMenu->isEmpty())
                            {
                                addMenu.addMenu(packageMenu);
                            }
                        }
                    }
                    menu.addSeparator();
                    if(pNode->getParentNode()) // If it's not the root node
                    {
                        Action* pAction = o_new(UnloadNodeAction)(this, pNode, m_UnloadNodeActionDelegate, &menu);
                        menu.addAction(pAction);
                        actions.push_back(pAction);
                    }
                }

            }
            else if(pNode->getState() == serialization::Node::e_Unloaded)
            {
                Action* pAction = o_new(LoadNodeAction)(this, pNode, m_LoadNodeActionDelegate, &menu);
                menu.addAction(pAction);
                actions.push_back(pAction);
                pAction = o_new(LoadNodeAction)(this, pNode, m_RecursiveLoadNodeActionDelegate, &menu);
                menu.addAction(pAction);
                actions.push_back(pAction);
            }
        }
    }
    {
        vector<uint> guids;
        for(auto it = items.begin(); it != items.end(); ++it)
        {
            guids.push_back(((DataTreeViewItem*)(*it))->getGuid());
        }
        RemoveDataAction* pRemoveDataAction = o_new(RemoveDataAction)(this, guids, m_RemoveDataActionDelegate, &menu) ;
        menu.addAction(pRemoveDataAction);
        actions.push_back(pRemoveDataAction);
    }
    if(NOT(menu.isEmpty()))
    {
        menu.exec(QCursor::pos());
    }
    for(auto it = actions.begin(); it != actions.end(); ++it)
    {
        o_dynamic_delete *it;
    }
}
Пример #4
0
bool smart_object::near_back(complex_object target)
{
    return isless(utilities::distance(back(),target.get_position()),target.get_height()/2);
}
Пример #5
0
std::string show(const IRGS& irgs) {
  std::ostringstream out;
  auto header = [&](const std::string& str) {
    out << folly::format("+{:-^102}+\n", str);
  };

  const int32_t frameCells = resumed(irgs)
    ? 0
    : curFunc(irgs)->numSlotsInFrame();
  auto const stackDepth = irgs.irb->fs().bcSPOff().offset - frameCells;
  assertx(stackDepth >= 0);
  auto spOffset = stackDepth;
  auto elem = [&](const std::string& str) {
    out << folly::format("| {:<100} |\n",
                         folly::format("{:>2}: {}",
                                       stackDepth - spOffset, str));
    assertx(spOffset > 0);
    --spOffset;
  };

  auto fpi = curFunc(irgs)->findFPI(bcOff(irgs));
  auto checkFpi = [&]() {
    if (fpi && spOffset + frameCells == fpi->m_fpOff) {
      auto fpushOff = fpi->m_fpushOff;
      auto after = fpushOff + instrLen(curUnit(irgs)->at(fpushOff));
      std::ostringstream msg;
      msg << "ActRec from ";
      curUnit(irgs)->prettyPrint(
        msg,
        Unit::PrintOpts().range(fpushOff, after)
                         .noLineNumbers()
                         .indent(0)
                         .noFuncs()
      );
      auto msgStr = msg.str();
      assertx(msgStr.back() == '\n');
      msgStr.erase(msgStr.size() - 1);
      for (unsigned i = 0; i < kNumActRecCells; ++i) elem(msgStr);
      fpi = fpi->m_parentIndex != -1
        ? &curFunc(irgs)->fpitab()[fpi->m_parentIndex]
        : nullptr;
      return true;
    }
    return false;
  };

  header(folly::format(" {} stack element(s): ",
                       stackDepth).str());
  assertx(spOffset <= curFunc(irgs)->maxStackCells());

  for (auto i = 0; i < spOffset; ) {
    if (checkFpi()) {
      i += kNumActRecCells;
      continue;
    }

    auto const spRel = offsetFromIRSP(irgs, BCSPRelOffset{i});
    auto const stkTy  = irgs.irb->stack(spRel, DataTypeGeneric).type;
    auto const stkVal = irgs.irb->stack(spRel, DataTypeGeneric).value;

    std::string elemStr;
    if (stkTy == TStkElem) {
      elemStr = "unknown";
    } else if (stkVal) {
      elemStr = stkVal->inst()->toString();
    } else {
      elemStr = stkTy.toString();
    }

    auto const irSPRel = BCSPRelOffset{i}
      .to<FPInvOffset>(irgs.irb->fs().bcSPOff());
    auto const predicted = predictedType(irgs, Location::Stack { irSPRel });

    if (predicted < stkTy) {
      elemStr += folly::sformat(" (predict: {})", predicted);
    }
    elem(elemStr);
    ++i;
  }
  header("");
  out << "\n";

  header(folly::format(" {} local(s) ",
                       curFunc(irgs)->numLocals()).str());
  for (unsigned i = 0; i < curFunc(irgs)->numLocals(); ++i) {
    auto const localValue = irgs.irb->local(i, DataTypeGeneric).value;
    auto const localTy = localValue ? localValue->type()
                                    : irgs.irb->local(i, DataTypeGeneric).type;
    auto str = localValue ? localValue->inst()->toString()
                          : localTy.toString();
    auto const predicted = irgs.irb->fs().local(i).predictedType;
    if (predicted < localTy) str += folly::sformat(" (predict: {})", predicted);

    if (localTy <= TBoxedCell) {
      auto const pred = irgs.irb->predictedLocalInnerType(i);
      if (pred != TBottom) {
        str += folly::sformat(" (predict inner: {})", pred.toString());
      }
    }

    out << folly::format("| {:<100} |\n",
                         folly::format("{:>2}: {}", i, str));
  }
  header("");
  return out.str();
}
Пример #6
0
void top_screen()
{
	//Texture load
	sf::Texture button_back;
	button_back.loadFromFile("data/button0.png");

	button back(sf::Vector2f(150, 70), sf::Vector2f(75, 35), "BACK", font, 30, sf::Color::Black, button_back);
	button down(sf::Vector2f(150, 70), sf::Vector2f(WIDTH - 75, HEIGHT - 35), "DOWN", font, 30, sf::Color::Black, button_back);
	button up(sf::Vector2f(150, 70), sf::Vector2f(WIDTH - 75, 35), "UP", font, 30, sf::Color::Black, button_back);
	button test(sf::Vector2f(150, 70), sf::Vector2f(WIDTH / 2, HEIGHT / 2), "TEST", font, 30, sf::Color::Black, button_back);

	sf::View TView;
	int pos_y = 0;
	TView.reset(sf::FloatRect(0, pos_y, WIDTH, HEIGHT));
	TView.setViewport(sf::FloatRect(0, 0, 1, 1));
	
	while (States == Top)
	{
		sf::Event event;
		while (windows.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				States = End;
			if (event.type == sf::Event::MouseButtonPressed && event.key.code == sf::Mouse::Left)
			{
				if (back.mouse_over_button(windows))
					States = Start;
				if (down.mouse_over_button(windows))
				{
					pos_y += 50;
					std::cout << pos_y << std::endl;
					TView.reset(sf::FloatRect(0, pos_y, WIDTH, HEIGHT));
				}
				if (up.mouse_over_button(windows))
				{
					pos_y += 50;
					std::cout << pos_y << std::endl;
					TView.reset(sf::FloatRect(0, pos_y, WIDTH, HEIGHT));
				}

			}
			if (event.type == sf::Event::MouseWheelMoved)
			{
				if (event.mouseWheel.delta == 1)		//rolka do góry
				{
					pos_y -= 50;
					TView.reset(sf::FloatRect(0, pos_y, WIDTH, HEIGHT));
				}
				else			//rolka na dó³
				{
					pos_y += 50;
					TView.reset(sf::FloatRect(0, pos_y, WIDTH, HEIGHT));
				}

				// display number of ticks mouse wheel has moved
				//std::cout << event.mouseWheel.delta << '\n';
			}
		} //while
		windows.clear(sf::Color::Green);

		windows.setView(TView);		//Nowy widok
		windows.draw(rank);
		
		windows.setView(windows.getDefaultView());		//Koniec elementów dla nowego widoku, rysujemy elementy na które widok nie ma wp³ywu

		windows.draw(back);
		windows.draw(down);		//Do przesuwania widoku w dó³
		windows.draw(up);		//Do przesuwania widoku w górê

		windows.display();
	} //while
}
Пример #7
0
 /**
  * Checks whether the first and last node in the collection have the
  * same ID. The locations are not checked.
  *
  * @pre @code !empty() @endcode
  */
 bool ends_have_same_id() const noexcept {
     return front().ref() == back().ref();
 }
Пример #8
0
  std::shared_ptr<BaseEncodedSegment> _on_encode(const AnySegmentIterable<pmr_string> segment_iterable,
                                                 const PolymorphicAllocator<pmr_string>& allocator) {
    /**
     * First iterate over the values for two reasons.
     * 1) If all the strings are empty LZ4 will try to compress an empty vector which will cause a segmentation fault.
     *    In this case we can and need to do an early exit.
     * 2) Sum the length of the strings to improve the performance when copying the data to the char vector.
     */
    auto num_chars = size_t{0u};
    segment_iterable.with_iterators([&](auto it, auto end) {
      for (; it != end; ++it) {
        if (!it->is_null()) {
          num_chars += it->value().size();
        }
      }
    });

    // copy values and null flags from value segment
    auto values = pmr_vector<char>{allocator};
    values.reserve(num_chars);
    auto null_values = pmr_vector<bool>{allocator};

    /**
     * If the null value vector only contains the value false, then the value segment does not have any row value that
     * is null. In that case, we don't store the null value vector to reduce the LZ4 segment's memory footprint.
     */
    auto segment_contains_null = false;

    /**
     * These offsets mark the beginning of strings (and therefore end of the previous string) in the data vector.
     * These offsets are character offsets. The string at position 0 starts at the offset stored at position 0, which
     * will always be 0.
     * Its exclusive end is the offset stored at position 1 (i.e., offsets[1] - 1 is the last character of the string
     * at position 0).
     * In case of the last string its end is determined by the end of the data vector.
     *
     * The offsets are stored as 32 bit unsigned integer as opposed to 64 bit (size_t) so that they can later be
     * compressed via vector compression.
     */
    auto offsets = pmr_vector<uint32_t>{allocator};

    /**
     * These are the lengths of each string. They are needed to train the zstd dictionary.
     */
    auto string_samples_lengths = pmr_vector<size_t>{allocator};

    segment_iterable.with_iterators([&](auto it, auto end) {
      const auto segment_size = std::distance(it, end);

      null_values.resize(segment_size);
      offsets.resize(segment_size);
      string_samples_lengths.resize(segment_size);

      auto offset = uint32_t{0u};
      // iterate over the iterator to access the values and increment the row index to write to the values and null
      // values vectors
      auto row_index = size_t{0};
      for (; it != end; ++it) {
        const auto segment_element = *it;
        const auto contains_null = segment_element.is_null();
        null_values[row_index] = contains_null;
        segment_contains_null = segment_contains_null || contains_null;
        offsets[row_index] = offset;
        auto sample_size = size_t{0u};
        if (!contains_null) {
          const auto value = segment_element.value();
          const auto string_length = value.size();
          values.insert(values.cend(), value.begin(), value.end());
          Assert(string_length <= std::numeric_limits<uint32_t>::max(),
                 "The size of string row value exceeds the maximum of uint32 in LZ4 encoding.");
          offset += static_cast<uint32_t>(string_length);
          sample_size = string_length;
        }

        string_samples_lengths[row_index] = sample_size;
        ++row_index;
      }
    });

    auto optional_null_values = segment_contains_null ? std::optional<pmr_vector<bool>>{null_values} : std::nullopt;

    /**
     * If the input only contained null values and/or empty strings we don't need to compress anything (and LZ4 will
     * cause an error). We can also throw away the offsets, since they won't be used for decompression.
     * We can do an early exit and return the (not encoded) segment.
     */
    if (num_chars == 0) {
      auto empty_blocks = pmr_vector<pmr_vector<char>>{allocator};
      auto empty_dictionary = pmr_vector<char>{};
      return std::allocate_shared<LZ4Segment<pmr_string>>(allocator, std::move(empty_blocks),
                                                          std::move(optional_null_values), std::move(empty_dictionary),
                                                          nullptr, _block_size, 0u, 0u, null_values.size());
    }

    // Compress the offsets with a vector compression method to reduce the memory footprint of the LZ4 segment.
    auto compressed_offsets = compress_vector(offsets, vector_compression_type(), allocator, {offsets.back()});

    /**
     * Pre-compute a zstd dictionary if the input data is split among multiple blocks. This dictionary allows
     * independent compression of the blocks, while maintaining a good compression ratio.
     * If the input data fits into a single block, training of a dictionary is skipped.
     */
    const auto input_size = values.size();
    auto dictionary = pmr_vector<char>{allocator};
    if (input_size > _block_size) {
      dictionary = _train_dictionary(values, string_samples_lengths);
    }

    /**
     * Compress the data and calculate the last block size (which may vary from the block size of the previous blocks)
     * and the total compressed size. The size of the last block is needed for decompression. The total compressed size
     * is pre-calculated instead of iterating over all blocks when the memory consumption of the LZ4 segment is
     * estimated.
     */
    auto lz4_blocks = pmr_vector<pmr_vector<char>>{allocator};
    _compress(values, lz4_blocks, dictionary);

    auto last_block_size = input_size % _block_size != 0 ? input_size % _block_size : _block_size;

    auto total_compressed_size = size_t{0u};
    for (const auto& compressed_block : lz4_blocks) {
      total_compressed_size += compressed_block.size();
    }

    return std::allocate_shared<LZ4Segment<pmr_string>>(
        allocator, std::move(lz4_blocks), std::move(optional_null_values), std::move(dictionary),
        std::move(compressed_offsets), _block_size, last_block_size, total_compressed_size, null_values.size());
  }
Пример #9
0
	static int load()
	{
		FreeTypeDecoder::initialize();

		ShowWindow(GetConsoleWindow(), SW_HIDE);

		Graphics3D * graphics = D3DGraphics::initialize();
		FinalAction finally(D3DGraphics::free);

		graphics->setClearColor({0.0f, 0.0f, 0.0f});

		Handle<Window> window(graphics, 0, 0, 1024, 758);
		Handle<WindowBackground> back(window);
		back->name = "Background";

		Handle<Panel> frame(back);
		frame->setPlacement({0.5f, 0.5f, 0.5f, 0.5f}, {-300, -300, 300, 300});
		frame << [](const DrawParams & p)
		{
			p.graphics->setColor({0.25f, 0.25f, 0.25f});
			p.graphics->rectangle(p.clipped);
		};

		Handle<Panel> frame0(frame);
		frame0->setPlacement(ModelMask::FullSize, {4, 4, -4, -4});
		frame0 << [](const DrawParams & p)
		{
			p.graphics->setColor({0.5f, 0.5f, 0.5f});
			p.graphics->rectangle(p.clipped);
		};

		Handle<Panel> frame1(frame0);
		frame1->setPlacement(ModelMask::FullSize, {3, 3, -3, -3});
		frame1 << [](const DrawParams & p)
		{
			p.graphics->setColor({0.75f, 0.75f, 0.75f});
			p.graphics->rectangle(p.clipped);
		};

		Handle<Panel> frame2(frame1);
		frame2->setPlacement(ModelMask::FullSize, {2, 2, -2, -2});
		frame2 << [](const DrawParams & p)
		{
			p.graphics->setColor({1.0f, 1.0f, 1.0f});
			p.graphics->rectangle(p.clipped);
		};

		Handle<Panel> panel(frame2);
		panel->setPlacement(ModelMask::FullSize, {1, 1, -1, -1});
		panel << [](const DrawParams & p)
		{
			p.graphics->setColor({0.0f, 0.0f, 0.0f});
			p.graphics->rectangle(p.clipped);
		};

		auto arial = Font::load("arial.ttf");

		graphics->bind(arial);
		graphics->setFontSize(16);

		Handle<String> project_name("Independence");
		Handle<Panel> project_name_panel(back);
		project_name_panel->setPlacement(10, 10, 0, 0);
		project_name_panel->setSize(graphics->getTextSize(*project_name));

		project_name_panel << [arial, project_name](const DrawParams & p)
		{
			auto & graphics = p.graphics;
			auto & region = p.region;
			graphics->bind(arial);
			graphics->setFontSize(16);

			p.graphics->setColor({1.0f, 1.0f, 1.0f});
			graphics->draw(region.left, region.top, *project_name);
		};

		Handle<String> text("Press Esc to quit");
		Handle<Panel> text_panel(back);
		text_panel->setPlacement(ModelMask::RightTop, {0, 10, -10, 0});
		text_panel->setSize(graphics->getTextSize(*text));

		text_panel << [arial, text](const DrawParams & p)
		{
			auto & graphics = p.graphics;
			auto & region = p.region;
			graphics->bind(arial);
			graphics->setFontSize(16);

			p.graphics->setColor({1.0f, 1.0f, 1.0f});
			graphics->draw(region.left, region.top, *text);
		};

		Handle<FpsCounter> counter(emptiness);

		Handle<Panel> fps_panel(back);
		fps_panel->setPlacement({0.5f, 1.0f, 0.5f, 1.0f}, {-40, -30, 40, -10});
		fps_panel << [counter, arial](const DrawParams & p)
		{
			auto graphics = p.graphics;
			graphics->bind(arial);
			graphics->setFontSize(16);

			auto text = String(counter->get()) + " fps";
			auto textSize = graphics->getTextSize(text);
			int left = p.region.left + (p.region.width() - textSize.x) / 2;
			int top = p.region.top + (p.region.height() - textSize.y) / 2;

			p.graphics->setColor({1.0f, 1.0f, 1.0f});
			graphics->draw(left, top, text);
		};
		
		Handle<Scene> scene(panel);
		scene->append<Snake>(color(1.0f, 0.0f, 0.0f));
		scene->append<Snake>(color(1.0f, 0.5f, 0.0f));
		scene->append<Snake>(color(1.0f, 1.0f, 0.0f));
		scene->append<Snake>(color(0.0f, 1.0f, 0.0f));
		scene->append<Snake>(color(0.0f, 1.0f, 1.0f));
		scene->append<Snake>(color(0.0f, 0.0f, 1.0f));
		scene->append<Snake>(color(0.5f, 0.0f, 1.0f));

		connect(*window, onWindowKeyDown);

		window->setBorderStyle(BorderStyle::Static);
		window->setCaption("Independence");
		window->centralize();
		window->show();

		ThreadLoop::add(processWindowMessage);
		ThreadLoop::add([scene, window, counter, fps_panel] () mutable
		{
			//std::this_thread::sleep_for(1ms);
			
			counter->next();
			window->invalidate(fps_panel);
			
			scene->invalidate();
			window->validate();

			return 0;
		});

		ThreadLoop::run();

		return 0;
	}
Пример #10
0
void Emulator::Load()
{
	Stop();

	try
	{
		Init();

		if (!fs::is_file(m_path))
		{
			LOG_ERROR(LOADER, "File not found: %s", m_path);
			return;
		}

		const std::string& elf_dir = fs::get_parent_dir(m_path);

		if (IsSelf(m_path))
		{
			const std::size_t elf_ext_pos = m_path.find_last_of('.');
			const std::string& elf_ext = fmt::to_upper(m_path.substr(elf_ext_pos != -1 ? elf_ext_pos : m_path.size()));
			const std::string& elf_name = m_path.substr(elf_dir.size());

			if (elf_name.compare(elf_name.find_last_of("/\\", -1, 2) + 1, 9, "EBOOT.BIN", 9) == 0)
			{
				m_path.erase(m_path.size() - 9, 1); // change EBOOT.BIN to BOOT.BIN
			}
			else if (elf_ext == ".SELF" || elf_ext == ".SPRX")
			{
				m_path.erase(m_path.size() - 4, 1); // change *.self to *.elf, *.sprx to *.prx
			}
			else
			{
				m_path += ".decrypted.elf";
			}

			if (!DecryptSelf(m_path, elf_dir + elf_name))
			{
				LOG_ERROR(LOADER, "Failed to decrypt %s", elf_dir + elf_name);
				return;
			}
		}

		ResetInfo();

		LOG_NOTICE(LOADER, "Path: %s", m_path);

		// Load custom config
		if (fs::file cfg_file{ m_path + ".yml" })
		{
			LOG_NOTICE(LOADER, "Custom config: %s.yml", m_path);
			cfg::root.from_string(cfg_file.to_string());
		}

		const fs::file elf_file(m_path);
		ppu_exec_object ppu_exec;
		ppu_prx_object ppu_prx;
		spu_exec_object spu_exec;
		arm_exec_object arm_exec;

		if (!elf_file)
		{
			LOG_ERROR(LOADER, "Failed to open %s", m_path);
			return;
		}
		else if (ppu_exec.open(elf_file) == elf_error::ok)
		{
			// PS3 executable
			m_status = Ready;
			vm::ps3::init();

			if (m_elf_path.empty())
			{
				m_elf_path = "/host_root/" + m_path;
				LOG_NOTICE(LOADER, "Elf path: %s", m_elf_path);
			}

			// Load PARAM.SFO
			const auto _psf = psf::load_object(fs::file(elf_dir + "/../PARAM.SFO"));
			m_title = psf::get_string(_psf, "TITLE", m_path);
			m_title_id = psf::get_string(_psf, "TITLE_ID");
			fs::get_data_dir(m_title_id, m_path);

			LOG_NOTICE(LOADER, "Title: %s", GetTitle());
			LOG_NOTICE(LOADER, "Serial: %s", GetTitleID());

			// Mount all devices
			const std::string& emu_dir_ = g_cfg_vfs_emulator_dir;
			const std::string& emu_dir = emu_dir_.empty() ? fs::get_executable_dir() : emu_dir_;
			const std::string& bdvd_dir = g_cfg_vfs_dev_bdvd;
			const std::string& home_dir = g_cfg_vfs_app_home;

			vfs::mount("dev_hdd0", fmt::replace_all(g_cfg_vfs_dev_hdd0, "$(EmulatorDir)", emu_dir));
			vfs::mount("dev_hdd1", fmt::replace_all(g_cfg_vfs_dev_hdd1, "$(EmulatorDir)", emu_dir));
			vfs::mount("dev_flash", fmt::replace_all(g_cfg_vfs_dev_flash, "$(EmulatorDir)", emu_dir));
			vfs::mount("dev_usb", fmt::replace_all(g_cfg_vfs_dev_usb000, "$(EmulatorDir)", emu_dir));
			vfs::mount("dev_usb000", fmt::replace_all(g_cfg_vfs_dev_usb000, "$(EmulatorDir)", emu_dir));
			vfs::mount("app_home", home_dir.empty() ? elf_dir + '/' : fmt::replace_all(home_dir, "$(EmulatorDir)", emu_dir));

			// Mount /dev_bdvd/ if necessary
			if (bdvd_dir.empty() && fs::is_file(elf_dir + "/../../PS3_DISC.SFB"))
			{
				const auto dir_list = fmt::split(elf_dir, { "/", "\\" });

				// Check latest two directories
				if (dir_list.size() >= 2 && dir_list.back() == "USRDIR" && *(dir_list.end() - 2) == "PS3_GAME")
				{
					vfs::mount("dev_bdvd", elf_dir.substr(0, elf_dir.length() - 15));
				}
				else
				{
					vfs::mount("dev_bdvd", elf_dir + "/../../");
				}

				LOG_NOTICE(LOADER, "Disc: %s", vfs::get("/dev_bdvd"));
			}
			else if (bdvd_dir.size())
			{
				vfs::mount("dev_bdvd", fmt::replace_all(bdvd_dir, "$(EmulatorDir)", emu_dir));
			}

			// Mount /host_root/ if necessary
			if (g_cfg_vfs_allow_host_root)
			{
				vfs::mount("host_root", {});
			}

			LOG_NOTICE(LOADER, "Used configuration:\n%s\n", cfg::root.to_string());

			ppu_load_exec(ppu_exec);

			Emu.GetCallbackManager().Init();
			fxm::import<GSRender>(PURE_EXPR(Emu.GetCallbacks().get_gs_render())); // TODO: must be created in appropriate sys_rsx syscall
		}
		else if (ppu_prx.open(elf_file) == elf_error::ok)
		{
			// PPU PRX (experimental)
			m_status = Ready;
			vm::ps3::init();
			ppu_load_prx(ppu_prx);
			GetCallbackManager().Init();
		}
		else if (spu_exec.open(elf_file) == elf_error::ok)
		{
			// SPU executable (experimental)
			m_status = Ready;
			vm::ps3::init();
			spu_load_exec(spu_exec);
		}
		else if (arm_exec.open(elf_file) == elf_error::ok)
		{
			// ARMv7 executable
			m_status = Ready;
			vm::psv::init();
			arm_load_exec(arm_exec);
		}
		else
		{
			LOG_ERROR(LOADER, "Invalid or unsupported file format: %s", m_path);

			LOG_WARNING(LOADER, "** ppu_exec -> %s", ppu_exec.get_error());
			LOG_WARNING(LOADER, "** ppu_prx  -> %s", ppu_prx.get_error());
			LOG_WARNING(LOADER, "** spu_exec -> %s", spu_exec.get_error());
			LOG_WARNING(LOADER, "** arm_exec -> %s", arm_exec.get_error());
			return;
		}

		debug::autopause::reload();
		SendDbgCommand(DID_READY_EMU);
		if (g_cfg_autostart) Run();
	}
	catch (const std::exception& e)
	{
		LOG_FATAL(LOADER, "%s thrown: %s", typeid(e).name(), e.what());
		Stop();
	}
}
Пример #11
0
void HitAndMissSampling::generate_particles( const kvs::StructuredVolumeObject* volume  )
{
    // Set the geometry arrays.
    const size_t max_nparticles = volume->numberOfNodes();
    std::vector<kvs::Real32> coords;  coords.reserve( max_nparticles * 3 );
    std::vector<kvs::UInt8>  colors;  colors.reserve( max_nparticles * 3 );
    std::vector<kvs::Real32> normals; normals.reserve( max_nparticles * 3 );

    // Aliases.
    const kvs::Vector3ui resolution = volume->resolution();
    const size_t line_size  = volume->numberOfNodesPerLine();
    const size_t slice_size = volume->numberOfNodesPerSlice();
    const T* values = reinterpret_cast<const T*>( volume->values().data() );

    kvs::MersenneTwister R; // Random number generator
    size_t index = 0;     // index of voxel
    for ( size_t k = 0; k < resolution.z(); k++ )
    {
        for ( size_t j = 0; j < resolution.y(); j++ )
        {
            for ( size_t i = 0; i < resolution.x(); i++, index++ )
            {
                // Rejection.
                const size_t voxel_value = values[ index ];
                if( R() < BaseClass::opacityMap()[ voxel_value ] )
                {
                    // Set coordinate value.
                    coords.push_back( static_cast<kvs::Real32>(i) );
                    coords.push_back( static_cast<kvs::Real32>(j) );
                    coords.push_back( static_cast<kvs::Real32>(k) );

                    // Set color value.
                    colors.push_back( BaseClass::colorMap()[ voxel_value ].r() );
                    colors.push_back( BaseClass::colorMap()[ voxel_value ].g() );
                    colors.push_back( BaseClass::colorMap()[ voxel_value ].b() );

                    // Calculate a normal vector at the node(i,j,k).
                    kvs::Vector3ui front( index, index, index ); // front index
                    kvs::Vector3ui back( index, index, index );  // back index

                    if(      i == 0                  ) front.x() += 1;
                    else if( i == resolution.x() - 1 ) back.x()  -= 1;
                    else{ front.x() += 1; back.x() -= 1; }

                    if(      j == 0                  ) front.y() += line_size;
                    else if( j == resolution.y() - 1 ) back.y()  -= line_size;
                    else{ front.y() += line_size; back.y() -= line_size; }

                    if(      k == 0                  ) front.z() += slice_size;
                    else if( k == resolution.z() - 1 ) back.z()  -= slice_size;
                    else{ front.z() += slice_size; back.z() -= slice_size; }

                    // Set normal vector.
                    normals.push_back( static_cast<kvs::Real32>( values[ front.x() ] - values[ back.x() ] ) );
                    normals.push_back( static_cast<kvs::Real32>( values[ front.y() ] - values[ back.y() ] ) );
                    normals.push_back( static_cast<kvs::Real32>( values[ front.z() ] - values[ back.z() ] ) );
                }
            } // end of i-loop
        } // end of j-loop
    } // end of k-loop

    SuperClass::setCoords( kvs::ValueArray<kvs::Real32>( coords ) );
    SuperClass::setColors( kvs::ValueArray<kvs::UInt8>( colors ) );
    SuperClass::setNormals( kvs::ValueArray<kvs::Real32>( normals ) );
    SuperClass::setSize( 1.0f );
}
Пример #12
0
void ProjectSplicedRoi::writeCurrentGroup()
{
    if (verbosity >= 3)
        std::cerr << "Writing current group (" << currentGroup << ": " << groupNames[currentGroup] << ")\n";

    // Collect all begin/end position pairs for GFF records with the grouping key set to currentName.
    seqan::Reference<TNameStore>::Type currentName = groupNames[currentGroup];
    seqan::String<seqan::Pair<int, int> > pairs;
    typedef std::list<seqan::StringSet<seqan::CharString> >::iterator TGroupsIter;
    TGroupsIter itG = gffGroups.begin();
    typedef std::list<seqan::GffRecord>::iterator TGffIter;
    for (TGffIter it = gffRecords.begin(); it != gffRecords.end(); ++it, ++itG)
    {
        if (std::find(begin(*itG, seqan::Standard()), end(*itG, seqan::Standard()), currentName) == end(*itG))
            continue;  // No match.
        appendValue(pairs, seqan::Pair<int, int>(it->beginPos, it->endPos));
    }

    if (verbosity >= 3)
    {
        std::cerr << "Has the following " << length(pairs) << " GFF intervals\n";
        for (unsigned i = 0; i < length(pairs); ++i)
            std::cerr << "  " << pairs[i].i1 << "\t" << pairs[i].i2 << "\n";
    }

    if (empty(pairs))
        return;  // Nothing to do.

    // Sort the begin/end positions by begin position.
    std::sort(begin(pairs, seqan::Standard()), end(pairs, seqan::Standard()));
    // Compute prefix sums of positions in result.
    seqan::String<int> beginPositions;
    appendValue(beginPositions, 0);
    for (unsigned i = 0; i < length(pairs); ++i)
        appendValue(beginPositions, back(beginPositions) + (pairs[i].i2 - pairs[i].i1));

    if (verbosity >= 3)
    {
        std::cerr << "Begin positions:";
        for (unsigned i = 0; i < length(beginPositions); ++i)
            std::cerr << " " << beginPositions[i];
        std::cerr << "\n";
    }

    // TODO(holtgrew): Check that the intervals in pairs don't overlap?

    // Create resulting ROI.
    seqan::RoiRecord record;
    record.ref = gffRecords.front().ref;
    record.beginPos = front(pairs).i1;
    record.endPos = back(pairs).i2;
    record.strand = gffRecords.front().strand;
    record.name = currentName; // TODO(holtgrew): Make unique.
    record.len = back(beginPositions);
    record.countMax = 0;
    resize(record.count, record.len, 0);

    // Project the ROI counts on the GFF intervals.
    typedef std::list<seqan::RoiRecord>::iterator TRoiIter;
    for (TRoiIter it = roiRecords.begin(); it != roiRecords.end(); ++it)
    {
        for (unsigned i = 0; i < length(pairs); ++i)
        {
            if (verbosity >= 3)
            {
                std::cerr << "ROI record\n  ";
                writeRecord(std::cerr, *it, seqan::Roi());
            }
            if (!(pairs[i].i1 < it->endPos && it->beginPos < pairs[i].i2))
                continue;
            if (verbosity >= 3)
                std::cerr << "=> overlapping\n";

            // Begin and end position of projected interval on contig.
            int beginPosI = std::max(it->beginPos, pairs[i].i1);
            int endPosI = std::min(it->endPos, pairs[i].i2);
            if (beginPosI >= endPosI)
                continue;  // Skip
            // Begin position in record.count.
            int offsetR = beginPositions[i] + beginPosI - pairs[i].i1;
            SEQAN_ASSERT_GEQ(offsetR, 0);
            // Begin position in it->count.
            int offsetC = beginPosI - it->beginPos;
            SEQAN_ASSERT_GEQ(offsetC, 0);

            if (verbosity >= 3)
                std::cerr << ">>> beginPosI = " << beginPosI << "\n"
                          << ">>> endPosI   = " << endPosI << "\n"
                          << ">>> offsetR   = " << offsetR << "\n"
                          << ">>> offsetC   = " << offsetC << "\n"
                          << ">>> beginPositions[i] = " << beginPositions[i] << "\n"
                          << ">>> it->beginPos      = " << it->beginPos << "\n";

            SEQAN_ASSERT_LEQ(offsetR + endPosI - beginPosI, (int)record.len);
            SEQAN_ASSERT_LEQ(offsetC + endPosI - beginPosI, (int)length(it->count));

            if (verbosity >= 3)
            {
                std::cerr << "PROJECTING [" << offsetC << ", " << (offsetC + endPosI - beginPosI) << ") TO "
                          << "[" << offsetR << ", " << offsetR + endPosI - beginPosI << ")\n";
            }

            for (int i = 0, len = endPosI - beginPosI; i < len; ++i)
                record.count[offsetR + i] = it->count[offsetC + i];
        }
    }
    for (unsigned i = 0; i < length(record.count); ++i)
        record.countMax = std::max(record.countMax, record.count[i]);

    writeRecord(roiFileOut, record);
    if (verbosity >= 3)
        std::cerr << "RESULT\t record.ref == " << record.ref << "\n";
}
Пример #13
0
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    static TCHAR szAppName[] = TEXT("SampleSRS");
    static int xBlock, yBlock;
    static HINSTANCE hInstance;
    static RECT rect_time1, rect_time2, rect_bk;
    static HBRUSH hBrushRed;

    SetRect(&rect_time1, PLAYER1_TIME_X1 - 10, PLAYER1_TIME_Y1 - 10, PLAYER1_TIME_X2, PLAYER1_TIME_Y2);
    SetRect(&rect_time2, PLAYER2_TIME_X1, PLAYER2_TIME_Y1 - 10, PLAYER2_TIME_X2 + 10, PLAYER2_TIME_Y2 - 10);
    SetRect(&rect_bk, 0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);

    switch(msg) {
    case WM_CREATE:
        hInstance = ((LPCREATESTRUCT)lParam)->hInstance;
        DrawUI(hwnd, &lParam, hInstance);

        /* Load Image (Background && Chessboard) */
        LoadRc(hInstance);

        hBrushRed = CreateSolidBrush(RGB(255, 0, 0));

        MessageBox(hwnd, "Load Resource Successfully", "Info", MB_OK);
        break;
    case WM_SIZE:
        xBlock = (BOARD_X2 - BOARD_X1) / 3;
        yBlock = (BOARD_Y2 - BOARD_Y1) / 3;
        break;
    case WM_PAINT:
        InitRc(hwnd);
        break;
    case WM_LBUTTONDOWN:
        /* */
        break;
    case WM_TIMER:
        if (is_pause == FALSE) {
            if (n_chess & 1) {
                InvalidateRect(hwnd, &rect_time2, TRUE);
                DrawTime(hwnd, hBrushRed);
            } else {
                InvalidateRect(hwnd, &rect_time1, TRUE);
                DrawTime(hwnd, hBrushRed);
            }
        }
        break;
    case WM_COMMAND:
        log_to_text("Button Pressed: %d\n", LOWORD(wParam));

        if (LOWORD(wParam) == BTN_PLAYER1_RECORD) { /* Speech Recogniton for player 1*/
            player1_or_player2 = PLAYER1;
            ControlRecord(hwnd, hInstance, PLAYER1);

        } else if (LOWORD(wParam) == BTN_PLAYER2_RECORD) { /* Speech Recogniton for player 2*/
            player1_or_player2 = PLAYER2;
            ControlRecord(hwnd, hInstance, PLAYER2);

        } else if (LOWORD(wParam) == BTN_RESET) { /* Reset Button */
            InitGame(hwnd);

        } else if (LOWORD(wParam) == BTN_PAUSE) {  /* Pause Button */
            if (is_pause) {
                SetWindowText(GetDlgItem(hwnd, BTN_PAUSE), S_PAUSE);
            } else {
                SetWindowText(GetDlgItem(hwnd, BTN_PAUSE), S_CONTINUE);
            } 
            is_pause = !is_pause;

        } else if (LOWORD(wParam) == BTN_REDO) { /* Redo Button */
            back(hwnd, hInstance);
            GameCon();
        } else if (LOWORD(wParam) == BTN_EXIT) { /* Exit Button */
            if (IDYES == AskConfirmation(hwnd)) {
                DestroyWindow(hwnd) ;
            }
        }
        break;
    case WM_DESTROY:
        KillTimer(hwnd, ID1_TIMER);
		KillTimer(hwnd, ID2_TIMER);
        DeleteObject(hBkBitmap);
        DeleteObject(hBdBitmap);
        PostQuitMessage(0);
        break;
    }

    return DefWindowProc(hwnd, msg, wParam, lParam);
}
Пример #14
0
arma::vec CustomKinestheticTeacher::getNextDifferentialCommand(Eigen::MatrixXd jacobian,arma::vec currentJointState, ControllerType myType){


    std::vector<double> sensorReading= armadilloToStdVec(robotinoQueue->getCurrentProcessedCartesianFrcTrq().joints);
    auto numberOfCartesianFTs=jacobian.rows();
    if (numberOfCartesianFTs != sensorReading.size()){
        cout << "Problem in sensor readings vector size" << endl;
        return stdToArmadilloVec({0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0});
    }
    std::vector<double> forceVector = scaleForcesTorques(sensorReading);
    std::vector<double> additiveDifferential;

    switch(myType){
    case JACOBIAN:
    {

        additiveDifferential =  eigenToStdVec(jacobian.transpose() * stdToEigenVec(forceVector));
        additiveDifferential= scaleJointCommands(additiveDifferential);
        break;
    }
    case INVERSE://Pseudo inverse..horrible!
    {
        Eigen::JacobiSVD<Eigen::MatrixXd> svd(jacobian, Eigen::ComputeThinU | Eigen::ComputeThinV);
        additiveDifferential= scaleJointCommands(eigenToStdVec(0.15*svd.solve(stdToEigenVec(forceVector))));
        break;
    }
    case IK:
    {
        const double scaleIK=0.2;
        forceVector = armadilloToStdVec( scaleIK*stdToArmadilloVec(forceVector));
        geometry_msgs::Pose currentPose = mvKin->computeFk(armadilloToStdVec(currentJointState));
        geometry_msgs::Pose newPose;
        newPose.position.x= currentPose.position.x + forceVector.at(0);
        newPose.position.y=currentPose.position.y + forceVector.at(1);
        newPose.position.z=currentPose.position.z + forceVector.at(2);
        tf::Quaternion quat(currentPose.orientation.x,currentPose.orientation.y,currentPose.orientation.z,currentPose.orientation.w);
        tf::Matrix3x3 m(quat);
        double roll,pitch,yaw;
        m.getRPY(roll,pitch,yaw);
        roll+= forceVector.at(3);
        pitch+= forceVector.at(4);
        yaw+= forceVector.at(5);
        newPose.orientation = tf::createQuaternionMsgFromRollPitchYaw(roll,pitch,yaw);
        auto planIK = mvKin->computeIk(armadilloToStdVec(currentJointState),newPose);
        auto target =currentJointState;
        if (planIK.size()>0)
            target=planIK.back();
        else
            cout << "IK solution not found" << endl;

        additiveDifferential = armadilloToStdVec( target - currentJointState);
        if (isBigJump(additiveDifferential)){
            additiveDifferential={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
            cout << " Big Jump from IK solution" << endl;
        }
        break;
    }
    case HYBRID:
    {
        const double scaleIK=0.1;
        additiveDifferential={0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0};
        forceVector = armadilloToStdVec( scaleIK*stdToArmadilloVec(forceVector));
        geometry_msgs::Pose currentPose = mvKin->computeFk(armadilloToStdVec(currentJointState));
        geometry_msgs::Pose newPose;
        newPose.position.x= currentPose.position.x + forceVector.at(0);
        newPose.position.y=currentPose.position.y + forceVector.at(1);
        newPose.position.z=currentPose.position.z + forceVector.at(2);
        tf::Quaternion quat(currentPose.orientation.x,currentPose.orientation.y,currentPose.orientation.z,currentPose.orientation.w);
        tf::Matrix3x3 m(quat);
        double roll,pitch,yaw;
        m.getRPY(roll,pitch,yaw);
        roll+= forceVector.at(3);
        pitch+= forceVector.at(4);
        yaw+= forceVector.at(5);
        newPose.orientation = tf::createQuaternionMsgFromRollPitchYaw(roll,pitch,yaw);
        auto planIK = mvKin->computeIk(armadilloToStdVec(currentJointState),newPose);
        auto target =currentJointState;
        bool jacobianUse = false;
        if (planIK.size()>0){
            target=planIK.back();
            additiveDifferential = armadilloToStdVec( target - currentJointState);
        }
        else
            jacobianUse =true;

        if (isBigJump(additiveDifferential))
            jacobianUse =true;


        if (jacobianUse){
            additiveDifferential =  eigenToStdVec(jacobian.transpose() * stdToEigenVec(forceVector));
            additiveDifferential= scaleJointCommands(additiveDifferential);
            cout << " jacobian" << endl;
        }
        break;
    }
    }


    return stdToArmadilloVec(capVec(additiveDifferential,MAXIMUM_JOINT_STEP));

}
Пример #15
0
void sandbox(SDL_Surface *s, int width, int height){
	form sand(0,0,1000,600);
	cout<<sand.children.size()<<"\n";
	XAutomataEngine game(&sand,200,100,750,400,width,height);
	//configure key events to pass preview to sand.
	sand.tag = &game;
	sand.addHandler(event_keydown,sandKey);

	//pan controls
	Button panUp(&sand,70,190,45,45); panUp.text = "Up";
	Button panDown(&sand,70,290,45,45); panDown.text = "Down";
	Button panLeft(&sand,20,240,45,45); panLeft.text = "Left";
	Button panRight(&sand,120,240,45,45); panRight.text = "Right";
	Button home(&sand,70,240,45,45); home.text = (width==-1&&height==-1?"Home":"Fit");

	panUp.tag = panDown.tag = panLeft.tag = panRight.tag = home.tag = (void*)(&game);
	panUp.addHandler(event_Lclick,sandUpHandler);
	panDown.addHandler(event_Lclick,sandDownHandler);
	panLeft.addHandler(event_Lclick,sandLeftHandler);
	panRight.addHandler(event_Lclick,sandRightHandler);
	home.addHandler(event_Lclick,sandHomeHandler);

	//zoom controls
	Button zoomIn(&sand,55,375,75,45); zoomIn.text = "Zoom in";
	Button zoomOut(&sand,55,445,75,45); zoomOut.text = "Zoom out";
	zoomIn.tag = zoomOut.tag =  (void*)(&game);
	zoomIn.addHandler(event_Lclick,sandZoomInHandler);
	zoomOut.addHandler(event_Lclick,sandZoomOutHandler);

	//speed controls
	label speedLabel(&sand,200,530,130,30); speedLabel.text = "Speed: Paused";
	HScroll speedScroll(&sand,350,530,200,30,1,10,5);
	Button pause(&sand,600,530,70,30); pause.text = "Pause";
	Button step(&sand,700,530,70,30); step.text = "Step";
	speedLabel.tag = speedScroll.tag = pause.tag = step.tag = (void*)(&game);
	speedScroll.addHandler(event_scroll,sandScrollHandler);
	pause.addHandler(event_Lclick,sandPause);
	step.addHandler(event_Lclick,sandStep);
	
	//colour controls
	radioButton white(&sand,300,35,80,20,NULL);	white.setTextColour(255,255,255);	white.setText("Master");
	radioButton red(&sand,400,35,80,20,&white);	red.setTextColour(255,100,100);		red.setText("Red");
	radioButton green(&sand,500,35,80,20,&red);	green.setTextColour(0,255,100);	green.setText("Green");
	radioButton blue(&sand,600,35,80,20,&green);	blue.setTextColour(100,100,255);	blue.setText("Blue");
	radioButton yellow(&sand,700,35,80,20,&green);	yellow.setTextColour(255,255,0);	yellow.setText("Yellow");

	checkBox bind(&sand,300,70,150,30); bind.setText("Enforce rules");
	bind.tag = (void*)&game;
	bind.addHandler(event_checkchanged,changeRestrict);

	teamRadioStruct params[5];
	radioButton *colours[5] = {&white,&red,&green,&blue,&yellow};
	for(int i = 0; i < 5; i++){
		params[i] = teamRadioStruct(i,&game);
		colours[i]->tag = &params[i];
		colours[i]->addHandler(event_checkchanged,changeTeam);
	}
	
	white.select();
	game.fit();

	//adding a save feature. No open yet...
	Button save(&sand,900,10,80,40); save.text = "Save";

	//exit controls
	Button back(&sand,50,50,100,50); back.text = "Back";
	back.addHandler(event_Lclick,sandBack);

	sand.addHandler(event_quit,sandBack);

	//keep that label and pause button updated
	pause.addHandler(event_frameTick,sandPauseButtonText);
	speedLabel.addHandler(event_frameTick,sandLabelText);

	sand.startFramerate(20,s);
	
	running = true;
	while(running){
		sand.wait();
		SDL_Flip(s);
	}
	cout<<"Ended";
}
Пример #16
0
CUnitDiskObjectPtr
CMirDiskObject::SecondDisk() const
{
	return boost::dynamic_pointer_cast<CUnitDiskObject>( back() );
}
Пример #17
0
bool PhysicsInterface::convertImageAlphaTo2DPolygons(const Image& image, Vector<Vector<Vec2>>& outPolygons,
                                                     bool flipHorizontally, bool flipVertically)
{
    // Check image is valid
    if (!image.isValid2DImage())
    {
        LOG_ERROR << "The passed image is not a valid 2D image: " << image;
        return false;
    }

    auto bitmap = Bitmap(image.getWidth(), image.getHeight());

    // Setup bitmap contents
    auto width = int(image.getWidth());
    for (auto i = 0U; i < bitmap.data.size(); i++)
        bitmap.set(i % width, i / width, image.getPixelColor(i % width, i / width).a > 0.5f);

    // Find all the edge pixels
    auto edgePixels = Vector<PolygonVertex>();
    for (auto y = 0; y < bitmap.height; y++)
    {
        for (auto x = 0; x < bitmap.width; x++)
        {
            if (bitmap.get(x, y) && (!bitmap.get(x - 1, y - 1) || !bitmap.get(x - 1, y) || !bitmap.get(x - 1, y + 1) ||
                                     !bitmap.get(x, y - 1) || !bitmap.get(x, y + 1) || !bitmap.get(x + 1, y - 1) ||
                                     !bitmap.get(x + 1, y) || !bitmap.get(x + 1, y + 1)))
                edgePixels.emplace(x, y);
        }
    }

    while (!edgePixels.empty())
    {
        // Start the next polygon at an unused edge pixel
        auto polygon = Vector<PolygonVertex>(1, edgePixels.popBack());

        // Each pixel that is put onto polygon can be backtracked if it leads to a dead end, this fixes problems with
        // pointy angles that can cause the edge walking to get stuck.
        auto hasBacktracked = false;

        while (true)
        {
            // Continue building this polygon by finding the next adjacent edge pixel
            auto adjacentPixel = 0U;
            for (; adjacentPixel < edgePixels.size(); adjacentPixel++)
            {
                if (bitmap.isAdjacent(polygon.back(), edgePixels[adjacentPixel]))
                    break;
            }

            // If there was no adjacent edge pixel then this polygon is malformed, so skip it and keep trying to build
            // more
            if (adjacentPixel == edgePixels.size())
            {
                if (!hasBacktracked)
                {
                    polygon.popBack();
                    hasBacktracked = true;

                    if (polygon.empty())
                        break;

                    continue;
                }
                else
                    break;
            }

            // Add the adjacent edge pixel to this polygon
            polygon.append(edgePixels[adjacentPixel]);
            edgePixels.erase(adjacentPixel);
            hasBacktracked = false;

            // Check whether this polygon is now complete, at least 4 points are required for a valid polygon
            if (polygon.size() < 4 || !bitmap.isAdjacent(polygon[0], polygon.back()))
                continue;

            // Now that a complete polygon has been constructed it needs to be simplified down as much as possible while
            // retaining key features such as large straight edges and right angles

            // Simplify perfectly horizontal and vertical edges as much as possible
            for (auto i = 0; i < int(polygon.size()); i++)
            {
                const auto& a = polygon[i];
                const auto& b = polygon[(i + 1) % polygon.size()];
                const auto& c = polygon[(i + 2) % polygon.size()];

                if ((a.x == b.x && a.x == c.x) || (a.y == b.y && a.y == c.y))
                    polygon.erase((i-- + 1) % polygon.size());
            }

            // Identify horizontal and vertical edges that are on the outside edge of the bitmap and mark their vertices
            // as important
            for (auto i = 0U; i < polygon.size(); i++)
            {
                auto& a = polygon[i];
                auto& b = polygon[(i + 1) % polygon.size()];
                if ((a.x == 0 || a.x == int(image.getWidth() - 1) || a.y == 0 || a.y == int(image.getHeight() - 1)) &&
                    a.isAxialEdge(b))
                {
                    a.keep = true;
                    b.keep = true;
                }
            }

            // Identify axial right angles and flag the relevant vertices as important
            for (auto i = 0U; i < polygon.size(); i++)
            {
                const auto& a = polygon[i];
                const auto& c = polygon[(i + 2) % polygon.size()];
                auto& b = polygon[(i + 1) % polygon.size()];

                if (a.isAxialEdge(b) && b.isAxialEdge(c) && (a - b).isRightAngle(c - b))
                    b.keep = true;
            }

            // The ends of straight edges that are not part of a right angle shape are pulled inwards by inserting new
            // vertices one pixel apart, this allows the ends of straight edges to undergo subsequent simplification.
            // The 'body' of the straight edge is then flagged as important to avoid any further simplification, which
            // will preserve the straight edge in the final result.
            const auto straightEdgePullBackSize = straightEdgeLength / 3;
            for (auto i = 0U; i < polygon.size(); i++)
            {
                auto a = polygon[i];
                auto b = polygon[(i + 1) % polygon.size()];

                if (a.isAxialEdge(b))
                {
                    auto xSign = Math::getSign(b.x - a.x);
                    auto ySign = Math::getSign(b.y - a.y);

                    if (!a.keep)
                    {
                        for (auto j = 0U; j < straightEdgePullBackSize; j++)
                            polygon.insert(i++, PolygonVertex(a.x + xSign * (j + 1), a.y + (j + 1) * ySign));

                        polygon[i].keep = true;
                    }

                    if (!b.keep)
                    {
                        for (auto j = 0U; j < straightEdgePullBackSize; j++)
                        {
                            polygon.insert(i++, PolygonVertex(b.x - (straightEdgePullBackSize - j) * xSign,
                                                              b.y - (straightEdgePullBackSize - j) * ySign));
                        }
                        polygon[i - straightEdgePullBackSize + 1].keep = true;
                    }
                }
            }

            // This is the main simplification loop, it works by trying to do progressively larger and larger
            // simplifcations on the polygon
            auto simplificationThreshold = 1.5f;
            while (polygon.size() > 3)
            {
                for (auto i = 0U; i < polygon.size(); i++)
                {
                    const auto& a = polygon[i];
                    const auto& b = polygon[(i + 1) % polygon.size()];
                    const auto& c = polygon[(i + 2) % polygon.size()];

                    // If b is important then don't try to get rid of it
                    if (b.keep)
                        continue;

                    // Get rid of point b if the line a-c is connected by an edge in the bitmap
                    if (a.distance(c) < simplificationThreshold && bitmap.arePixelsConnectedByEdge(a, c))
                        polygon.erase((i + 1) % polygon.size());
                }

                simplificationThreshold += 1.0f;
                if (simplificationThreshold >= std::max(image.getWidth(), image.getHeight()))
                    break;
            }

            if (polygon.size() < 3)
                break;

            outPolygons.enlarge(1);
            auto& outPolygon = outPolygons.back();

            // Scale to the range 0-1
            for (const auto& vertex : polygon)
                outPolygon.append(vertex.toVec2() / Vec2(float(image.getWidth() - 1), float(image.getHeight() - 1)));

            // Apply horizontal and vertical flips if requested
            if (flipHorizontally)
            {
                for (auto& vertex : outPolygon)
                    vertex.setXY(1.0f - vertex.x, vertex.y);
            }
            if (flipVertically)
            {
                for (auto& vertex : outPolygon)
                    vertex.setXY(vertex.x, 1.0f - vertex.y);
            }

            // Order vertices clockwise
            auto center = outPolygon.getAverage();
            if ((Vec3(outPolygon[0]) - center).cross(Vec3(outPolygon[1]) - center).z > 0.0f)
                outPolygon.reverse();

            break;
        }
    }

    return !outPolygons.empty();
}
Пример #18
0
void ResourceWizard::PageChanged(int PageId)
{
    //qDebug()<<"start"<<"PageId"<<PageId<<"CurrentPageId"<<CurrentPageId;
    if(CurrentPageId == 0)
    {
        MultiLanguageString str;
        str.SetTranslation("en",ui->DescriptionEn->text());
        str.SetTranslation("ru",ui->DescripnionRu->text());

        ResourceWidget->SetVariableName(ui->Name->text());
        ResourceWidget->SetDescription(str);
    }else if(CurrentPageId == 1)
    {
        ResourceWidget->SetTypeId(Type);

    }else if(CurrentPageId == 2)
    {
        if(Type == "FixedString")
        {
            QCheckBox * e = ResourceWidget->GetTemplateWidgetByType(false,Type)->findChild<QCheckBox *>("NotEmptyCheckBox");
            if(e)
                e->setChecked(ui->StringNotEmpty->isChecked());

            QLineEdit * FixedStringValue = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QLineEdit *>("FixedStringValue");
            if(FixedStringValue)
                FixedStringValue->setText(ui->StringDefaultValue->text());
        }
    }else if(CurrentPageId == 10)
    {
        if(IsAdditionalTab)
        {
            IsAdditionalTab = false;
            MultiLanguageString str;
            str.SetTranslation("en",ui->TabEn->text());
            str.SetTranslation("ru",ui->TabRu->text());
            ResourceWidget->SetSectionName(str);
        }
    }else if(CurrentPageId == 9)
    {
        if(IsAdditionalIf)
        {
            IsAdditionalIf = false;
            ResourceWidget->SetVisibilityConditionValue(ui->VisibilityValue->text());
            ResourceWidget->SetVisibilityConditionVariable(ui->VisibilityName->text());

        }
    }else if(CurrentPageId == 8)
    {
        if(Type == "Select")
        {
            QComboBox * SelectTypeCombo = ResourceWidget->GetTemplateWidgetByType(false,Type)->findChild<QComboBox *>("SelectTypeCombo");
            if(SelectTypeCombo)
                SelectTypeCombo->setCurrentText(ui->SelectType->currentText());

            QPlainTextEdit * SelectValuesEdit = ResourceWidget->GetTemplateWidgetByType(false,Type)->findChild<QPlainTextEdit *>("SelectValuesEdit");
            if(SelectValuesEdit)
                SelectValuesEdit->setPlainText(ui->SelectLines->toPlainText());

            QWidget *child = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QWidget *>("SelectWidget");
            QLayout * layout = child->layout();

            /*MultiSelect * OldSelect = child->findChild<MultiSelect *>();
            if(OldSelect)
                OldSelect->deleteLater();

            MultiSelect * Select = new MultiSelect(child);*/

            MultiSelect * Select = child->findChild<MultiSelect *>();

            QStringList list = ui->SelectLines->toPlainText().split(QRegExp("[\r\n]"),QString::SkipEmptyParts);

            MultiSelect *multi = ui->SelectDefaultValueContainer->findChild<MultiSelect *>();

            Select->Update(ui->SelectType->currentText(), list, multi->GetSelectedIndex());
            layout->addWidget(Select);


        }
    }else if(CurrentPageId == 7)
    {
        if(Type == "RandomString")
        {
            QLineEdit * RandomStringValue = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QLineEdit *>("RandomStringValue");
            if(RandomStringValue)
                RandomStringValue->setText(ui->RandomStringValue->text());
        }
    }else if(CurrentPageId == 4)
    {
        if(Type == "FixedInteger")
        {
            QSpinBox * min = ResourceWidget->GetTemplateWidgetByType(false,Type)->findChild<QSpinBox *>("EditMinimum");
            QSpinBox * max = ResourceWidget->GetTemplateWidgetByType(false,Type)->findChild<QSpinBox *>("EditMaximum");
            if(min)
                min->setValue(ui->MinValueNumber->value());
            if(max)
                max->setValue(ui->MaxValueNumber->value());

            QSpinBox * FixedIntegerValue = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("FixedIntegerValue");
            if(FixedIntegerValue)
                FixedIntegerValue->setValue(ui->Number->value());


        }

    }else if(CurrentPageId == 3)
    {

        if(Type == "RandomInteger")
        {
            QSpinBox * min = ResourceWidget->GetTemplateWidgetByType(false,Type)->findChild<QSpinBox *>("EditMinimum_2");
            QSpinBox * max = ResourceWidget->GetTemplateWidgetByType(false,Type)->findChild<QSpinBox *>("EditMaximum_2");
            if(min)
                min->setValue(ui->MinValueRange->value());
            if(max)
                max->setValue(ui->MaxValueRange->value());

            QSpinBox * RIMinimumValue = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("RIMinimumValue");
            if(RIMinimumValue)
                RIMinimumValue->setValue(ui->NumberMin->value());

            QSpinBox * RIMaximumValue = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("RIMaximumValue");
            if(RIMaximumValue)
                RIMaximumValue->setValue(ui->NumberMax->value());
        }
    }else if(CurrentPageId == 5)
    {
        if(Type == "LinesFromFile")
        {

            QCheckBox * FileRead = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QCheckBox *>("FileRead");
            if(FileRead)
                FileRead->setChecked(!ui->OnlyWrite->isChecked());

            QCheckBox * FileWrite = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QCheckBox *>("FileWrite");
            if(FileWrite)
                FileWrite->setChecked(!ui->OnlyRead->isChecked());

            QCheckBox * FileMix = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QCheckBox *>("FileMix");
            if(FileMix)
                FileMix->setChecked(ui->MixLines->isChecked());


        }
        if(Type == "FilesFromDirectory")
        {
            QCheckBox * DirectoryClean = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QCheckBox *>("DirectoryClean");
            if(DirectoryClean)
                DirectoryClean->setChecked(!ui->OnlyRead->isChecked());

            QCheckBox * DirectoryMix = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QCheckBox *>("DirectoryMix");
            if(DirectoryMix)
                DirectoryMix->setChecked(ui->MixLines->isChecked());

        }

        if(Type == "Database")
        {
            QCheckBox * DatabaseClear = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QCheckBox *>("DatabaseClear");
            if(DatabaseClear)
                DatabaseClear->setChecked(!ui->OnlyRead->isChecked());

            QCheckBox * DatabaseMix = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QCheckBox *>("DatabaseMix");
            if(DatabaseMix)
                DatabaseMix->setChecked(ui->MixLines->isChecked());
        }
    }else if(CurrentPageId == 6)
    {
        int Success = 0;
        int Fails = 0;
        if(ui->EachLineOneTime->isChecked())
        {
            Success = 1;
            Fails = 1;
        }else if(ui->EachLineSeveralTimes->isChecked())
        {
            Success = 10;
            Fails = 10;
        }else if(ui->EachLineAnyNumberOfTimes->isChecked())
        {
            Success = 100000;
            Fails = 100000;
        }

        if(Type == "LinesFromFile")
        {
            QSpinBox * FileMaxSuccess = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("FileMaxSuccess");
            if(FileMaxSuccess)
                FileMaxSuccess->setValue(Success);

            QSpinBox * FileMaxFail = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("FileMaxFail");
            if(FileMaxFail)
                FileMaxFail->setValue(Fails);
        }

        if(Type == "FilesFromDirectory")
        {
            QSpinBox * DirectoryMaxSuccess = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("DirectoryMaxSuccess");
            if(DirectoryMaxSuccess)
                DirectoryMaxSuccess->setValue(Success);

            QSpinBox * DirectoryMaxFail = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("DirectoryMaxFail");
            if(DirectoryMaxFail)
                DirectoryMaxFail->setValue(Fails);

        }

        if(Type == "Database")
        {
            QSpinBox * DatabaseMaxSuccess = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("DatabaseMaxSuccess");
            if(DatabaseMaxSuccess)
                DatabaseMaxSuccess->setValue(Success);

            QSpinBox * DatabaseMaxFail = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("DatabaseMaxFail");
            if(DatabaseMaxFail)
                DatabaseMaxFail->setValue(Fails);
        }

        if(Type == "LinesFromUrl")
        {
            QSpinBox * UrlMaxSuccess = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("UrlMaxSuccess");
            if(UrlMaxSuccess)
                UrlMaxSuccess->setValue(Success);

            QSpinBox * UrlMaxFail = ResourceWidget->GetTemplateWidgetByType(true,Type)->findChild<QSpinBox *>("UrlMaxFail");
            if(UrlMaxFail)
                UrlMaxFail->setValue(Fails);
        }
    }

    if(PageId > CurrentPageId)
    {
        if(PageId == 2 && Type != "FixedString")
        {
            next();
            return;
        }
        if(PageId == 3 && Type != "RandomInteger")
        {
            next();
            return;
        }
        if(PageId == 4 && Type != "FixedInteger")
        {
            next();
            return;
        }
        if(PageId == 5 && Type != "LinesFromFile" && Type != "FilesFromDirectory" && Type != "Database")
        {
            next();
            return;
        }
        if(PageId == 6 && Type != "LinesFromFile" && Type != "FilesFromDirectory" && Type != "Database" && Type != "LinesFromUrl")
        {
            next();
            return;
        }
        if(PageId == 7 && Type != "RandomString")
        {
            next();
            return;
        }
        if(PageId == 8 && Type != "Select")
        {
            next();
            return;
        }
        if(PageId == 9 && !IsAdditionalIf)
        {
            next();
            return;
        }
        if(PageId == 10 && !IsAdditionalTab)
        {
            next();
            return;
        }
    }else
    {
        if(PageId == 2 && Type != "FixedString")
        {
            back();
            return;
        }
        if(PageId == 3 && Type != "RandomInteger")
        {
            back();
            return;
        }
        if(PageId == 4 && Type != "FixedInteger")
        {
            back();
            return;
        }
        if(PageId == 5 && Type != "LinesFromFile" && Type != "FilesFromDirectory" && Type != "Database")
        {
            back();
            return;
        }
        if(PageId == 6 && Type != "LinesFromFile" && Type != "FilesFromDirectory" && Type != "Database" && Type != "LinesFromUrl")
        {
            back();
            return;
        }
        if(PageId == 7 && Type != "RandomString")
        {
            back();
            return;
        }
        if(PageId == 8 && Type != "Select")
        {
            back();
            return;
        }
        if(PageId == 9 && !IsAdditionalIf)
        {
            back();
            return;
        }
        if(PageId == 10 && !IsAdditionalTab)
        {
            back();
            return;
        }
    }

    CurrentPageId = PageId;
}
Пример #19
0
void NGLScene::initialize()
{
  // we must call this first before any other GL commands to load and link the
  // gl commands from the lib, if this is not done program will crash
  ngl::NGLInit::instance();

  glClearColor(0.4f, 0.4f, 0.4f, 1.0f);			   // Grey Background
  // enable depth testing for drawing
  glEnable(GL_DEPTH_TEST);
  // enable multisampling for smoother drawing
  glEnable(GL_MULTISAMPLE);
  ngl::Vec3 from(0,0,3);
  ngl::Vec3 to(0,0,0);
  ngl::Vec3 up(0,1,0);

  m_cam= new ngl::Camera(from,to,up);
  // set the shape using FOV 45 Aspect Ratio based on Width and Height
  // The final two are near and far clipping planes of 0.5 and 10
  m_cam->setShape(45,(float)720.0/576.0,0.5,150);

  // grab an instance of shader manager
  ngl::ShaderLib *shader=ngl::ShaderLib::instance();

  shader->createShaderProgram("Phong");

  shader->attachShader("PhongVertex",ngl::VERTEX);
  shader->attachShader("PhongFragment",ngl::FRAGMENT);
  shader->loadShaderSource("PhongVertex","shaders/PhongVertex.glsl");
  shader->loadShaderSource("PhongFragment","shaders/PhongFragment.glsl");

  shader->compileShader("PhongVertex");
  shader->compileShader("PhongFragment");
  shader->attachShaderToProgram("Phong","PhongVertex");
  shader->attachShaderToProgram("Phong","PhongFragment");

  shader->linkProgramObject("Phong");
  (*shader)["Phong"]->use();

  // now pass the modelView and projection values to the shader
  shader->setShaderParam1i("Normalize",1);
  shader->setShaderParam3f("viewerPos",m_cam->getEye().m_x,m_cam->getEye().m_y,m_cam->getEye().m_z);

  // now set the material and light values
  ngl::Material m(ngl::POLISHEDSILVER);
  m.loadToShader("material");
  ngl::Mat4 iv;
  iv=m_cam->getProjectionMatrix();
  //iv.transpose();

  /// now setup a basic 3 point lighting system
  ngl::Light key(ngl::Vec3(2,1,3),ngl::Colour(1,1,1,1),ngl::POINTLIGHT);
  key.setTransform(iv);
  key.enable();
  key.loadToShader("light[0]");
  ngl::Light fill(ngl::Vec3(-2,1.5,3),ngl::Colour(1,1,1,1),ngl::POINTLIGHT);
  fill.setTransform(iv);
  fill.enable();
  fill.loadToShader("light[1]");

  ngl::Light back(ngl::Vec3(2,1,-2),ngl::Colour(1,1,1,1),ngl::POINTLIGHT);
  back.setTransform(iv);
  back.enable();
  back.loadToShader("light[2]");



  shader->createShaderProgram("normalShader");

  shader->attachShader("normalVertex",ngl::VERTEX);
  shader->attachShader("normalFragment",ngl::FRAGMENT);
  shader->loadShaderSource("normalVertex","shaders/normalVertex.glsl");
  shader->loadShaderSource("normalFragment","shaders/normalFragment.glsl");

  shader->compileShader("normalVertex");
  shader->compileShader("normalFragment");
  shader->attachShaderToProgram("normalShader","normalVertex");
  shader->attachShaderToProgram("normalShader","normalFragment");

  shader->attachShader("normalGeo",ngl::GEOMETRY);
  shader->loadShaderSource("normalGeo","shaders/normalGeo.glsl");
  shader->compileShader("normalGeo");
  shader->attachShaderToProgram("normalShader","normalGeo");
  shader->linkProgramObject("normalShader");
  shader->use("normalShader");
  // now pass the modelView and projection values to the shader
  shader->setShaderParam1f("normalSize",0.1);
  shader->setShaderParam4f("vertNormalColour",1,1,0,1);
  shader->setShaderParam4f("faceNormalColour",1,0,0,1);

  shader->setShaderParam1i("drawFaceNormals",true);
  shader->setShaderParam1i("drawVertexNormals",true);

  glEnable(GL_DEPTH_TEST); // for removal of hidden surfaces
  ngl::VAOPrimitives *prim=ngl::VAOPrimitives::instance();
  prim->createSphere("sphere",0.8,40);
  prim->createCylinder("cylinder",0.2,2.0,40,40);
  prim->createCone("cone",0.8,2.0,40,40);
  prim->createTorus("torus",0.2,1.0,20,20);

  // as re-size is not explicitly called we need to do this.
  glViewport(0,0,width(),height());
}
Пример #20
0
void ResourceWizard::on_ToTab_clicked()
{
    IsAdditionalTab = true;
    back();
}
Пример #21
0
 /**
  * Checks whether the first and last node in the collection have the
  * same location. The IDs are not checked.
  *
  * @pre @code !empty() @endcode
  * @pre @code front().location() && back().location() @endcode
  */
 bool ends_have_same_location() const {
     assert(front().location() && back().location());
     return front().location() == back().location();
 }
Пример #22
0
void ResourceWizard::on_VisibleIf_clicked()
{
    IsAdditionalIf = true;
    back();
}
Пример #23
0
RES Camera::_get_gizmo_geometry() const {

	Ref<SurfaceTool> surface_tool(memnew(SurfaceTool));

	Ref<FixedMaterial> mat(memnew(FixedMaterial));

	mat->set_parameter(FixedMaterial::PARAM_DIFFUSE, Color(1.0, 0.5, 1.0, 0.5));
	mat->set_line_width(4);
	mat->set_flag(Material::FLAG_DOUBLE_SIDED, true);
	mat->set_flag(Material::FLAG_UNSHADED, true);
	//mat->set_hint(Material::HINT_NO_DEPTH_DRAW,true);

	surface_tool->begin(Mesh::PRIMITIVE_LINES);
	surface_tool->set_material(mat);

	switch (mode) {

		case PROJECTION_PERSPECTIVE: {

			Vector3 side = Vector3(Math::sin(Math::deg2rad(fov)), 0, -Math::cos(Math::deg2rad(fov)));
			Vector3 nside = side;
			nside.x = -nside.x;
			Vector3 up = Vector3(0, side.x, 0);

#define ADD_TRIANGLE(m_a, m_b, m_c)    \
	{                                  \
		surface_tool->add_vertex(m_a); \
		surface_tool->add_vertex(m_b); \
		surface_tool->add_vertex(m_b); \
		surface_tool->add_vertex(m_c); \
		surface_tool->add_vertex(m_c); \
		surface_tool->add_vertex(m_a); \
	}

			ADD_TRIANGLE(Vector3(), side + up, side - up);
			ADD_TRIANGLE(Vector3(), nside + up, nside - up);
			ADD_TRIANGLE(Vector3(), side + up, nside + up);
			ADD_TRIANGLE(Vector3(), side - up, nside - up);

			side.x *= 0.25;
			nside.x *= 0.25;
			Vector3 tup(0, up.y * 3 / 2, side.z);
			ADD_TRIANGLE(tup, side + up, nside + up);

		} break;
		case PROJECTION_ORTHOGONAL: {

#define ADD_QUAD(m_a, m_b, m_c, m_d)   \
	{                                  \
		surface_tool->add_vertex(m_a); \
		surface_tool->add_vertex(m_b); \
		surface_tool->add_vertex(m_b); \
		surface_tool->add_vertex(m_c); \
		surface_tool->add_vertex(m_c); \
		surface_tool->add_vertex(m_d); \
		surface_tool->add_vertex(m_d); \
		surface_tool->add_vertex(m_a); \
	}

			float hsize = size * 0.5;
			Vector3 right(hsize, 0, 0);
			Vector3 up(0, hsize, 0);
			Vector3 back(0, 0, -1.0);
			Vector3 front(0, 0, 0);

			ADD_QUAD(-up - right, -up + right, up + right, up - right);
			ADD_QUAD(-up - right + back, -up + right + back, up + right + back, up - right + back);
			ADD_QUAD(up + right, up + right + back, up - right + back, up - right);
			ADD_QUAD(-up + right, -up + right + back, -up - right + back, -up - right);

			right.x *= 0.25;
			Vector3 tup(0, up.y * 3 / 2, back.z);
			ADD_TRIANGLE(tup, right + up + back, -right + up + back);

		} break;
	}

	return surface_tool->commit();
}
Пример #24
0
Main::Main()
{
    setIcon( (const char**)logo_xpm );
#ifdef FIXED_LAYOUT
    QHBox* horizontal = new QHBox(this);
#else
    QSplitter* horizontal = new QSplitter(this);
#endif

    lv = new QListView(horizontal);
    lv->setSorting(-1);
    lv->setRootIsDecorated(TRUE);
    lv->addColumn("ID");

    info = new Info(horizontal);
    info->setBackgroundMode(PaletteBase);
    info->setMargin(10);
    info->setFrameStyle(QFrame::WinPanel|QFrame::Sunken);
    info->setAlignment(AlignTop);

    connect(info, SIGNAL(idClicked(const QString&)),
	    this, SLOT(selectId(const QString&)));

#ifdef FIXED_LAYOUT
    horizontal->setStretchFactor(info,2);
#endif

    connect(lv, SIGNAL(pressed(QListViewItem*)),
	    this, SLOT(updateAvailability(QListViewItem*)));
    connect(lv, SIGNAL(selectionChanged(QListViewItem*)),
	    this, SLOT(showInfo(QListViewItem*)));

    setCentralWidget(horizontal);

    QToolBar* tb = new QToolBar( this, "browser controls" );
    tb->setLabel( "Browser Controls" );
    (void)new QToolButton( QPixmap(back_xpm), "Back", QString::null,
                           info, SLOT(back()), tb, "back" );
    (void)new QToolButton( QPixmap(forward_xpm), "Forward", QString::null,
                           info, SLOT(forward()), tb, "forward" );

    QPopupMenu* file = new QPopupMenu( menuBar() );
    file->insertItem( "&Open",  this, SLOT(open()), CTRL+Key_O );
    file->insertItem( "&Save", this, SLOT(save()), CTRL+Key_S );
    file->insertSeparator();
    file->insertItem( "&Test all", this, SLOT(testAll()), CTRL+Key_T );
    file->insertSeparator();
    file->insertItem( "E&xit",  qApp, SLOT(quit()), CTRL+Key_Q );

    menuBar()->insertItem( "&File",file );

    menuBar()->insertSeparator();

    QPopupMenu *help = new QPopupMenu( menuBar() );
    help->insertItem( "&About", this, SLOT(about()) );
    help->insertItem( "About &Qt", this, SLOT(aboutQt()) );

    menuBar()->insertItem( "&Help", help );

    statusBar()->message( "Ready" );
}
Пример #25
0
void Kiten::setupActions()
{
  /* Add the basic quit/print/prefs actions, use the gui factory for keybindings */
  (void) KStandardAction::quit( this, SLOT(close()), actionCollection() );
  //Why the heck is KSA:print adding it's own toolbar!?
  //	(void) KStandardAction::print(this, SLOT(print()), actionCollection());
  (void) KStandardAction::preferences( this, SLOT(slotConfigure()), actionCollection() );
  //old style cast seems needed here, (const QObject*)
  KStandardAction::keyBindings(   (const QObject*)guiFactory()
                                , SLOT(configureShortcuts())
                                , actionCollection() );

  /* Setup the Go-to-learn-mode actions */
  /* TODO: put back when Dictionary Editor is reorganised */
// 	(void) new KAction(   i18n( "&Dictionary Editor..." )
//                             , "document-properties"
//                             , 0
//                             , this
//                             , SLOT(createEEdit())
//                             , actionCollection()
//                             , "dict_editor");
  QAction *radselect = actionCollection()->addAction( "radselect" );
  radselect->setText( i18n( "Radical Selector" ) );
//	radselect->setIcon( "edit-find" );
  actionCollection()->setDefaultShortcut(radselect, Qt::CTRL+Qt::Key_R );
  connect(radselect, &QAction::triggered, this, &Kiten::radicalSearch);

  QAction *kanjibrowser = actionCollection()->addAction( "kanjibrowser" );
  kanjibrowser->setText( i18n( "Kanji Browser" ) );
  actionCollection()->setDefaultShortcut(kanjibrowser, Qt::CTRL+Qt::Key_K );
  connect(kanjibrowser, &QAction::triggered, this, &Kiten::kanjiBrowserSearch);

  /* Setup the Search Actions and our custom Edit Box */
  _inputManager = new SearchStringInput( this );

  QAction *searchButton = actionCollection()->addAction( "search" );
  searchButton->setText( i18n( "S&earch" ) );
  // Set the search button to search
  connect(searchButton, &QAction::triggered, this, &Kiten::searchFromEdit);
  searchButton->setIcon( KStandardGuiItem::find().icon() );

  // That's not it, that's "find as you type"...
//   connect( Edit, SIGNAL(completion(QString)),
//            this,   SLOT(searchFromEdit()) );

  /* Setup our widgets that handle preferences */
//   deinfCB = new KToggleAction(   i18n( "&Deinflect Verbs in Regular Search" )
//                                 , 0
//                                 , this
//                                 , SLOT(kanjiDictChange())
//                                 , actionCollection()
//                                 , "deinf_toggle" );

  _autoSearchToggle = actionCollection()->add<KToggleAction>( "autosearch_toggle" );
  _autoSearchToggle->setText( i18n( "&Automatically Search Clipboard Selections" ) );

  _irAction = actionCollection()->add<QAction>( "search_in_results" );
  _irAction->setText( i18n( "Search &in Results" ) );
  connect(_irAction, &QAction::triggered, this, &Kiten::searchInResults);


  QAction *actionFocusResultsView;
  actionFocusResultsView = actionCollection()->addAction(  "focusresultview"
                                                         , this
                                                         , SLOT(focusResultsView()) );
  actionCollection()->setDefaultShortcut(actionFocusResultsView, Qt::Key_Escape );
  actionFocusResultsView->setText( i18n( "Focus result view" ) );


  (void) KStandardAction::configureToolbars(   this
                                             , SLOT(configureToolBars())
                                             , actionCollection() );

  //TODO: this should probably be a standard action
  /*
  globalShortcutsAction = actionCollection()->addAction( "options_configure_global_keybinding" );
  globalShortcutsAction->setText( i18n( "Configure &Global Shortcuts..." ) );
  connect( globalShortcutsAction, SIGNAL(triggered()), this, SLOT(configureGlobalKeys()) );
  */

  //TODO: implement this
  //_globalSearchAction = actionCollection()->add<KToggleAction>( "search_on_the_spot" );
  //_globalSearchAction->setText( i18n( "On The Spo&t Search" ) );
  //KAction *temp = qobject_cast<KAction*>( _globalSearchAction );
  //KShortcut shrt( "Ctrl+Alt+S" );
  //globalSearchAction->setGlobalShortcut(shrt);  //FIXME: Why does this take ~50 seconds to return!?
  //connect(globalSearchAction, SIGNAL(triggered()), this, SLOT(searchOnTheSpot()));

  _backAction = KStandardAction::back( this, SLOT(back()), actionCollection() );
  _forwardAction = KStandardAction::forward( this, SLOT(forward()), actionCollection() );
  _backAction->setEnabled( false );
  _forwardAction->setEnabled( false );
}
Пример #26
0
 static Box* f_back(Box* obj, void* arg) noexcept { return incref(back(obj, arg)); }
Пример #27
0
void dra::vector<T>::push_back(const T& val)
{
	resize(sz_+1);
	back() = val;
}
Пример #28
0
   template<class T>
   static T&& select(any<Ts>..., T&& v){ return std::forward<T>(v); }
};
} // aux::

namespace meta{
template<class T> struct identity{ using type = T; };

template<class T> using Invoke = typename T::type;
template<class T> using Unqualified = Invoke<std::remove_cv<Invoke<std::remove_reference<T>>>>;

template<class T, class... Ts>
struct back{
  using type = Invoke<Unqualified<decltype(aux::back<Ts...>::select(identity<T>{}, identity<Ts>{}...))>>;
};

template<class... Ts>
using Back = Invoke<back<Ts...>>;
} // meta::

template<class T, class... Ts>
auto back(T&& v, Ts&&... vs)
  //-> decltype(aux::back<Ts...>::select(std::declval<T>(), std::declval<Ts>()...))
  -> meta::Back<T, Ts...>&&
{
    return aux::back<Ts...>::select(std::forward<T>(v), std::forward<Ts>(vs)...);
}

static_assert(std::is_same<int&&, decltype(back(3.14f, 13.37, true, 'x', "hi", 42))>(), "fix it, idiot");

int main(){}
Пример #29
0
int main()
{
    //Create window, and limit frame rate
    sf::RenderWindow window (sf::VideoMode(800, 600, 32), "Game", sf::Style::Default);
    window.setFramerateLimit(60);

//------------------------TEXTURES------------------------------

    //Declare textures
    sf::Texture texture;
    sf::Texture texture1;
    sf::Texture texture2;
    //Load image
    if(!texture.loadFromFile("Sprites/main.png"))
    {
        return 1;
    }
    if(!texture1.loadFromFile("Sprites/background.png"))
    {
        return 1;
    }
    if(!texture2.loadFromFile("Sprites/house.png"))
    {
        return 1;
    }

//------------------------SPRITES--------------------------

    //Creates and places the sprites
    sf::Sprite sprite;
    sf::Sprite background;
    sf::Sprite house;
    sprite.setPosition(400, 300);
    background.setPosition(0, 0);
    house.setPosition(440, 300);

    //Loads texture into sprite
    sprite.setTexture(texture);
    background.setTexture(texture1);
    house.setTexture(texture2);

//-------------------------RECTANGLES--------------------------------

    //Declares the rectangles
    sf::IntRect front(1, 1, 18, 24);
    sf::IntRect back (20, 1, 18, 24);
    sf::IntRect left (20, 26, 18, 24);
    sf::IntRect right (1, 26, 18, 24);
    //Steps
    sf::IntRect frontLeft(39, 1, 18, 24);
    sf::IntRect frontRight(39, 26, 18, 24);
    sf::IntRect backLeft();
    sf::IntRect backRight();
    sf::IntRect leftLeft();
    sf::IntRect leftRight();
    sf::IntRect rightLeft();
    sf::IntRect rightRight();

    sf::IntRect backgroundRect (0, 0, 800, 600);

    sf::IntRect houseRect (0, 0, 17, 22);


    //Crop sprites using rectangles defined above
    sprite.setTextureRect(front);
    background.setTextureRect(backgroundRect);
    house.setTextureRect(houseRect);

//-----------------------SOUND------------------------------------------------------

    //Declare the Sound Buffer
    sf::SoundBuffer footstepsBuffer;
    sf::SoundBuffer bumpBuffer;
    //Loads the sound file
    if(!footstepsBuffer.loadFromFile("Sounds/footsteps.wav"))
    {
        return 1;
    }
    if(!bumpBuffer.loadFromFile("Sounds/bump.wav"))
    {
        return 1;
    }

    //Declare sound
    sf::Sound footsteps;
    sf::Sound bump;
    //Load Buffer into Sound
    footsteps.setBuffer(footstepsBuffer);
    bump.setBuffer(bumpBuffer);

//-------------------------------MAIN-----------------------------

    //Main window loop
    while(window.isOpen())
    {
        sf::Event event;

        //Vectors used for collision
        sf::Vector2i spritePosition(sprite.getPosition());
        sf::Vector2i backgroundPosition(background.getPosition());
        sf::Vector2i housePosition(house.getPosition());

        //Sprite Vectors
        sf::Vector2i backVector(back.width, back.height);
        sf::Vector2i frontVector(front.width, front.height);
        sf::Vector2i rightVector(right.width, right.height);
        sf::Vector2i leftVector(left.width, left.height);

        //House Vectors
        sf::Vector2i houseVector(houseRect.width, houseRect.height);

        while(window.pollEvent(event))
        {
            if(event.type == sf::Event::Closed)
            {
                window.close();
            }

            if(event.key.code == sf::Keyboard::Insert)
            {
                sf::Image screenshot = window.capture();
                screenshot.saveToFile("Screenshot.png");
            }
        }

//-----------------------------------MOVEMENT----------------------------------------

        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
        {
            //Change to stepping sprite
            Sleep(250);
            sprite.setTextureRect(back);
            sprite.move(0, -24);
            //Redeclaring the collision textures
            sf::Vector2i spritePosition(sprite.getPosition());
            sf::Vector2i housePosition(house.getPosition());
            if(collision(spritePosition, backVector, housePosition, houseVector) == true)
            {
                sprite.move(0, 24);
                bump.play();
            }
            else
            {
                footsteps.play();
            }
        }

        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
        {
            //Change to stepping sprite
            Sleep(250);
            sprite.setTextureRect(front);
            sprite.move(0, 24);
            //Redeclaring the collision textures
            sf::Vector2i spritePosition(sprite.getPosition());
            sf::Vector2i housePosition(house.getPosition());
            if(collision(spritePosition, frontVector, housePosition, houseVector) == true)
            {
                sprite.move(0, -24);
                bump.play();
            }
            else
            {
                footsteps.play();
            }
        }

        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
        {
            //Change to stepping sprite
            Sleep(250);
            sprite.setTextureRect(right);
            sprite.move(19, 0);
            //Redeclaring the collision textures
            sf::Vector2i spritePosition(sprite.getPosition());
            sf::Vector2i housePosition(house.getPosition());
            if(collision(spritePosition, leftVector, housePosition, houseVector) == true)
            {
                sprite.move(-19, 0);
                bump.play();
            }
            else
            {
                footsteps.play();
            }
        }

        else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
        {
            //Change to stepping sprite
            Sleep(250);
            sprite.setTextureRect(left);
            sprite.move(-19, 0);
            //Redeclaring the collision textures
            sf::Vector2i spritePosition(sprite.getPosition());
            sf::Vector2i housePosition(house.getPosition());
            if(collision(spritePosition, rightVector, housePosition, houseVector) == true)
            {
                sprite.move(19, 0);
                bump.play();
            }
            else
            {
                footsteps.play();
            }
        }

        //Draw sequence
        window.clear(); //(Red, Green, Blue, (optional) Alpha) Alpha is transperency

        //Draw....

        window.draw(background);

        window.draw(house);

        window.draw(sprite);

        window.display();

        std::cout << x << std::endl;
        std::cout << y << std::endl;
    }
    return 0;
}
Пример #30
0
Dialog::Dialog(QWidget *parent) :
    QWidget(parent),
    loading(false),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    foreach (QextPortInfo info, QextSerialEnumerator::getPorts())
        if (!info.portName.isEmpty())
            ui->portBox->addItem(info.portName);
    //make sure user can input their own port name!
    ui->portBox->setEditable(true);

//    ui->led->turnOff();

    PortSettings settings = {BAUD9600, DATA_8, PAR_NONE, STOP_1, FLOW_OFF, 10};
    port = new QextSerialPort(ui->portBox->currentText(), settings, QextSerialPort::Polling);

    enumerator = new QextSerialEnumerator(this);
    enumerator->setUpNotifications();

    ui->boardComboBox->addItem("PX4FMU v1.6+", 5);
    ui->boardComboBox->addItem("PX4FLOW v1.1+", 6);
    ui->boardComboBox->addItem("PX4IO v1.3+", 7);
    ui->boardComboBox->addItem("PX4 board #8", 8);
    ui->boardComboBox->addItem("PX4 board #9", 9);
    ui->boardComboBox->addItem("PX4 board #10", 10);
    ui->boardComboBox->addItem("PX4 board #11", 11);

    connect(ui->portBox, SIGNAL(editTextChanged(QString)), SLOT(onPortNameChanged(QString)));
    connect(ui->flashButton, SIGNAL(clicked()), SLOT(onUploadButtonClicked()));
    connect(ui->selectFileButton, SIGNAL(clicked()), SLOT(onFileSelectRequested()));
    connect(ui->cancelButton, SIGNAL(clicked()), SLOT(onCancelButtonClicked()));

    // disable JavaScript for Windows for faster startup
#ifdef Q_OS_WIN
    QWebSettings *webViewSettings = ui->webView->settings();
    webViewSettings->setAttribute(QWebSettings::JavascriptEnabled, false);
#endif

    connect(ui->webView->page(), SIGNAL(downloadRequested(const QNetworkRequest&)), this, SLOT(onDownloadRequested(const QNetworkRequest&)));
    ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);

    connect(ui->webView->page(), SIGNAL(linkClicked(const QUrl&)), this, SLOT(onLinkClicked(const QUrl&)));

    connect(ui->prevButton, SIGNAL(clicked()), ui->webView, SLOT(back()));
    connect(ui->homeButton, SIGNAL(clicked()), this, SLOT(onHomeRequested()));

    connect(ui->advancedCheckBox, SIGNAL(clicked(bool)), this, SLOT(onToggleAdvancedMode(bool)));

    connect(enumerator, SIGNAL(deviceDiscovered(QextPortInfo)), SLOT(onPortAddedOrRemoved()));
    connect(enumerator, SIGNAL(deviceRemoved(QextPortInfo)), SLOT(onPortAddedOrRemoved()));

    setWindowTitle(tr("QUpgrade Firmware Upload / Configuration Tool"));

    // Adjust the size
    const int screenHeight = qMin(1000, QApplication::desktop()->height() - 100);

    resize(700, qMax(screenHeight, 550));

    // about:blank shouldn't be part of the history
    ui->webView->history()->clear();
    onHomeRequested();

    // load settings
    loadSettings();

    // Set up initial state
    if (!lastFilename.isEmpty()) {
        ui->flashButton->setEnabled(true);
    } else {
        ui->flashButton->setEnabled(false);
    }
}