Esempio n. 1
0
util::BoundingBox<util::Vec3d> ModelEntityLogic::getBoundingBox() const {
	PROFILE();
	
	if (!getDef().getModel())
		return BoundingBox::zero();

	ensure(getDef().getModel());

	auto model_bb= getDef().getModel()->getBoundingBox();
	if (!model_bb.isSet())
		return BoundingBox::zero();
	
	/// @todo More precise solution
	
	std::array<util::Vec3f, 4> bb_v= {
		model_bb.getMin(),
		model_bb.getMax(),
		util::Vec3f{	model_bb.getMin().x,
						model_bb.getMax().y,
						model_bb.getMin().z },
		util::Vec3f{	model_bb.getMax().x,
						model_bb.getMin().y,
						model_bb.getMax().z }
	};

	util::Vec3d rad= util::Vec3d(1.0)*sqrt(	std::max({	bb_v[0].lengthSqr(),
											bb_v[1].lengthSqr(),
											bb_v[2].lengthSqr(),
											bb_v[3].lengthSqr()})*
								getDef().getOffset().scale.lengthSqr()*
								getTransform().scale.lengthSqr());
	
	return util::BoundingBox<util::Vec3d>(-rad, rad);
}
Esempio n. 2
0
bool
Instruction::writesPredicate() const
{
   for (int d = 0; defExists(d); ++d)
      if (getDef(d)->inFile(FILE_PREDICATE) || getDef(d)->inFile(FILE_FLAGS))
         return true;
   return false;
}
bool StrengthReductionReversalPass::execute(UserProc *proc)
{
    StatementList stmts;
    proc->getStatements(stmts);

    for (Statement *s : stmts) {
        if (!s->isAssign()) {
            continue;
        }

        Assign *as = static_cast<Assign *>(s);

        // of the form x = x{p} + c
        if ((as->getRight()->getOper() == opPlus) && as->getRight()->getSubExp1()->isSubscript() &&
            (*as->getLeft() == *as->getRight()->getSubExp1()->getSubExp1()) &&
            as->getRight()->getSubExp2()->isIntConst()) {
            int c  = as->getRight()->access<Const, 2>()->getInt();
            auto r = as->getRight()->access<RefExp, 1>();

            if (r->getDef() && r->getDef()->isPhi()) {
                PhiAssign *p = static_cast<PhiAssign *>(r->getDef());

                if (p->getNumDefs() == 2) {
                    Statement *first  = p->begin()->getDef();
                    Statement *second = p->rbegin()->getDef();

                    if (first == as) {
                        // want the increment in second
                        std::swap(first, second);
                    }

                    // first must be of form x := 0
                    if (first && first->isAssign() &&
                        static_cast<Assign *>(first)->getRight()->isIntConst() &&
                        static_cast<Assign *>(first)->getRight()->access<Const>()->getInt() == 0) {
                        // ok, fun, now we need to find every reference to p and
                        // replace with x{p} * c
                        StatementList stmts2;
                        proc->getStatements(stmts2);

                        for (Statement *stmt2 : stmts2) {
                            if (stmt2 != as) {
                                stmt2->searchAndReplace(
                                    *r, Binary::get(opMult, r->clone(), Const::get(c)));
                            }
                        }

                        // that done we can replace c with 1 in as
                        as->getRight()->access<Const, 2>()->setInt(1);
                    }
                }
            }
        }
    }

    return true;
}
Esempio n. 4
0
QString LatexTables::getSimplifiedDef(QDocumentCursor &cur){
	QString def=getDef(cur);
	QStringList l_defs=splitColDef(def);
	def=l_defs.join("");
	def.remove('|');
	return def;
}
Esempio n. 5
0
bool
Instruction::canCommuteDefDef(const Instruction *i) const
{
   for (int d = 0; defExists(d); ++d)
      for (int c = 0; i->defExists(c); ++c)
         if (getDef(d)->interfers(i->getDef(c)))
            return false;
   return true;
}
Esempio n. 6
0
unsigned int
Instruction::defCount(unsigned int mask, bool singleFile) const
{
   unsigned int i, n;

   if (singleFile) {
      unsigned int d = ffs(mask);
      if (!d)
         return 0;
      for (i = d--; defExists(i); ++i)
         if (getDef(i)->reg.file != getDef(d)->reg.file)
            mask &= ~(1 << i);
   }

   for (n = 0, i = 0; this->defExists(i); ++i, mask >>= 1)
      n += mask & 1;
   return n;
}
Esempio n. 7
0
bool
Instruction::canCommuteDefSrc(const Instruction *i) const
{
   for (int d = 0; defExists(d); ++d)
      for (int s = 0; i->srcExists(s); ++s)
         if (getDef(d)->interfers(i->getSrc(s)))
            return false;
   return true;
}
Esempio n. 8
0
uint32 ModelEntityLogic::getBatchCompatibilityHash() const {
	return	util::hash32(
				util::makeTuple(
					getDef().getBatchCompatibilityHash(),
					customDrawPriority,
					useCustomDrawPriority,
					static_cast<int32>(getLayer())
				)
			);
}
Esempio n. 9
0
uint32 ModelEntityLogic::getContentHash() const {
	return	util::hash32(
				util::makeTuple(
					getDef().getContentHash(),
					customDrawPriority,
					useCustomDrawPriority,
					colorMul,
					getTransform()
				)
			);
}
Esempio n. 10
0
void Pokemon::SetStatsForLevel()
{
	setHP(round(ceil(2 * getBaseHP() + 31) * getLevel() / 100 + getLevel() + 10));
   setAtt(round(ceil(2 * getBaseAtt() + 31) * getLevel() / 100 + 5));
   setDef(round(ceil(2 * getBaseDef() + 31) * getLevel() / 100 + 5));
   setSpeed(round(ceil(2 * getBaseSpeed() + 31) * getLevel() / 100 + 5));

	setCurrentHP(getHP());
	setCurrentAtt(getAtt());
	setCurrentDef(getDef());
	setCurrentSpeed(getSpeed());
}
Esempio n. 11
0
void Cell::loadEmptyCell ()
{
  setFlagStr(INVALID_STR);

  setType (0);

  setLhs (-1);

  _rhsDim = -1;
  _rhs = NULL;

  _detwindow = NULL;

  setI(-1);

  getOffset().w = -1;
  getOffset().blocklabel = -1;

  _anchorDim = -1;
  _anchor = NULL;

  for (int i = 0; i < 4; i++)
    getDef().w[i] = -1;

  getDef().blocklabel = -1;
  getDef().flip = false;
  getDef().symmetric = 0;

  _scoreDim = -1;
  _score = NULL;

  _IxDim = -1;
  _Ix = NULL;

  _IyDim = -1;
  _Iy = NULL;
}
Esempio n. 12
0
Instruction *
Instruction::clone(ClonePolicy<Function>& pol, Instruction *i) const
{
   if (!i)
      i = new_Instruction(pol.context(), op, dType);
#ifndef NDEBUG // non-conformant assert, so this is required
   assert(typeid(*i) == typeid(*this));
#endif

   pol.set<Instruction>(this, i);

   i->sType = sType;

   i->rnd = rnd;
   i->cache = cache;
   i->subOp = subOp;

   i->saturate = saturate;
   i->join = join;
   i->exit = exit;
   i->mask = mask;
   i->ftz = ftz;
   i->dnz = dnz;
   i->ipa = ipa;
   i->lanes = lanes;
   i->perPatch = perPatch;

   i->postFactor = postFactor;

   for (int d = 0; defExists(d); ++d)
      i->setDef(d, pol.get(getDef(d)));

   for (int s = 0; srcExists(s); ++s) {
      i->setSrc(s, pol.get(getSrc(s)));
      i->src(s).mod = src(s).mod;
   }

   i->cc = cc;
   i->predSrc = predSrc;
   i->flagsDef = flagsDef;
   i->flagsSrc = flagsSrc;

   return i;
}
Esempio n. 13
0
// Tries to evaluate the integer constant of a value. The \p depth is used
// to limit the complexity.
ConstantTracker::IntConst ConstantTracker::getIntConst(SILValue val, int depth) {

  // Don't spend too much time with constant evaluation.
  if (depth >= 10)
    return IntConst();
  
  SILInstruction *I = getDef(val);
  if (!I)
    return IntConst();
  
  if (auto *IL = dyn_cast<IntegerLiteralInst>(I)) {
    return IntConst(IL->getValue(), IL->getFunction() != F);
  }
  if (auto *BI = dyn_cast<BuiltinInst>(I)) {
    if (constCache.count(BI) != 0)
      return constCache[BI];
    
    IntConst builtinConst = getBuiltinConst(BI, depth + 1);
    constCache[BI] = builtinConst;
    return builtinConst;
  }
  return IntConst();
}
Esempio n. 14
0
void *Commands::processEvent(Event *e)
{
    BarShow *b;
    ProcessMenuParam *mp;
    switch (e->type()){
    case EventPluginsUnload:
        clear();
        break;
    case EventToolbarCreate:
        return (void*)createBar((unsigned)(e->param()));
    case EventToolbarRemove:
        removeBar((unsigned)(e->param()));
        break;
    case EventShowBar:
        b = (BarShow*)(e->param());
        return show(b->bar_id, b->parent);
    case EventMenuCreate:
        return (void*)createMenu((unsigned)(e->param()));
    case EventMenuRemove:
        removeMenu((unsigned)(e->param()));
        break;
    case EventGetMenu:
        return (void*)get((CommandDef*)(e->param()));
    case EventGetMenuDef:
        return (void*)getDef((unsigned)(e->param()));
    case EventProcessMenu:
        mp = (ProcessMenuParam*)(e->param());
        return (void*)processMenu(mp->id, mp->param, mp->key);
    case EventMenuCustomize:
        customizeMenu((unsigned)(e->param()));
        break;
    default:
        break;
    }
    return NULL;
}
Esempio n. 15
0
void FileUnit::saveModel()
{
	auto map = Detect::shareDetect()->saveModel();
	ValueMap labelMap;
	auto player = Detect::shareDetect()->getPlayer();
	std::string info = StringUtils::format("%s %d %d %d %d %d",player->getNickName().c_str(),player->getHp(),player->getStr(),player->getDef(),player->getGold(),player->getXp());
	labelMap["info"] = info;
	std::string date = getTimeStr();
	labelMap["date"] = date;
	map["label"] = labelMap;
	map["exist"] = true;
	FileUtils::getInstance()->writeToFile(map,_path);
}
Esempio n. 16
0
std::string Pickup::use()
{
	getDef()->useEffect();
	return "used " + getDef()->getName();
}
Esempio n. 17
0
ModelEntityLogic::DrawPriority ModelEntityLogic::getDrawPriority() const {
	if (useCustomDrawPriority)
		return customDrawPriority;
	
	return getDef().getDrawPriority();
}
Esempio n. 18
0
TypePoint getSpecifier(TreeNode *head){
	TreeNode *child = head->firstChild;
	if(child->name == TYPE){
		TypePoint type = (TypePoint)malloc(sizeof(Type));
		type->kind = BASIC;
		if(strcmp(child->data,"INT")==0)
			type->data.basic = INT;
		else
			type->data.basic = FLOAT;
		return type;
	}
	else{
		//Specifier -> StructSpecifier
		child=child->firstChild;
		TreeNode *temp= child;
		TreeNode *brother = child->nextSibling;
		if(brother->name == OptTag || brother->name == Empty){
			isInsert++;
			char *name = NULL; 
			int lineno = 0;
			if(brother->name == OptTag){
				name = brother->firstChild->data;
				lineno = brother->firstChild->lineno;
			}
			brother=brother->nextSibling->nextSibling;//brother->name = DefList;
			FieldListPoint field = NULL;
			for(;;){
				if(brother->name == Empty)
					break;
				child = brother->firstChild;
				FieldListPoint temp = getDef(child);
				if(field == NULL)
					field = temp;
				else{
					FieldListPoint fieldhead = field,tail = field;
					for(;fieldhead!=NULL;)
						tail=fieldhead,fieldhead=fieldhead->tail;
					tail->tail = temp;
				}
				brother = child->nextSibling;
			}
			FieldListPoint Head = field;
			for(;Head!=NULL;Head = Head->tail){
				FieldListPoint p=Head;
				if(p==NULL)
					break;
				for(p=p->tail;p!=NULL;p=p->tail){
					if(strcmp(p->name,Head->name)==0){
						printf("Error type 15 at Line %d: Redefined field \"%s\".\n",p->lineno,p->name);
					}
				}
			}
			TypePoint type = (TypePoint)malloc(sizeof(Type));
			type->kind = STRUCTURE;
			type->data.structure = (FieldListPoint)malloc(sizeof(FieldList));
			type->data.structure->type = (TypePoint)malloc(sizeof(Type));
			type->data.structure->type->kind = STRUCTURE;
			type->data.structure->type->data.structure = field;
			type->data.structure->name = name;
			type->data.structure->tail = NULL;
			type->data.structure->lineno = lineno;
			if(name != NULL && isInsert == 2){//when the isInsert value equals 2,the type is a structure and should be inserted into the symbol talbe.
				TableNode *table = insertTableNode(name,type);
				if(table == NULL)
					printf("Error type 16 at Line %d: Duplicated name \"%s\".\n",type->data.structure->lineno,name);
			}
			isInsert--;
			return type;
		}
		else{
			brother = brother->firstChild;
			char *name = brother->data;
			TableNode *find = findTableNode(name);
			if(find == NULL){
				printf("Error type 17 at Line %d: Undefined structure \"%s\".\n",brother->lineno,name);
				return NULL;
			}
			else if(find->type->kind != STRUCTURE){
				printf("Error type 17 at Line %d: \"%s\" is a variable, isn't a structure.\n",brother->lineno,name);
				return NULL;
			}
			else if(strcmp(find->type->data.structure->name,name)!=0){
				printf("Error type 17 at Line %d: \"%s\"  is a struct variable, isn't a structure.\n",brother->lineno,name);
				return NULL;
			}
			else{
				return find->type;
			}
		}
		return NULL;
	}
}
Esempio n. 19
0
//
//START VMD
//
void VMD::dump(Region * rg, UseDefMgr * mgr)
{
    if (g_tfile == NULL) { return; }
    ASSERT0(is_md() && rg);
    fprintf(g_tfile, "(MD%dV%d", mdid(), version());

    //Dump Def
    if (getDef() != NULL) {
        ASSERT0(!getDef()->is_phi());

        if (getDef()->getPrev() != NULL) {
            fprintf(g_tfile, ",PrevDEF:MD%dV%d",
                getDef()->getPrev()->getResult()->mdid(),
                getDef()->getPrev()->getResult()->version());
        } else {
            fprintf(g_tfile, ",-");
        }

        if (getDef()->getNextSet() != NULL) {
            SEGIter * nit = NULL;
            bool first = true;
            for (INT w = getDef()->getNextSet()->get_first(&nit);
                w >= 0; w = getDef()->getNextSet()->get_next(w, &nit)) {
                if (first) {
                    first = false;
                } else {
                    fprintf(g_tfile, ",");
                }

                MDDef const* use = mgr->getMDDef(w);
                ASSERT(use, ("not such MDDef"));
                ASSERT0(use->getResult());
                ASSERT(use->getPrev() == getDef(), ("insanity relation"));
                fprintf(g_tfile, ",NextDEF:MD%dV%d",
                    use->getResult()->mdid(), use->getResult()->version());
                }
        }
    } else {
        fprintf(g_tfile, ",-");
    }
    fprintf(g_tfile, ")");

    //Dump OccSet
    fprintf(g_tfile, "|UsedBy:");
    SEGIter * vit = NULL;
    bool first = true;
    for (INT i2 = getOccSet()->get_first(&vit);
        i2 >= 0; i2 = getOccSet()->get_next(i2, &vit)) {
        if (first) {
            first = false;
        } else {
            fprintf(g_tfile, ",");
        }

        IR * use = rg->getIR(i2);
        ASSERT0(use && (use->isMemoryRef() || use->is_id()));
        fprintf(g_tfile, "%s(id:%d)", IRNAME(use), use->id());
    }

    fflush(g_tfile);
}
Esempio n. 20
0
void LatexTables::removeColumn(QDocument *doc,const int lineNumber,const int column,QStringList *cutBuffer){
	QDocumentCursor cur(doc);
	//preparations for search
	QStringList nTokens;
	nTokens << "\\\\" << "\\&" << "&";
	
	cur.moveTo(lineNumber,0);
	QString def=getDef(cur);
	//int result=findNextToken(cur,QStringList(),false,true); // move to \begin{...}
	if(def.isEmpty()) {
		return; // begin not found
	}
	cur.beginEditBlock();
	//remove col in definition
	QStringList defs=splitColDef(def);
	def.clear();
	for(int i=0;i<defs.count();i++){
		if(i==column){
			if(cutBuffer)
				cutBuffer->append(defs[i]);
		}else{
			def.append(defs[i]);
		}
	}
	if(def.isEmpty()){
		cur.removeSelectedText();
	}else{
		cur.insertText(def);
	}
	cur.movePosition(2,QDocumentCursor::Right);
	// remove column
	QString line;
	bool breakLoop=false;
	while(!breakLoop){
		int result=2;
		int off=0;
		for(int col=0;col<column;col++){
			if(off>0) off--;
			cur.clearSelection();
			QDocumentCursor oldCur(cur);
			do{
				result=findNextToken(cur,nTokens,true);
			}while(result==1);
			QString selText=cur.selectedText();
			if(selText.startsWith("\\multicolumn")){
				int add=getNumOfColsInMultiColumn(selText);
				if(off==0) off=add;
				if(off>1) cur=oldCur;
			}
			breakLoop=(result<0); // end of tabular reached (eof or \end)
			if(result<1) break; //end of tabular line reached
		}
		cur.clearSelection();
		if(result==-1) break;
		// add element
		if(result>0 || off){
			do{
				result=findNextToken(cur,nTokens,true);
			}while(result==1);
			QString selText=cur.selectedText();
			int add=0;
			if(selText.startsWith("\\multicolumn")){
				add=getNumOfColsInMultiColumn(selText);
			}
			if(add>1) {
				//multicolumn handling
				QStringList values;
				LatexParser::resolveCommandOptions(selText,0,values);
				values.takeFirst();
				values.prepend(QString("{%1}").arg(add-1));
				cur.movePosition(1,QDocumentCursor::Left,QDocumentCursor::KeepAnchor);
				if(result==0) cur.movePosition(1,QDocumentCursor::Left,QDocumentCursor::KeepAnchor);
				cur.insertText("\\multicolumn"+values.join(""));
			}else{
				//normal handling
				if(result==2 && column>0) {
					cur.movePosition(1,QDocumentCursor::Left,QDocumentCursor::KeepAnchor);
				}
				if(result==0) {
					cur.movePosition(2,QDocumentCursor::Left,QDocumentCursor::KeepAnchor);
				}
				QString zw=cur.selectedText();
				if(cutBuffer){
					if(column==0 && result!=0) zw.chop(1);
					cutBuffer->append(zw);
				}
				// detect elements which need to be kept like \hline
				QString keep;
				if(column==0){
					QStringList elementsToKeep;
					elementsToKeep << "\\hline" << "\\endhead" << "\\endfoot" << "\\endfirsthead" << "\\endlastfoot";
					for(int i=0;i<zw.length();i++){
						if(zw.at(i)=='\n') {
							if(!keep.endsWith('\n'))
								keep += "\n";
						}
						//commands
						if(zw.at(i)=='\\') {
							QRegExp rx("\\w+");
							rx.indexIn(zw,i+1);
							QString cmd="\\"+rx.cap();
							if(elementsToKeep.contains(cmd)){
								keep += " " + cmd;
							}
						}
					}
					if(keep.length()==1) keep.clear();;
				}
				cur.removeSelectedText();
				if(column>0) {
					cur.movePosition(1,QDocumentCursor::Left,QDocumentCursor::KeepAnchor);
					cur.removeSelectedText();
				}
				cur.insertText(keep);
			}
			const QStringList tokens("\\\\");
			breakLoop=(findNextToken(cur,tokens)==-1);
		}
		if(cur.atLineEnd()) cur.movePosition(1,QDocumentCursor::Right);
		line=cur.line().text();
		if(line.contains("\\end{")) breakLoop=true;
	}
	cur.endEditBlock();
}
Esempio n. 21
0
void Instruction::print() const
{
   #define BUFSZ 512

   const size_t size = BUFSZ;

   char buf[BUFSZ];
   int s, d;
   size_t pos = 0;

   PRINT("%s", colour[TXT_INSN]);

   if (join)
      PRINT("join ");

   if (predSrc >= 0) {
      const size_t pre = pos;
      if (getSrc(predSrc)->reg.file == FILE_PREDICATE) {
         if (cc == CC_NOT_P)
            PRINT("not");
      } else {
         PRINT("%s", CondCodeStr[cc]);
      }
      if (pos > pre)
         SPACE();
      pos += getSrc(predSrc)->print(&buf[pos], BUFSZ - pos);
      PRINT(" %s", colour[TXT_INSN]);
   }

   if (saturate)
      PRINT("sat ");

   if (asFlow()) {
      PRINT("%s", operationStr[op]);
      if (asFlow()->indirect)
         PRINT(" ind");
      if (asFlow()->absolute)
         PRINT(" abs");
      if (op == OP_CALL && asFlow()->builtin) {
         PRINT(" %sBUILTIN:%i", colour[TXT_BRA], asFlow()->target.builtin);
      } else
      if (op == OP_CALL && asFlow()->target.fn) {
         PRINT(" %s%s:%i", colour[TXT_BRA],
               asFlow()->target.fn->getName(),
               asFlow()->target.fn->getLabel());
      } else
      if (asFlow()->target.bb)
         PRINT(" %sBB:%i", colour[TXT_BRA], asFlow()->target.bb->getId());
   } else {
      PRINT("%s ", operationStr[op]);
      if (op == OP_LINTERP || op == OP_PINTERP)
         PRINT("%s ", interpStr[ipa]);
      switch (op) {
      case OP_SUREDP:
      case OP_ATOM:
         if (subOp < ARRAY_SIZE(atomSubOpStr))
            PRINT("%s ", atomSubOpStr[subOp]);
         break;
      case OP_LOAD:
      case OP_STORE:
         if (subOp < ARRAY_SIZE(ldstSubOpStr))
            PRINT("%s ", ldstSubOpStr[subOp]);
         break;
      case OP_SUBFM:
         if (subOp < ARRAY_SIZE(subfmOpStr))
            PRINT("%s ", subfmOpStr[subOp]);
         break;
      case OP_SHFL:
         if (subOp < ARRAY_SIZE(shflOpStr))
            PRINT("%s ", shflOpStr[subOp]);
         break;
      case OP_PIXLD:
         if (subOp < ARRAY_SIZE(pixldOpStr))
            PRINT("%s ", pixldOpStr[subOp]);
         break;
      case OP_RCP:
      case OP_RSQ:
         if (subOp < ARRAY_SIZE(rcprsqOpStr))
            PRINT("%s ", rcprsqOpStr[subOp]);
         break;
      case OP_EMIT:
         if (subOp < ARRAY_SIZE(emitOpStr))
            PRINT("%s ", emitOpStr[subOp]);
         break;
      default:
         if (subOp)
            PRINT("(SUBOP:%u) ", subOp);
         break;
      }
      if (perPatch)
         PRINT("patch ");
      if (asTex())
         PRINT("%s %s$r%u $s%u %s", asTex()->tex.target.getName(),
               colour[TXT_MEM], asTex()->tex.r, asTex()->tex.s,
               colour[TXT_INSN]);
      if (postFactor)
         PRINT("x2^%i ", postFactor);
      PRINT("%s%s", dnz ? "dnz " : (ftz ? "ftz " : ""),  DataTypeStr[dType]);
   }

   if (rnd != ROUND_N)
      PRINT(" %s", RoundModeStr[rnd]);

   if (defExists(1))
      PRINT(" {");
   for (d = 0; defExists(d); ++d) {
      SPACE();
      pos += getDef(d)->print(&buf[pos], size - pos);
   }
   if (d > 1)
      PRINT(" %s}", colour[TXT_INSN]);
   else
   if (!d && !asFlow())
      PRINT(" %s#", colour[TXT_INSN]);

   if (asCmp())
      PRINT(" %s%s", colour[TXT_INSN], CondCodeStr[asCmp()->setCond]);

   if (sType != dType)
      PRINT(" %s%s", colour[TXT_INSN], DataTypeStr[sType]);

   for (s = 0; srcExists(s); ++s) {
      if (s == predSrc || src(s).usedAsPtr)
         continue;
      const size_t pre = pos;
      SPACE();
      pos += src(s).mod.print(&buf[pos], BUFSZ - pos);
      if (pos > pre + 1)
         SPACE();
      if (src(s).isIndirect(0) || src(s).isIndirect(1))
         pos += getSrc(s)->asSym()->print(&buf[pos], BUFSZ - pos,
                                          getIndirect(s, 0),
                                          getIndirect(s, 1));
      else
         pos += getSrc(s)->print(&buf[pos], BUFSZ - pos, sType);
   }
   if (exit)
      PRINT("%s exit", colour[TXT_INSN]);

   PRINT("%s", colour[TXT_DEFAULT]);

   buf[MIN2(pos, BUFSZ - 1)] = 0;

   INFO("%s (%u)\n", buf, encSize);
}
double pewarpcost(float *x, float *bX, float *bY, float *dbY, float *bZ,
        mwSignedIndex *bdims, uint8_T *target, float *source, uint8_T *mask,
        mwSignedIndex *ddims, float *skrn, int skrnl, float xscale,
        float regstrength, float *H, uint8_T *warped, float *def)
{
    int nvox = ddims[0] * ddims[1] * ddims[2];
    /* float *def = mxMalloc(sizeof(float) * nvox); */
    float *jac = mxMalloc(sizeof(float) * nvox);
    /* uint8_T *warped = mxMalloc(sizeof(uint8_T) * nvox); */
    /* float *H = mxMalloc(sizeof(float) * 256 * 256); */
    float *Htmp = mxMalloc(sizeof(float) * 256 * 256);

    double *s1 = mxMalloc(sizeof(double) * 256);
    double *s2 = mxMalloc(sizeof(double) * 256);
    double s, sL, s1L, s2L;
    
    double cost;
    
    /* mexPrintf(">>> Start -> %lu (CLOCKS_PER_SEC: %lu)\n", clock(), CLOCKS_PER_SEC); */
            
    getDef(def, ddims, bdims[0], bX, bdims[1], bY, bdims[2], bZ, x, xscale);
    /* The actual Jacobian is 1 + jac, but it is easier to add 1 later. */
    getDef(jac, ddims, bdims[0], bX, bdims[1], dbY, bdims[2], bZ, x, xscale);
    
    /* mexPrintf("getDef done -> %lu\n", clock()); */
    

    /* For some reason, execution is single-threaded without the num_threads clause.
     * TODO: Find out why and change. */
    #pragma omp parallel num_threads(4) shared(s, sL, s1L, s2L)
    {
        peResampleAndApplyJacobian(warped, source, def, /* jac, */ mask, ddims);
        
        /* if (omp_get_thread_num() == 1)
            mexPrintf("peResampleAndApplyJacobian done -> %lu\n", clock()); */
        
        hist2(H, target, warped, mask, nvox);
        
        /* if (omp_get_thread_num() == 1)
            mexPrintf("hist2 done -> %lu\n", clock()); */
        
        smoothRows(Htmp, H, 256, 256, skrn, skrnl);
        smoothCols(H, Htmp, 256, 256, skrn, skrnl);
        
        /* if (omp_get_thread_num() == 1)
            mexPrintf("smooth... done -> %lu\n", clock()); */
        
        #pragma omp single
        {
            s = histSumAll(H, 65536);
        }

        #pragma omp sections
        {
            #pragma omp section
            {
                sL = histLogAll(H, s, 65536);
            }

            #pragma omp section
            {
                s1L = histLogVert(H, s1, s, 256, 256);
            }

            #pragma omp section
            {
                s2L = histLogHorz(H, s2, s, 256, 256);
            }
        }
        
        /* if (omp_get_thread_num() == 1)
            mexPrintf("hist... done -> %lu\n", clock()); */
        
    }
    
    cost = - (s1L + s2L) / sL + regstrength * regularisation(jac, nvox);
    
    /* mexPrintf("regularisation done -> %lu\n", clock());
    mexPrintf("<<<\n"); */
    
    /* mexPrintf("cost: %f  sL: %f  s1L: %f  s2L: %f  #voxels: %d\n", cost, sL, s1L, s2L, nvox); */

    /* mxFree(def); */
    mxFree(jac);
    /* mxFree(warped); */
    /* mxFree(H); */
    mxFree(Htmp);
    mxFree(s1);
    mxFree(s2);

    return cost;
}
Esempio n. 23
0
void LatexTables::addColumn(QDocument *doc,const int lineNumber,const int afterColumn,QStringList *cutBuffer){
	QDocumentCursor cur(doc);
	QStringList pasteBuffer;
	QStringList nTokens;
	nTokens << "\\\\" << "\\&" << "&";
	if(cutBuffer) pasteBuffer=*cutBuffer;
	cur.beginEditBlock();
	cur.moveTo(lineNumber,0);
	QString def=getDef(cur);
	//int result=findNextToken(cur,QStringList(),false,true); // move to \begin{...}
	if(def.isEmpty()) {
		cur.endEditBlock();
		return; // begin not found
	}
	//add col in definition
	QStringList defs=splitColDef(def);
	QString addCol="l";
	if(cutBuffer){
		addCol=pasteBuffer.takeFirst();
	}
	def.clear();
	if(afterColumn==0)
		def=addCol;
	for(int i=0;i<defs.count();i++){
		def.append(defs[i]);
		if(i+1==afterColumn || (i+1==defs.count()&&i+1<afterColumn))
			def.append(addCol);
	}
	cur.insertText(def);
	//continue adding col
	cur.movePosition(2,QDocumentCursor::Right);
	QString line;
	bool breakLoop=false;
	int result=2;
	while(!breakLoop){
		for(int col=0;col<afterColumn;col++){
			do{
				result=findNextToken(cur,nTokens);
			}while(result==1);
			breakLoop=(result<0); // end of tabular reached (eof or \end)
			if(result<1) break; //end of tabular line reached
		}
		if(result==-1) break;
		//if last line before end, check whether the user was too lazy to put in a linebreak
		if(result==-2){
			QDocumentCursor ch(cur);
			QStringList tokens("\\\\");
			int res=findNextToken(ch,tokens,true,true);
			if(res==0){
				ch.movePosition(2,QDocumentCursor::Right,QDocumentCursor::KeepAnchor);
				if(ch.selectedText().contains(QRegExp("^\\S+$")))
					break;
			}
		}
		// add element
		if(result==2){
			if(pasteBuffer.isEmpty()) {
				cur.insertText(" &");
			}else{
				if(afterColumn==0){
					QDocumentCursor ch(cur);
					int res=findNextToken(ch,nTokens);
					cur.insertText(pasteBuffer.takeFirst());
					if(res!=0){
						cur.insertText("&");
					}
				}else{
					cur.insertText(pasteBuffer.takeFirst()+"&");
				}
				
			}
		}
		if(result<=0){
			int count= result==0 ? 2 : 1;
			cur.movePosition(count,QDocumentCursor::Left);
			if(pasteBuffer.isEmpty()) {
				cur.insertText("& ");
			}else{
				cur.insertText("&"+pasteBuffer.takeFirst());
			}
		}
		const QStringList tokens("\\\\");
		breakLoop=(findNextToken(cur,tokens)==-1);
		// go over \hline if present
		QString text=cur.line().text();
		int col=cur.columnNumber();
		text=text.mid(col);
		QRegExp rxHL("^(\\s*\\\\hline\\s*)");
		int pos_hline=rxHL.indexIn(text);
		if(pos_hline>-1){
			int l=rxHL.cap().length();
			cur.movePosition(l,QDocumentCursor::Right);
		}
		if(cur.atLineEnd()) cur.movePosition(1,QDocumentCursor::Right);
		line=cur.line().text();
		if(line.contains("\\end{")) breakLoop=true;
	}
	cur.endEditBlock();
}