当前位置: 首页>>代码示例>>C++>>正文


C++ Core类代码示例

本文整理汇总了C++中Core的典型用法代码示例。如果您正苦于以下问题:C++ Core类的具体用法?C++ Core怎么用?C++ Core使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Core类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: hm

void TestApp::Run()
{
	if (*mCore << "Config/T08.txt")
	{
		mCore->Lock();

		// First we need to create a heightmap we'll use to create the terrain. R5 has a fairly flexible
		// noise library with a variety of simple filters that we can use for just that purpose.

		Noise noise;

		// We want to generate a 256x256 heightmap
		noise.SetSize(256, 256);

		// You can combine a variety of filters to create the terrain's "final" look, but for the sake
		// of simplicity, let's only use one -- a perlin noise. The numbers that follow are optional
		// parameters. In this case '8' means generate an 8-octave noise, and 0.65 means that the noise
		// with values above 0.65 will be mirrored, turning high peaks into volcano-like crevices.
		// This type of noise is also known as ridged multifractal due to the ridges it tends to produce.

		noise.ApplyFilter("Perlin").Set(8.0f, 0.65f);

		// Now that we have our heightmap, we should create our terrain.
		mTerrain = mCore->GetRoot()->AddObject<Terrain>("First Terrain");

		// We want to partition our terrain into an 8 by 8 grid. This will create 64 subdivisions
		// that the terrain will use together with frustum culling to automatically discard portions
		// of the terrain that are not visible. We can actually see what percentage of the terrain
		// is being rendered by using the Terrain::GetVisibility() function after the scene has been
		// culled... but more on that later.

		mTerrain->PartitionInto(8, 8);

		// In order to fill the terrain's partitions with geometry we need to provide additional
		// information about the heightmap that will be used and how it will be used to begin with.
		// Terrain::Heightmap struct exists for just this purpose.

		// Provide the heightmap itself
		Terrain::Heightmap hm (noise.GetBuffer(), noise.GetWidth(), noise.GetHeight());

		// We want each subdivided mesh to be 32 by 32 quads. As you might recall there are 64 subdivisions
		// in total, and now each of those 64 will contain (32 x 32) = 1024 quads, or 2048 triangles.
		// When the terrain is generated the provided heightmap will be sampled using bicubic filtering,
		// so you can make the mesh much more tessellated than the heightmap, if you wish.

		hm.mMeshSize.Set(32, 32);

		// By default the terrain will be generated with dimensions of (0, 0, 0) to (1, 1, 1). Of course
		// that's not what we want. Let's apply a different scaling property here, stretching the terrain
		// along the horizontal plane (and a little bit along the vertical as well).
		hm.mTerrainScale.Set(20.0f, 20.0f, 4.0f);

		// By default the terrain starts at (0, 0, 0). Let's somwhat-center it instead.
		hm.mTerrainOffset.Set(-10.0f, -10.0f, -3.0f);

		// Time to fill the actual geometry. One last important thing to note is the optional bounding
		// box padding parameter that QuadTree::Fill function accepts. This parameter is used to extrude
		// the height of the bounding box vertically in both directions so that child objects can
		// fit easier. Objects that "fit" into the bounding box of the terrain's subdivisioned
		// nodes will get culled faster, speeding up your game. I recommend setting this property to
		// the height of the tallest building or tree you expect to place on your map. In this
		// example we don't have any objects placed as children of the terrain, but it's worth
		// noting nonetheless.

		mTerrain->FillGeometry(&hm, 0.0f);

		// And now... we need to be able to see the terrain we've just created.
		// The best way to visualize a terrain without any textures on it is to display it in wireframe.
		// You can easily do that in R5 by using a material that has a "Wireframe" technique as one of
		// its draw methods. As long as you won't forget to use that technique in the OnDraw function,
		// your wireframe object will show up in your scene. In this case it will be used for our terrain.

		// Wireframe is an R5-recognized technique so we don't need to set up any states.
		ITechnique* wireframe = mGraphics->GetTechnique("Wireframe");

		// Save it for our Draw function
		//mTechniques.Expand() = wireframe;

		// We'll be using a custom material to draw our terrain. Let's just give it the same name.
		IMaterial* mat = mGraphics->GetMaterial("Terrain");

		// Se need to change the material's color as all newly created materials start invisible (alpha of 0)
		mat->SetDiffuse( Color4ub(255, 255, 255, 255) );

		// Add this technique to the material
		mat->GetDrawMethod(wireframe, true);

		// Tell the terrain to use this material
		mTerrain->SetMaterial(mat);

		// Last thing we should do is find the label I've added to the "T08.txt" configuration file.
		// The reason it's not created via code is to simplify this tutorial. If you're curious,
		// have a look at that resource file and see how it was created inside. Since the label is
		// part of the configuration file that we've loaded at the top of this function, it's already
		// in memory and all we have to do is find it using this handy template:

		mLabel = mUI->FindWidget<UILabel>("Status");

		// Add a custom draw function that will update the label showing us how much of the terrain is
		// actually visible at any given time. Look below to see exactly what it does.
//.........这里部分代码省略.........
开发者ID:saggita,项目名称:r5ge,代码行数:101,代码来源:T08.cpp

示例2: compileOneFragment

/// Try and compile a fragment starting at the specified address. Returns
/// true if successful setting \a nextAddress to the first instruction after
/// the fragment. If unsuccessful returns false and sets \a nextAddress to the
/// address after the current function. \a endOfBlock is set to true if the
/// next address is in a new basic block.
bool JITImpl::
compileOneFragment(Core &core, JITCoreInfo &coreInfo, uint32_t startPc,
                   bool &endOfBlock, uint32_t &pcAfterFragment)
{
  assert(initialized);
  resetPerFunctionState();

  auto infoIt = coreInfo.functionMap.find(startPc);
  JITFunctionInfo *info =
    (infoIt == coreInfo.functionMap.end()) ? 0 : infoIt->second;
  if (info && !info->isStub) {
    endOfBlock = true;
    return false;
  }

  std::vector<InstructionOpcode> opcode;
  std::vector<Operands> operands;
  if (!getFragmentToCompile(core, core.fromRamPc(startPc), opcode, operands,
                            endOfBlock, pcAfterFragment)) {
    pcAfterFragment = core.toRamPc(pcAfterFragment);
    return false;
  }
  std::queue<std::pair<uint32_t,MemoryCheck*> > checks;
  placeMemoryChecks(opcode, operands, checks);

  LLVMValueRef f;
  if (info) {
    f = info->value;
    info->func = 0;
    info->isStub = false;
    deleteFunctionBody(f);
  } else {
    info = new JITFunctionInfo(startPc);
    coreInfo.functionMap.insert(std::make_pair(startPc, info));
    // Create function to contain the code we are about to add.
    info->value = f = LLVMAddFunction(module, "", jitFunctionType);
    LLVMSetFunctionCallConv(f, LLVMFastCallConv);
  }
  threadParam = LLVMGetParam(f, 0);
  LLVMValueRef ramBase =
    LLVMConstInt(LLVMInt32TypeInContext(context), core.getRamBase(), false);
  ramSizeLog2Param =
    LLVMConstInt(LLVMInt32TypeInContext(context), core.getRamSizeLog2(), false);
  LLVMBasicBlockRef entryBB =
    LLVMAppendBasicBlockInContext(context, f, "entry");
  LLVMPositionBuilderAtEnd(builder, entryBB);
  uint32_t pc = startPc;
  bool needsReturn = true;
  for (unsigned i = 0, e = opcode.size(); i != e; ++i) {
    InstructionOpcode opc = opcode[i];
    const Operands &ops = operands[i];
    InstructionProperties *properties = &instructionProperties[opc];
    uint32_t nextPc = pc + properties->size / 2;
    emitMemoryChecks(i, checks);

    // Lookup function to call.
    LLVMValueRef callee = LLVMGetNamedFunction(module, properties->function);
    assert(callee && "Function for instruction not found in module");
    LLVMTypeRef calleeType = LLVMGetElementType(LLVMTypeOf(callee));
    const unsigned fixedArgs = 4;
    const unsigned maxOperands = 6;
    unsigned numArgs = properties->getNumExplicitOperands() + fixedArgs;
    assert(LLVMCountParamTypes(calleeType) == numArgs);
    LLVMTypeRef paramTypes[fixedArgs + maxOperands];
    assert(numArgs <= (fixedArgs + maxOperands));
    LLVMGetParamTypes(calleeType, paramTypes);
    // Build call.
    LLVMValueRef args[fixedArgs + maxOperands];
    args[0] = threadParam;
    args[1] = LLVMConstInt(paramTypes[1], nextPc, false);
    args[2] = ramBase;
    args[3] = ramSizeLog2Param;
    for (unsigned i = fixedArgs; i < numArgs; i++) {
      uint32_t value =
      properties->getNumExplicitOperands() <= 3 ? ops.ops[i - fixedArgs] :
      ops.lops[i - fixedArgs];
      args[i] = LLVMConstInt(paramTypes[i], value, false);
    }
    LLVMValueRef call = emitCallToBeInlined(callee, args, numArgs);
    checkReturnValue(call, *properties);
    if (properties->mayBranch() && properties->function &&
        emitJumpToNextFragment(opc, ops, coreInfo, nextPc, info)) {
      needsReturn = false;
    }
    pc = nextPc;
  }
  assert(checks.empty() && "Not all checks emitted");
  if (needsReturn) {
    LLVMValueRef args[] = {
      threadParam
    };
    emitCallToBeInlined(functions.jitUpdateExecutionFrequency, args, 1);
    // Build return.
    LLVMBuildRet(builder,
                 LLVMConstInt(LLVMGetReturnType(jitFunctionType),
//.........这里部分代码省略.........
开发者ID:ajwlucas,项目名称:tool_axe,代码行数:101,代码来源:JIT.cpp

示例3: elf_errmsg

int BootSequenceStepElf::execute(ExecutionState &state)
{
  SystemState &sys = state.sys;
  BreakpointManager &BM = state.breakpointManager;
  const LoadedElf &loadedElf = state.elfManager.load(*core, elfSector);
  Elf *e = loadedElf.getElf();
  const char *buf = loadedElf.getBuf();
  if (elf_kind(e) != ELF_K_ELF) {
    std::cerr << "ELF section is not an ELF object" << std::endl;
    std::exit(1);
  }
  GElf_Ehdr ehdr;
  if (gelf_getehdr(e, &ehdr) == NULL) {
    std::cerr << "Reading ELF header failed: " << elf_errmsg(-1) << std::endl;
    std::exit(1);
  }
  if (ehdr.e_machine != XCORE_ELF_MACHINE &&
      ehdr.e_machine != XCORE_ELF_MACHINE_OLD) {
    std::cerr << "Not a XCore ELF" << std::endl;
    std::exit(1);
  }
  uint32_t entryPoint = core->getRamBase();
  if (ehdr.e_entry != 0) {
    if (core->isValidRamAddress(ehdr.e_entry)) {
      entryPoint = ehdr.e_entry;
    } else {
      std::cout << "Warning: invalid ELF entry point 0x";
      std::cout << std::hex << ehdr.e_entry << std::dec << "\n";
    }
  }
  uint32_t ram_base = core->getRamBase();
  uint32_t ram_size = core->getRamSize();
  if (loadImage) {
    unsigned num_phdrs = ehdr.e_phnum;
    if (num_phdrs == 0) {
      std::cerr << "No ELF program headers" << std::endl;
      std::exit(1);
    }
    for (unsigned i = 0; i < num_phdrs; i++) {
      GElf_Phdr phdr;
      if (gelf_getphdr(e, i, &phdr) == NULL) {
        std::cerr << "Reading ELF program header " << i << " failed: ";
        std::cerr << elf_errmsg(-1) << std::endl;
        std::exit(1);
      }
      if (phdr.p_filesz == 0) {
        continue;
      }
      if (phdr.p_offset > elfSector->getElfSize()) {
        std::cerr << "Invalid offet in ELF program header" << i << std::endl;
        std::exit(1);
      }
      if (core->isValidRamAddress(phdr.p_paddr) &&
          core->isValidRamAddress(phdr.p_paddr + phdr.p_memsz)) {
        core->writeMemory(phdr.p_paddr, &buf[phdr.p_offset], phdr.p_filesz);
      } else if (!hasValidVirtualAddress(phdr, *core)) {
        std::cerr << "Error data from ELF program header " << i;
        std::cerr << " does not fit in memory" << std::endl;
        std::exit(1);
      }
    }
  }

  std::unique_ptr<CoreSymbolInfo> CSI;
  readSymbols(e, ram_base, ram_base + ram_size, CSI);
  SymbolInfo &SI = sys.getSymbolInfo();
  SI.add(core, std::move(CSI));

  // Patch in syscall instruction at the syscall address.
  if (const ElfSymbol *syscallSym = SI.getGlobalSymbol(core, "_DoSyscall")) {
    if (!BM.setBreakpoint(*core, syscallSym->value, BreakpointType::Syscall)) {
      std::cout << "Warning: invalid _DoSyscall address "
      << std::hex << syscallSym->value << std::dec << "\n";
    }
  }
  // Patch in exception instruction at the exception address
  if (const ElfSymbol *doExceptionSym = SI.getGlobalSymbol(core, "_DoException")) {
    if (!BM.setBreakpoint(*core, doExceptionSym->value,
                          BreakpointType::Exception)) {
      std::cout << "Warning: invalid _DoException address "
      << std::hex << doExceptionSym->value << std::dec << "\n";
    }
  }
  if (useElfEntryPoint) {
    sys.schedule(core->getThread(0));
    core->getThread(0).setPcFromAddress(entryPoint);
  }

  return 0;
}
开发者ID:xcore,项目名称:tool_axe,代码行数:90,代码来源:BootSequencer.cpp

示例4: tr

void PrivacyForm::onEncryptLogsUpdated()
{
    Core* core = Core::getInstance();

    if (bodyUI->cbEncryptHistory->isChecked())
    {
        if (!core->isPasswordSet(Core::ptHistory))
        {
            if (setChatLogsPassword())
            {
                bodyUI->cbEncryptHistory->setChecked(true);
                bodyUI->changeLogsPwButton->setEnabled(true);
                return;
            }
        }
    }
    else
    {
        QMessageBox::StandardButton button = QMessageBox::warning(
            Widget::getInstance(),
            tr("Old encrypted chat history", "title"),
            tr("Would you like to decrypt your chat history?\nOtherwise it will be deleted."),
            QMessageBox::Ok | QMessageBox::No | QMessageBox::Cancel,
            QMessageBox::Cancel
        );

        if (button == QMessageBox::Ok)
        {
            QList<HistoryKeeper::HistMessage> oldMessages = HistoryKeeper::exportMessagesDeleteFile(true);
            core->clearPassword(Core::ptHistory);
            Settings::getInstance().setEncryptLogs(false);
            HistoryKeeper::getInstance()->importMessages(oldMessages);
        }
        else if (button == QMessageBox::No)
        {
            if (QMessageBox::critical(
                    Widget::getInstance(),
                    tr("Old encrypted chat history", "title"),
                    tr("Are you sure you want to lose your entire chat history?"),
                    QMessageBox::Yes | QMessageBox::Cancel,
                    QMessageBox::Cancel
                    )
                == QMessageBox::Yes)
            {
                HistoryKeeper::removeHistory(true);
            }
            else
            {
                bodyUI->cbEncryptHistory->setChecked(true);
                return;
            }
        }
        else
        {
            bodyUI->cbEncryptHistory->setChecked(true);
            return;
        }
    }

    core->clearPassword(Core::ptHistory);
    Settings::getInstance().setEncryptLogs(false);
    bodyUI->cbEncryptHistory->setChecked(false);
    bodyUI->changeLogsPwButton->setEnabled(false);
    HistoryKeeper::resetInstance();
}
开发者ID:krepa098,项目名称:qTox,代码行数:65,代码来源:privacyform.cpp

示例5: f

ChatForm::ChatForm(Friend* chatFriend)
    : f(chatFriend)
    , isTyping{false}
{
    Core* core = Core::getInstance();
    coreav = core->getAv();

    nameLabel->setText(f->getDisplayedName());

    avatar->setPixmap(QPixmap(":/img/contact_dark.svg"), Qt::transparent);

    statusMessageLabel = new CroppingLabel();
    statusMessageLabel->setObjectName("statusLabel");
    statusMessageLabel->setFont(Style::getFont(Style::Medium));
    statusMessageLabel->setMinimumHeight(Style::getFont(Style::Medium).pixelSize());
    statusMessageLabel->setTextFormat(Qt::PlainText);

    callConfirm = nullptr;
    offlineEngine = new OfflineMsgEngine(f);

    typingTimer.setSingleShot(true);

    callDurationTimer = nullptr;
    disableCallButtonsTimer = nullptr;

    chatWidget->setTypingNotification(ChatMessage::createTypingNotification());

    headTextLayout->addWidget(statusMessageLabel);
    headTextLayout->addStretch();
    callDuration = new QLabel();
    headTextLayout->addWidget(callDuration, 1, Qt::AlignCenter);
    callDuration->hide();

    chatWidget->setMinimumHeight(160);
    connect(this, &GenericChatForm::messageInserted, this, &ChatForm::onMessageInserted);

    loadHistoryAction = menu.addAction(QString(), this, SLOT(onLoadHistory()));

    connect(core, &Core::fileSendStarted, this, &ChatForm::startFileSend);
    connect(sendButton, &QPushButton::clicked, this, &ChatForm::onSendTriggered);
    connect(fileButton, &QPushButton::clicked, this, &ChatForm::onAttachClicked);
    connect(screenshotButton, &QPushButton::clicked, this, &ChatForm::onScreenshotClicked);
    connect(callButton, &QPushButton::clicked, this, &ChatForm::onCallTriggered);
    connect(videoButton, &QPushButton::clicked, this, &ChatForm::onVideoCallTriggered);
    connect(msgEdit, &ChatTextEdit::enterPressed, this, &ChatForm::onSendTriggered);
    connect(msgEdit, &ChatTextEdit::textChanged, this, &ChatForm::onTextEditChanged);
    connect(core, &Core::fileSendFailed, this, &ChatForm::onFileSendFailed);
    connect(this, &ChatForm::chatAreaCleared, getOfflineMsgEngine(), &OfflineMsgEngine::removeAllReciepts);
    connect(&typingTimer, &QTimer::timeout, this, [=]{
        Core::getInstance()->sendTyping(f->getFriendID(), false);
        isTyping = false;
    } );
    connect(nameLabel, &CroppingLabel::editFinished, this, [=](const QString& newName)
    {
        nameLabel->setText(newName);
        emit aliasChanged(newName);
    } );

    setAcceptDrops(true);

    retranslateUi();
    Translator::registerHandler(std::bind(&ChatForm::retranslateUi, this), this);
}
开发者ID:TheNain38,项目名称:qTox,代码行数:63,代码来源:chatform.cpp

示例6: printf

bool
Script::_ExecuteAction(action_node* act)
{
#if DEBUG_SCRIPTS
	printf("SCRIPT: %s (%d 0x%x)\n", IDTable::ActionAt(act->id).c_str(), act->id, act->id);
	act->Print();
#endif
	Core* core = Core::Get();
	Actor* thisActor = dynamic_cast<Actor*>(fTarget.Target());

	switch (act->id) {
		case 0x03:
		{
			/* Attack(O:Target*) */
			Object* targetObject = FindObject(act);
			if (targetObject != NULL) {
				Actor* targetActor = dynamic_cast<Actor*>(targetObject);
				if (thisActor != NULL && targetActor != NULL) {
					Attack* attackAction = new Attack(thisActor, targetActor);
					thisActor->AddAction(attackAction);
				}
			}
			break;
		}
		case 0x07:
		{
			/* CreateCreature(S:NewObject*,P:Location*,I:Face*) */
			// TODO: If point is (-1, -1) we should put the actor near
			// the active creature. Which one is the active creature?
			IE::point point = act->where;
			if (point.x == -1 && point.y == -1) {
				point = Game::Get()->Party()->ActorAt(0)->Position();
				point.x += Core::RandomNumber(-20, 20);
				point.y += Core::RandomNumber(-20, 20);
			}

			Actor* actor = new Actor(act->string1, point, act->integer1);
			RoomContainer::Get()->ActorEnteredArea(actor);

			// TODO: Add actor to the current area
			break;
		}

		case 0x8:
		{
			/*	DIALOGUE(O:OBJECT*) (8 0x8) */
			Actor* actor = dynamic_cast<Actor*>(FindObject(act));
			if (actor != NULL) {
				Dialogue* dialogueAction = new Dialogue(thisActor, actor);
				thisActor->AddAction(dialogueAction);
			}
			break;
		}
		case 0xA:
		{
			/* ENEMY() (10 0xa) */
			uint32 id = IDTable::EnemyAllyValue("ENEM");
			thisActor->SetEnemyAlly(id);
			break;
		}
		case 22:
		{
			// MoveToObject
			Object* object = FindObject(act);
			if (object != NULL) {
				WalkTo* walkTo = new WalkTo(thisActor, object->Position());
				fTarget.Target()->AddAction(walkTo);
			}

			break;
		}
		case 23:
		{
			// MoveToPoint
			Actor* actor = dynamic_cast<Actor*>(fTarget.Target());
			if (actor != NULL) {
				WalkTo* walkTo = new WalkTo(actor, act->where);
				actor->AddAction(walkTo);
				actor->StopCheckingConditions();
			}
			break;
		}
		case 29:
		{
			/* RunAwayFrom(O:Creature*,I:Time*) */
			Actor* targetActor = dynamic_cast<Actor*>(FindObject(act));
			if (targetActor != NULL && thisActor != NULL) {
				RunAwayFrom* run = new RunAwayFrom(thisActor, targetActor);
				fTarget.Target()->AddAction(run);
			}
			break;
		}
		case 36:
		{
			/*
			 * 36 Continue()
			 * This action instructs the script parser to continue looking
			 * for actions in the active creatures action list.
			 * This is mainly included in scripts for efficiency.
			 * Continue should also be appended to any script blocks added
//.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:101,代码来源:

示例7: f

/**
@brief Saves the current settings back to file
*/
void SettingsSerializer::save()
{
    QSaveFile f(path);
    if (!f.open(QIODevice::Truncate | QIODevice::WriteOnly))
    {
        qWarning() << "Couldn't open file";
        return;
    }

    QByteArray data(magic, 4);
    QDataStream stream(&data, QIODevice::ReadWrite | QIODevice::Append);
    stream.setVersion(QDataStream::Qt_5_0);

    for (int g=-1; g<groups.size(); g++)
    {
        // Save the group name, if any
        if (g!=-1)
        {
            writeStream(stream, RecordTag::GroupStart);
            writeStream(stream, groups[g].toUtf8());
        }

        // Save all the arrays of this group
        for (const Array& a : arrays)
        {
            if (a.group != g)
                continue;
            if (a.size <= 0)
                continue;
            writeStream(stream, RecordTag::ArrayStart);
            writeStream(stream, a.name.toUtf8());
            writeStream(stream, vintToData(a.size));

            for (int vi : a.values)
            {
                const Value& v = values[vi];
                writeStream(stream, RecordTag::ArrayValue);
                writeStream(stream, vintToData(values[vi].arrayIndex));
                writeStream(stream, v.key.toUtf8());
                writePackedVariant(stream, v.value);
            }
            writeStream(stream, RecordTag::ArrayEnd);
        }

        // Save all the values of this group that aren't in an array
        for (const Value& v : values)
        {
            if (v.group != g || v.array != -1)
                continue;
            writeStream(stream, RecordTag::Value);
            writeStream(stream, v.key.toUtf8());
            writePackedVariant(stream, v.value);
        }
    }

    // Encrypt
    if (!password.isEmpty())
    {
        Core* core = Nexus::getCore();
        auto passkey = core->createPasskey(password);
        data = core->encryptData(data, *passkey);
    }

    f.write(data);

    // check if everything got written
    if (f.flush())
    {
        f.commit();
    }
    else
    {
        f.cancelWriting();
        qCritical() << "Failed to write, can't save!";
    }
}
开发者ID:CuiZhicheng,项目名称:qTox,代码行数:79,代码来源:settingsserializer.cpp

示例8: get_max_volume

ErrorCode get_max_volume(Core &mb,  EntityHandle fileset, int dim, double &vmax)
{
  ErrorCode error;
  VerdictWrapper vw(&mb);
  QualityType q;

  switch (dim) {
    case 1: q = MB_LENGTH; break;
    case 2: q = MB_AREA; break;
    case 3: q = MB_VOLUME; break;
    default: return MB_FAILURE; break;
    }

  //Get all entities of the highest dimension which is passed as a command line argument.
  Range allents, owned;
  error = mb.get_entities_by_handle(fileset, allents);MB_CHK_ERR(error);
  owned = allents.subset_by_dimension(dim);MB_CHK_ERR(error);

  //Get all owned entities
#ifdef MOAB_HAVE_MPI
  int size = 1;
  MPI_Comm_size( MPI_COMM_WORLD, &size );
  int mpi_err;
  if (size>1)
    {
      // filter the entities not owned, so we do not process them more than once
      ParallelComm* pcomm = moab::ParallelComm::get_pcomm(&mb, 0);
      Range current = owned;
      owned.clear();
      error = pcomm->filter_pstatus(current, PSTATUS_NOT_OWNED, PSTATUS_NOT, -1, &owned);
      if (error != MB_SUCCESS)
        {
          MPI_Finalize();
          return MB_FAILURE;
        }
    }
#endif

  double vmax_local=0;
  //Find the maximum volume of an entity in the owned mesh
  for (Range::iterator it=owned.begin(); it != owned.end(); it++)
    {
      double volume;
      error = vw.quality_measure(*it, q, volume);MB_CHK_ERR(error);
      if (volume >vmax_local)
        vmax_local = volume;
    }

  //Get the global maximum
  double vmax_global = vmax_local;
#ifdef MOAB_HAVE_MPI
  mpi_err = MPI_Reduce(&vmax_local, &vmax_global, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD);
  if (mpi_err)
      {
        MPI_Finalize();
        return MB_FAILURE;
      }
#endif

  vmax = vmax_global;

  return MB_SUCCESS;
}
开发者ID:obmun,项目名称:moab,代码行数:63,代码来源:umr.cpp

示例9: executeCore

void OS::executeCore(unsigned int n, unsigned int unitTick) {
    Core *core = env->getCore(n);
    core->run(unitTick);
}
开发者ID:yb-kim,项目名称:osSim,代码行数:4,代码来源:os.cpp

示例10: Bestmove

int Think::Bestmove(
	Core			core			,
	int				color			,
	Board*			pBoard			,
	LibertyOfNodes*	pLibertyOfNodes
)
{
#ifdef CHECK_LOG
	core.PRT( _T("Bestmove開始☆! \n"));
#endif

#ifdef ENABLE_MOVE_RETRY
	int retry = 0;
	// 異常回避☆! リトライ☆!
	gt_Retry:
		;
#endif


	int maxScore;	// 今まで読んだ手で一番高かった評価値
	int bestmoveNode;

	// 実行するたびに違う値が得られるように現在の時刻で乱数を初期化
	srand((unsigned)clock());

	//----------------------------------------
	// 石を置く位置1つずつ、その手の評価値を算出します。
	//----------------------------------------
	maxScore = -1;
	bestmoveNode = 0; // 0 ならパス。

	pBoard->ForeachAllNodesWithoutWaku([color,&maxScore,&bestmoveNode,&pBoard,&pLibertyOfNodes, &core](int node, bool& isBreak) {
		//{
			//int x, y;
			//AbstractBoard::ConvertToXy(x, y, node);
			//core.PRT(_T("#(%d,%d) "), x, y);
		//}

		// この局面で、石を置いたときの評価値
		int flgAbort = 0;
		int score;		// 読んでいる手の評価値
		score = Evaluation::EvaluateAtNode(core, flgAbort, color, node, pBoard, pLibertyOfNodes);
		if (flgAbort)
		{
			goto gt_Next;
		}

		// ベストムーブを更新します。
		// PRT("x,y=(%d,%d)=%d\n",x,y,score);
		if (maxScore < score) {
			maxScore = score;
			bestmoveNode = node;
		}
	gt_Next:
		;
	});

#ifdef ENABLE_MOVE_RETRY

	int x, y;
	AbstractBoard::ConvertToXy(x, y, bestmoveNode);

	// 異常回避☆! リトライ☆!
	if (bestmoveNode==0)
	{
		// パスは正常です。
		goto gt_EndMethod;
	}
	else if (400<retry)
	{
		// 諦めてパスにします。
		bestmoveNode = 0;
		goto gt_EndMethod;
	}
	else if (pBoard->ValueOf(bestmoveNode) == BLACK || pBoard->ValueOf(bestmoveNode) == WHITE) {
		// 石があるなら
		core.PRT(_T("(%d,%d) 石がある。 リトライ☆! [%d]\n"), x,y, retry);
		retry++;
		goto gt_Retry;
	}
	else if (pBoard->ValueOf(bestmoveNode) == WAKU) {
		// 枠なら
		core.PRT(_T("(%d,%d) 枠だった。 リトライ☆! [%d]\n"), x, y, retry);
		retry++;
		goto gt_Retry;
	}
	else if (bestmoveNode == pBoard->kouNode) {
		// コウになる位置なら
		core.PRT(_T("(%d,%d) コウになる。 リトライ☆! [%d]\n"), x, y, retry);
		retry++;
		goto gt_Retry;
	}

	Liberty liberties[4];// 上隣 → 右隣 → 下隣 → 左隣
	pBoard->ForeachArroundDirAndNodes(bestmoveNode, [&pBoard, &liberties](int iDir, int adjNode, bool& isBreak) {
		int adjColor = pBoard->ValueOf(adjNode);			// 上下左右隣(adjacent)の石の色
		liberties[iDir].Count(adjNode, adjColor, pBoard);	// 隣の石(または連)の呼吸点 の数を数えます。
	});

	// 自分の眼潰しチェック
//.........这里部分代码省略.........
开发者ID:muzudho,项目名称:Kifuwarabe_Uec9_Cgfthink,代码行数:101,代码来源:n700_200_think.cpp

示例11: readElf

static void readElf(const char *filename, const XEElfSector *elfSector,
                    Core &core, std::auto_ptr<CoreSymbolInfo> &SI,
                    std::map<Core*,uint32_t> &entryPoints)
{
  uint64_t ElfSize = elfSector->getElfSize();
  const scoped_array<char> buf(new char[ElfSize]);
  if (!elfSector->getElfData(buf.get())) {
    std::cerr << "Error reading elf data from \"" << filename << "\"" << std::endl;
    std::exit(1);
  }

  if (elf_version(EV_CURRENT) == EV_NONE) {
    std::cerr << "ELF library intialisation failed: "
              << elf_errmsg(-1) << std::endl;
    std::exit(1);
  }
  Elf *e;
  if ((e = elf_memory(buf.get(), ElfSize)) == NULL) {
    std::cerr << "Error reading ELF: " << elf_errmsg(-1) << std::endl;
    std::exit(1);
  }
  if (elf_kind(e) != ELF_K_ELF) {
    std::cerr << filename << " is not an ELF object" << std::endl;
    std::exit(1);
  }
  GElf_Ehdr ehdr;
  if (gelf_getehdr(e, &ehdr) == NULL) {
    std::cerr << "Reading ELF header failed: " << elf_errmsg(-1) << std::endl;
    std::exit(1);
  }
  if (ehdr.e_machine != XCORE_ELF_MACHINE) {
    std::cerr << "Not a XCore ELF" << std::endl;
    std::exit(1);
  }
  if (ehdr.e_entry != 0) {
    entryPoints.insert(std::make_pair(&core, (uint32_t)ehdr.e_entry));
  }
  unsigned num_phdrs = ehdr.e_phnum;
  if (num_phdrs == 0) {
    std::cerr << "No ELF program headers" << std::endl;
    std::exit(1);
  }
  core.resetCaches();
  uint32_t ram_base = core.ram_base;
  uint32_t ram_size = core.getRamSize();
  for (unsigned i = 0; i < num_phdrs; i++) {
    GElf_Phdr phdr;
    if (gelf_getphdr(e, i, &phdr) == NULL) {
      std::cerr << "Reading ELF program header " << i << " failed: " << elf_errmsg(-1) << std::endl;
      std::exit(1);
    }
    if (phdr.p_filesz == 0) {
      continue;
    }
    if (phdr.p_offset > ElfSize) {
    	std::cerr << "Invalid offet in ELF program header" << i << std::endl;
    	std::exit(1);
    }
    if (!core.isValidAddress(phdr.p_paddr) ||
        !core.isValidAddress(phdr.p_paddr + phdr.p_memsz)) {
      std::cerr << "Error data from ELF program header " << i;
      std::cerr << " does not fit in memory" << std::endl;
      std::exit(1);
    }
    core.writeMemory(phdr.p_paddr, &buf[phdr.p_offset], phdr.p_filesz);
  }

  readSymbols(e, ram_base, ram_base + ram_size, SI);

  elf_end(e);
}
开发者ID:hoangt,项目名称:tool_axe,代码行数:71,代码来源:main.cpp

示例12: main

int main(int args, char **argp)
{
	Core* core = new Core();
	core->CoreEntry();
}
开发者ID:rpheuts,项目名称:artillery,代码行数:5,代码来源:Main.cpp

示例13: onGroupAction

void Core::onGroupAction(Tox*, int groupnumber, int peernumber, const uint8_t *action, uint16_t length, void* _core)
{
    Core* core = static_cast<Core*>(_core);
    emit core->groupMessageReceived(groupnumber, peernumber, CString::toString(action, length), true);
}
开发者ID:Pik-9,项目名称:qTox,代码行数:5,代码来源:core.cpp

示例14: compute_partition

ErrorCode ScdInterface::construct_box(HomCoord low, HomCoord high, const double * const coords, unsigned int num_coords,
                                      ScdBox *& new_box, int * const lperiodic, ScdParData *par_data,
                                      bool assign_gids, int tag_shared_ents)
{
    // create a rectangular structured mesh block
  ErrorCode rval;

  int tmp_lper[3] = {0, 0, 0};
  if (lperiodic) std::copy(lperiodic, lperiodic+3, tmp_lper);
  
#ifndef MOAB_HAVE_MPI
  if (-1 != tag_shared_ents) ERRORR(MB_FAILURE, "Parallel capability requested but MOAB not compiled parallel.");
  if (-1 == tag_shared_ents && !assign_gids) assign_gids = true; // need to assign gids in order to tag shared verts
#else
  if (par_data && low == high && ScdParData::NOPART != par_data->partMethod) {
      // requesting creation of parallel mesh, so need to compute partition
    if (!par_data->pComm) {
        // this is a really boneheaded way to have to create a PC
      par_data->pComm = ParallelComm::get_pcomm(mbImpl, 0);
      if (NULL == par_data->pComm) par_data->pComm = new ParallelComm(mbImpl, MPI_COMM_WORLD);
    }
    int ldims[6];
    rval = compute_partition(par_data->pComm->size(), par_data->pComm->rank(), *par_data, 
                             ldims, tmp_lper, par_data->pDims);
    ERRORR(rval, "Error returned from compute_partition.");
    low.set(ldims[0],ldims[1],ldims[2]);
    high.set(ldims[3],ldims[4],ldims[5]);
    if (par_data->pComm->get_debug_verbosity() > 0) {
      std::cout << "Proc " << par_data->pComm->rank() << ": " << *par_data;
      std::cout << "Proc " << par_data->pComm->rank() << " local dims: " 
                << low << "-" << high << std::endl;
    }
  }
#endif
  
  HomCoord tmp_size = high - low + HomCoord(1, 1, 1, 0);
  if ((tmp_size[1] && num_coords && (int)num_coords < tmp_size[0]) ||
      (tmp_size[2] && num_coords && (int)num_coords < tmp_size[0]*tmp_size[1]))
    return MB_FAILURE;

  rval = create_scd_sequence(low, high, MBVERTEX, 0, new_box);
  ERRORR(rval, "Trouble creating scd vertex sequence.");

    // set the vertex coordinates
  double *xc, *yc, *zc;
  rval = new_box->get_coordinate_arrays(xc, yc, zc);
  ERRORR(rval, "Couldn't get vertex coordinate arrays.");

  if (coords && num_coords) {
    unsigned int i = 0;
    for (int kl = low[2]; kl <= high[2]; kl++) {
      for (int jl = low[1]; jl <= high[1]; jl++) {
        for (int il = low[0]; il <= high[0]; il++) {
          xc[i] = coords[3*i];
          if (new_box->box_size()[1])
            yc[i] = coords[3*i+1];
          if (new_box->box_size()[2])
            zc[i] = coords[3*i+2];
          i++;
        }
      }
    }
  }
  else {
    unsigned int i = 0;
    for (int kl = low[2]; kl <= high[2]; kl++) {
      for (int jl = low[1]; jl <= high[1]; jl++) {
        for (int il = low[0]; il <= high[0]; il++) {
          xc[i] = (double) il;
          if (new_box->box_size()[1])
            yc[i] = (double) jl;
          else yc[i] = 0.0;
          if (new_box->box_size()[2])
            zc[i] = (double) kl;
          else zc[i] = 0.0;
          i++;
        }
      }
    }
  }

    // create element sequence
  Core *mbcore = dynamic_cast<Core*>(mbImpl);
  SequenceManager *seq_mgr = mbcore->sequence_manager();

  EntitySequence *tmp_seq;
  EntityHandle start_ent;

    // construct the sequence
  EntityType this_tp = MBHEX;
  if (1 >= tmp_size[2]) this_tp = MBQUAD;
  if (1 >= tmp_size[2] && 1 >= tmp_size[1]) this_tp = MBEDGE;
  rval = seq_mgr->create_scd_sequence(low, high, this_tp, 0, start_ent, tmp_seq, 
                                      tmp_lper);
  ERRORR(rval, "Trouble creating scd element sequence.");

  new_box->elem_seq(tmp_seq);
  new_box->start_element(start_ent);

    // add vertex seq to element seq, forward orientation, unity transform
//.........这里部分代码省略.........
开发者ID:obmun,项目名称:moab,代码行数:101,代码来源:ScdInterface.cpp

示例15: onGroupMessage

void Core::onGroupMessage(Tox*, int groupnumber, int peernumber, const uint8_t * message, uint16_t length, void *_core)
{
    Core* core = static_cast<Core*>(_core);
    emit core->groupMessageReceived(groupnumber, peernumber, CString::toString(message, length), false);
}
开发者ID:Pik-9,项目名称:qTox,代码行数:5,代码来源:core.cpp


注:本文中的Core类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。