void CScanLineZBufferView::CalcModelInfo()
{
	// 计算模型的中心坐标
	m_centerPoint.x = m_centerPoint.y = m_centerPoint.z = 0;
	CScanLineZBufferDoc *pDoc = GetDocument();
	Point min_xyz, max_xyz;
	auto first_point = (pDoc->m_mesh).point((pDoc->m_mesh).vertices_begin().handle());
	min_xyz.x = max_xyz.x = first_point.data()[0];
	min_xyz.y = max_xyz.y = first_point.data()[1];
	min_xyz.z = max_xyz.z = first_point.data()[2];
	for (auto vertex_it = (pDoc->m_mesh).vertices_begin(); vertex_it != (pDoc->m_mesh).vertices_end(); ++vertex_it)
	{
		auto point = (pDoc->m_mesh).point(vertex_it.handle());
		auto x = point.data()[0], y = point.data()[1], z = point.data()[2];
		m_centerPoint.x += x;
		m_centerPoint.y += y;
		m_centerPoint.z += z;
		min_xyz.x = mmin(min_xyz.x, x);
		min_xyz.y = mmin(min_xyz.y, y);
		min_xyz.z = mmin(min_xyz.z, z);
		max_xyz.x = mmax(max_xyz.x, x);
		max_xyz.y = mmax(max_xyz.y, y);
		max_xyz.z = mmax(max_xyz.z, z);
	}
	int n_verteice = (pDoc->m_mesh).n_vertices();
	m_centerPoint.x /= n_verteice;
	m_centerPoint.y /= n_verteice;
	m_centerPoint.z /= n_verteice;
	double vec[] = { max_xyz.x - min_xyz.x, max_xyz.y - min_xyz.y, max_xyz.z - min_xyz.z }; 
	// 计算模型的尺寸
	m_modelScale = sqrt(vec[0] * vec[0] + vec[1] * vec[1] + vec[2] * vec[2]);
}
Exemple #2
0
void Quant(int *coeff, int *qcoeff, int QP, int Mode)
{
  int i;
  int level;
  
  if (QP) {
    if (Mode == MODE_INTRA || Mode == MODE_INTRA_Q) { /* Intra */
      qcoeff[0] = mmax(1,mmin(254,coeff[0]/8));

      for (i = 1; i < 64; i++) {
        level = (abs(coeff[i])) / (2*QP);
        qcoeff[i] =  mmin(127,mmax(-127,sign(coeff[i]) * level));
      }
    }
    else { /* non Intra */
      for (i = 0; i < 64; i++) {
        level = (abs(coeff[i])-QP/2)  / (2*QP);
        qcoeff[i] = mmin(127,mmax(-127,sign(coeff[i]) * level));
      }
    }
  }
  else {
    /* No quantizing.
       Used only for testing. Bitstream will not be decodable 
       whether clipping is performed or not */
    for (i = 0; i < 64; i++) {
      qcoeff[i] = coeff[i];
    }
  }
  return;
}
Exemple #3
0
void HorizEdgeFilter (unsigned char *rec, int width, int height, Pict * pic, int chr)
{
  int i, j;
  int delta, d1, d2;
  int mbc, mbr, do_filter;
  int QP;
  int bquant[] = {5, 6, 7, 8};
  int mbr_above;

  /* horizontal edges */
  for (j = 8; j < height; j += 8)
  {
    for (i = 0; i < width; i++)
    {
      if (!chr)
      {
        mbr = j >> 4;
        mbc = i >> 4;
        mbr_above = (j - 8) >> 4;
      } else
      {
        mbr = j >> 3;
        mbc = i >> 3;
        mbr_above = mbr - 1;
      }

      do_filter = coded_map[mbr + 1][mbc + 1] || coded_map[mbr_above + 1][mbc + 1];

      if (do_filter)
      {
        if (pic->PB)
        {
          QP = coded_map[mbr + 1][mbc + 1] ?
            mmin (31, bquant[pic->BQUANT] * quant_map[mbr + 1][mbc + 1] / 4) :
            mmin (31, bquant[pic->BQUANT] * quant_map[mbr_above + 1][mbc + 1] / 4);
        } else
          QP = coded_map[mbr + 1][mbc + 1] ? quant_map[mbr + 1][mbc + 1] : quant_map[mbr_above + 1][mbc + 1];

        if (modified_quantization && chr) 
        {
          QP=MQ_chroma_QP_table[QP];                   
        }
        delta = (int) (((int) (*(rec + i + (j - 2) * width)) +
                        (int) (*(rec + i + (j - 1) * width) * (-4)) +
                        (int) (*(rec + i + (j) * width) * (4)) +
                     (int) (*(rec + i + (j + 1) * width) * (-1))) / 8.0);

        d1 = sign (delta) * mmax (0, abs (delta) - mmax (0, 2 * (abs (delta) - STRENGTH[QP - 1])));

        d2 = mmin (abs (d1 / 2), mmax (-abs (d1 / 2), (int) (((*(rec + i + (j - 2) * width) -
                                   *(rec + i + (j + 1) * width))) / 4)));

        *(rec + i + (j + 1) * width) = (int) (*(rec + i + (j + 1) * width)) + d2;
        *(rec + i + (j) * width) =
          mmin (255, mmax (0, (int) (*(rec + i + (j) * width)) - d1));
        *(rec + i + (j - 1) * width) =
          mmin (255, mmax (0, (int) (*(rec + i + (j - 1) * width)) + d1));
        *(rec + i + (j - 2) * width) = (int) (*(rec + i + (j - 2) * width)) - d2;
      }
    }
Exemple #4
0
/* Answer the address of minHeapSize rounded up to page size bytes of memory. */
usqInt
sqAllocateMemory(usqInt minHeapSize, usqInt desiredHeapSize)
{
    char *hint, *address, *alloc;
    unsigned long alignment, allocBytes;
    
    if (pageSize) {
        fprintf(stderr, "sqAllocateMemory: already called\n");
        exit(1);
    }
    pageSize = getpagesize();
    pageMask = ~(pageSize - 1);
    
    hint = sbrk(0);
    
    alignment = mmax(pageSize,1024*1024);
    address = (char *)(((usqInt)hint + alignment - 1) & ~(alignment - 1));
    
    alloc = sqAllocateMemorySegmentOfSizeAboveAllocatedSizeInto
    (roundUpToPage(desiredHeapSize), address, &allocBytes);
    if (!alloc) {
        fprintf(stderr, "sqAllocateMemory: initial alloc failed!\n");
        exit(errno);
    }
    return (usqInt)alloc;
}
Exemple #5
0
int main() {
       int N, M;
       int L, R;
       int i, k;
       scanf("%d %d", &N, &M);
       for(i=0; i<N; i++) {
              scanf("%d", profit+i);
       }

       // 约定Pk为以k为结尾的最长perfect串
       // 当前perfect串中出现的数,在app[]中对应位置为true
       perfect[0] = 1;
       repeat[0] = 0;
       Appear(profit[0]) = true;

       for(k=1; k<N; k++) {
              // 如果第k个数在Pk-1中未出现,将第k个数加入Pk-1仍然是个perfect串,那么|Pk| = |Pk-1|+1
              if( !Appear(profit[k]) ) {
                     Appear(profit[k]) = true;
                     perfect[k] = perfect[k-1]+1;
                     repeat[k] = repeat[k-1];       // repeat值和Pk-1相同
              }
              // 否则,从Pk-1开头开始找,一直找到和第k个数相同的那个数,截掉前面的那一段
              else {
                     i = k-perfect[k-1];
                     while( profit[i] != profit[k] ) {
                            Appear(profit[i]) = false;
                            i ++;
                     }
                     perfect[k] = k-i;                     // 新的串长度
                     repeat[k] = k;                            // repeat值为自己
              }
       }

       int ret;
       for(k=0; k<M; k++) {
              ret = 0;
              scanf("%d %d", &L, &R);
              while( 1 ) {
                     // 结果大于当前范围,可提前退出
                     if( R-L+1 <= ret ) {
                            break;
                     }
                     ret = mmax(ret, mmin(perfect[R], R-L+1));

                     // |P(repeat[R])| < |P(repeat[R]+1)| < ... < |P(R)|, 所以直接跳到P(repeat[R]-1)处
                     R = repeat[R]-1;
              }
              printf("%d\n", ret);
       }

       return 1;
}
double SDFFelementManager::extract_end_time(){
  std::map<std::string, std::vector<SDFFsequenceElement*> >::const_iterator i;
  double et=0;
  // go through all elements and always store the maximum end_time ...
  for (i=elements.begin(); i!=elements.end(); ++i) {
    if (i->second.size()>0) {
      for (size_t j=0; j<i->second.size(); j++) {
        double eet=i->second[j]->extract_real_t_end();
        et=mmax(et, eet);
      }
    }
  }
  return et;//+sample_timestep*2.0;
};
Exemple #7
0
void datatable2::resize(unsigned long newx, unsigned long newy){
    if (newy<=line_size) {
      line_count=newy;
    } else {
      if (column_size>0) for (unsigned long x=0; x<column_size; x++) {
          register void *value = realloc(data[x], (unsigned long)(newy*resize_factor)*sizeof(datatable2_value));
          if (value == NULL)
            DATATABLE2_ERROR(DATATABLE2_ERROR_VMEM_NUM, DATATABLE2_ERROR_VMEM_MESSAGE, "datatable2.resize("+inttostr(newx)+", "+inttostr(newy)+")");
          data[x]=(datatable2_value*)value;
          for (unsigned long y=line_count; y<(unsigned long)(newy*resize_factor); y++) {
            data[x][y].value=0;
            data[x][y].empty=true;
          }
      }
      line_size=(unsigned long)(newy*resize_factor);
      line_count=newy;
    }


    if (newx<=column_size) {
      column_count=newx;
    } else {
      if (column_size==0) {
          register void *value = malloc((unsigned long)(mmax(newx,1)*resize_factor)*sizeof(datatable2_value*)); // get a bit more (+20%) of memory for lines
          if (value == NULL)
            DATATABLE2_ERROR(DATATABLE2_ERROR_VMEM_NUM, DATATABLE2_ERROR_VMEM_MESSAGE, "datatable2.resize("+inttostr(newx)+", "+inttostr(newy)+")");
          data=(datatable2_value**)value;
      } else {
          register void *value = realloc(data, (unsigned long)(newx*resize_factor)*sizeof(datatable2_value*)); // get a bit more (+20%) of memory for lines
          if (value == NULL)
            DATATABLE2_ERROR(DATATABLE2_ERROR_VMEM_NUM, DATATABLE2_ERROR_VMEM_MESSAGE, "datatable2.resize("+inttostr(newx)+", "+inttostr(newy)+")");
          data=(datatable2_value**)value;
      }
      for (unsigned long i=column_size; i<(unsigned long)(newx*resize_factor); i++) {
          register void *value = malloc(line_size*sizeof(datatable2_value));
          if (value == NULL)
            DATATABLE2_ERROR(DATATABLE2_ERROR_VMEM_NUM, DATATABLE2_ERROR_VMEM_MESSAGE, "datatable2.resize("+inttostr(newx)+", "+inttostr(newy)+")");
          data[i]=(datatable2_value*)value;
          for (unsigned long y=0; y<line_size; y++) {
            data[i][y].value=0;
            data[i][y].empty=true;
          }
      }
      column_count=newx;
      column_size=(unsigned long)(newx*resize_factor);
    }
    resize_titles();
}
Exemple #8
0
void InterPolynomial::updateM(Vector newPoint, double valueF)
{
    //not tested
    unsigned i=nPtsUsed;
    double sum=0,a;
    Polynomial *pp=NewtonBasis;
    Vector *xx=NewtonPoints;

    while (i--)
    {
        a=newPoint.euclidianDistance(xx[i]);
        sum+=condorAbs(pp[i]( newPoint ))*a*a*a;
    }
    M=mmax(M, condorAbs((*this)(newPoint)-valueF)/sum);
    nUpdateOfM++;
}
Exemple #9
0
	void UnitList::recreateLists(const VC2 &size)
	{
		VC2	mmin(-size.x, -size.y);
		VC2 mmax( size.x,  size.y);

		LinkedListIterator iter(allUnits);
		while (iter.iterateAvailable())
		{
			Unit *u = (Unit *)iter.iterateNext();
			if (u->getUnitListEntity() != NULL)
			{
				delete u->getUnitListEntity();
				u->setUnitListEntity(NULL);
			}
		}

		impl->tree.reset(new UnitQTree(mmin, mmax));

		iter = LinkedListIterator(allUnits);
		while (iter.iterateAvailable())
		{
			Unit *u = (Unit *)iter.iterateNext();
			//assert(u->getUnitListEntity() != NULL);
			//delete u->getUnitListEntity();

			float radius = UNIT_QTREE_RADIUS_HACK;
			// grow the radius for non-boned units only
			// (as boned units may have 15m radius or such because of changing animations)
			if (u->getUnitType()->getBonesFilename() == NULL)
			{
				if (u->getVisualObject() != NULL
					&& u->getVisualObject()->getStormModel() != NULL)
				{
					float radius2 = u->getVisualObject()->getStormModel()->GetRadius();
					if (radius2 > radius) radius = radius2;
				}
			}
			u->setUnitListEntity(new UnitListEntity());
			u->getUnitListEntity()->entity = impl->tree->insert(u, u->getPosition(), radius);
			u->getUnitListEntity()->lastUpdatePosition = u->getPosition();
		}

	}
Exemple #10
0
int InterPolynomial::findAGoodPointToReplace(int excludeFromT, 
                                  double rho, Vector pointToAdd, double *maxd)
{
    //not tested

    // excludeFromT is set to k if not success from optim and we want
    //        to be sure that we keep the best point
    // excludeFromT is set to -1 if we can replace the point x_k by
    //        pointToAdd(=x_k+d) because of the success of optim.
    
    // chosen t: the index of the point inside the newtonPoints
    //            which will be replaced.

    Vector *xx=NewtonPoints;
    Vector XkHat;
    if (excludeFromT>=0) XkHat=xx[excludeFromT];
    else XkHat=pointToAdd;

    int t=-1, i, N=nPtsUsed;
    double a, aa, maxa=-1.0, maxdd=0;
    Polynomial *pp=NewtonBasis;

  //  if (excludeFromT>=0) maxa=1.0;

    for (i=0; i<N; i++)
    {
        if (i==excludeFromT) continue;
        aa=XkHat.euclidianDistance(xx[i]);
        if (aa==0.0) return -1;
        a=aa/rho;
        // because of the next line, rho is important:
        a=mmax(a*a*a,1.0);
        a*=condorAbs(pp[i] (pointToAdd));

        if (a>maxa)
        {
            t=i; maxa=a; maxdd=aa;
        }
    }
    if (maxd) *maxd=maxdd;
    return t;
}
Exemple #11
0
/* For q=8, a "speedy" version is integrated */
int QuantAndFindCBP(int *coeff, int *qcoeff, int QP, int Mode, int CBP_Mask)
{
  int i;
  int level;
  int tempje;
  int CBP = 0;

  if (Mode == MODE_INTRA) { /* Intra */
    qcoeff[0] = mmax(1,mmin(254,coeff[0] >> 3)); /* was: /8 */

    if(QP == 8) {

      for(i = 1; i < 64; i++) {
	level = (abs(coeff[i])) >> 4;
	qcoeff[i] = mmin(127, mmax(-127,sign(coeff[i]) * level));
	if(qcoeff[i])
	  CBP = CBP_Mask;
      }
    } else {			/* QP != 8 */
      for(i = 1; i < 64; i++) {
Exemple #12
0
/*
fills the virtual memory with anonymous PROT_NONE mmaps,
returns the mappings in *p and *n in decreasing size order,
the return value is the number of mappings or -1 on failure.
*/
int t_vmfill(void **p, size_t *n, int len)
{
	int fd = open("/dev/zero", O_RDWR);
	size_t start = SIZE_MAX/2 + 1;
	size_t m;
	void *q;
	int i;

	for (i=0;;i++) {
		m = mmax(fd, &start);
		if (!m)
			break;
		q = mmap(0, m, PROT_NONE, MAP_PRIVATE, fd, 0);
		if (q == MAP_FAILED)
			return -1;
		if (i < len) {
			p[i] = q;
			n[i] = m;
		}
	}
	return i;
}
Exemple #13
0
int
main(){
  double out[8][8];
  double out2[8][8];
  double out3[8][8];
  double in[8][8];
  double in2[8][8];

  
  for(int y=0;y<N;y++)
    for(int x=0;x<N;x++){
      mzero(in);
      in[y][x]=1;
      idct(in,out);
  
      for(int iy=0;iy<N;iy++)
	for(int ix=0;ix<N;ix++){
	  if(out[iy][ix]>=0)
	    in2[iy][ix]=255;
	  else
	    in2[iy][ix]=0;
	}

      dct(in2,out2);

      if(x==0&&y==0)
	out3[y][x]=out2[0][0];
      else
	out3[y][x]=mmax(out2);
    }

  // mmap(out3,(1.0/4)*);
  mmap(out3,round);
  mprint(out3);
  

  return true;
}
Exemple #14
0
void DDI_ARR_select_local(DDI_Patch *dAPatch, DDI_ARR_Element *element) {
  DDA_Index *Index = gv(dda_index);
  int dA = dAPatch->handle;
  double *dALocal;
  int op = dAPatch->oper;

  int dALdaLocal, dAiLocal, dAjLocal, dAmLocal, dAnLocal;

  /* A segment dimensions */
  dALdaLocal = Index[dA].ihi - Index[dA].ilo + 1;
  dAiLocal = dAPatch->ilo - Index[dA].ilo;
  dAjLocal = dAPatch->jlo - Index[dA].jlo;
  dAmLocal = dAPatch->ihi - dAPatch->ilo + 1;
  dAnLocal = dAPatch->jhi - dAPatch->jlo + 1;

# if defined USE_SYSV
  if(USING_DATA_SERVERS()) DDI_Fence_check(dA);
# endif
  
  DDI_Acquire(Index, dA, DDI_READ_ACCESS, (void**)&dALocal);
  
  switch(op) {
  case DDI_ARR_MIN:
    mmin(dALocal, dALdaLocal, dAiLocal, dAjLocal, dAmLocal, dAnLocal, &(element->alpha), element->index);
    break;
    
  case DDI_ARR_MAX:
    mmax(dALocal, dALdaLocal, dAiLocal, dAjLocal, dAmLocal, dAnLocal, &(element->alpha), element->index);
    break;
  } /* switch */
  
  /* adjust element indices to global values */
  element->index[0] += Index[dA].ilo;
  element->index[1] += Index[dA].jlo;
  
  DDI_Release(Index, dA, DDI_READ_ACCESS);
}
// 建立分类多边形边和分类边表
void ScanLineZBufferCore::BuildPolygonAndEdgeTable()
{
	int width = m_viewport[2];
	int height = m_viewport[3];
	m_polygonTable.resize(height, std::vector<PolygonTableElem>());
	m_edgeTable.resize(height, std::vector<EdgeTableElem>());
	for (auto i = 0; i < height; i++) 
	{
		m_polygonTable[i].clear();
		m_edgeTable[i].clear();
	}
	PolygonTableElem cpte;
	// 遍历每个多边形,加入到多边形表和边表
	for (auto f_it = pMesh->faces_begin(); f_it != pMesh->faces_end(); ++f_it)
	{
		//std::cout << "当前多边形 " << f_it->idx() << std::endl;
		// 遍历多边形的每条边,构造分类边表
		for (auto h_it = pMesh->fh_begin(f_it.handle()); h_it != pMesh->fh_end(f_it.handle()); ++h_it)
		{
			EdgeTableElem cete; 
			cete.id = f_it->idx();
			auto point_a_idx = (pMesh->from_vertex_handle(h_it.handle())).idx(); 
			auto point_b_idx = (pMesh->to_vertex_handle(h_it.handle())).idx();

			// 判断边上两个点谁的y值更大
			int max_idx, min_idx;
			if (m_projectionVertex[point_a_idx].y > m_projectionVertex[point_b_idx].y)
			{
				max_idx = point_a_idx;
				min_idx = point_b_idx;
			}
			else
			{
				max_idx = point_b_idx;
				min_idx = point_a_idx;
			}
			// 设置为边的上端点坐标
			cete.x = m_projectionVertex[max_idx].x;
			// 设置边跨越的扫描线数目 和 两点x方向差, 实质为 -cet.dy/cet.dx 
			cete.dy = m_projectionVertex[max_idx].y - m_projectionVertex[min_idx].y;
			// 略过水平线不处理
			if (abs(cete.dy) < 1e-8) continue;
			cete.dx = -(m_projectionVertex[min_idx].x - m_projectionVertex[max_idx].x) / (m_projectionVertex[min_idx].y - m_projectionVertex[max_idx].y);

			// 添加到分类边表
			// //std::cout << logTime() << " " << convertToInt(m_projectionVertex[max_idx].y) << std::endl;
			m_edgeTable[convertToInt(m_projectionVertex[max_idx].y)].push_back(cete);
			//std::cout << ">>>> 加入边" << h_it->idx() << std::endl;
		}

		// 求当前多边形的Y的最大最小值
		double min_y, max_y;
		// 获取多边形上的一个顶点,初始化多边形Y的最大最小值
		min_y = max_y = m_projectionVertex[(pMesh->fv_begin(f_it.handle()))->idx()].y;
		// 取出当前多边形上三个点,求平面a,b,c,d
		std::vector<Point> poly_point;
		// 求出当前多边形的Y的最大最小值
		for (auto v_it = pMesh->fv_begin(f_it.handle()); v_it != pMesh->fv_end(f_it.handle()); ++v_it)
		{
			auto point = m_projectionVertex[v_it->idx()];
			// //std::cout << logTime() << " 点坐标" << point.y << std::endl;
			poly_point.push_back(point);
			min_y = mmin(min_y, point.y);
			max_y = mmax(max_y, point.y);
		}
		// if (poly_point.size() < 3) //std::cout << logTime() << " 多边形上点的数量少于3" << std::endl;
		
		// 求ax+by+cz+d=0,设置分类多边形参数
		cpte.a = (poly_point[0].y - poly_point[1].y)*(poly_point[0].z - poly_point[2].z)
			- (poly_point[0].y - poly_point[2].y)*(poly_point[0].z - poly_point[1].z);
		cpte.b = (poly_point[0].x - poly_point[2].x)*(poly_point[0].z - poly_point[1].z)
			- (poly_point[0].z - poly_point[2].z)*(poly_point[0].x - poly_point[1].x);
		cpte.c = (poly_point[0].x - poly_point[1].x)*(poly_point[0].y - poly_point[2].y)
			- (poly_point[0].x - poly_point[2].x)*(poly_point[0].y - poly_point[1].y);
		cpte.d = -cpte.a*poly_point[0].x - cpte.b*poly_point[0].y - cpte.c*poly_point[0].z;
		//std::cout << ">>>> 平面方程参数" << cpte.a << " " << cpte.b << " " << cpte.c << " " << cpte.d << std::endl;
		// 设置多边形的id
		cpte.id = f_it->idx();
		// 设置多边形的颜色
		cpte.color.r = (rand() % 20) + 235;
		cpte.color.g = (rand() % 20) + 145;
		cpte.color.b = 0;

		// 加入到分类多边形表
		//std::cout << std::endl;
		cpte.dy = convertToInt(max_y) - convertToInt(min_y);
		m_polygonTable[convertToInt(max_y)].push_back(cpte);
	}
}
//------------------------------------------------------------------
// Storm3D_Mesh_CollisionTable::ReBuild
//------------------------------------------------------------------
void Storm3D_Mesh_CollisionTable::ReBuild(Storm3D_Mesh *mesh)
{
	// TEMP!!!
	//return;

	int memory_before = 0; //frozenbyte::debug::Debug_MemoryManager::amountMemoryInUse();

	// Set owner
	owner=mesh;

	// Allocate memory for collision table
	delete tree;
	tree = 0;

	if(!owner->vertexes || !owner->faces[0])
		return;

	face_amount=owner->face_amount[0];

	if (owner->collision_faces != -1)
		face_amount = owner->collision_faces;

	SAFE_DELETE_ARRAY(faces);
	faces = new CollisionFace[face_amount];

	VC2 mmin(10000000.f, 10000000.f);
	VC2 mmax(-10000000.f, -10000000.f);

	// Create collision table
	for(int fi = 0; fi < face_amount; ++fi)
	{
		// Set vertexes
		faces[fi].vertex0=owner->vertexes[owner->faces[0][fi].vertex_index[0]].position;
		faces[fi].vertex1=owner->vertexes[owner->faces[0][fi].vertex_index[1]].position;
		faces[fi].vertex2=owner->vertexes[owner->faces[0][fi].vertex_index[2]].position;

		// Create edges
		faces[fi].e01=owner->vertexes[owner->faces[0][fi].vertex_index[1]].position-owner->vertexes[owner->faces[0][fi].vertex_index[0]].position;
		faces[fi].e02=owner->vertexes[owner->faces[0][fi].vertex_index[2]].position-owner->vertexes[owner->faces[0][fi].vertex_index[0]].position;
		VC3 e12=owner->vertexes[owner->faces[0][fi].vertex_index[2]].position-owner->vertexes[owner->faces[0][fi].vertex_index[1]].position;

		VC3 cross_e01_e02 = faces[fi].e01.GetCrossWith(faces[fi].e02);
		if(cross_e01_e02.GetSquareLength() < 0.0001f)
		{
			CollisionFace &face = faces[fi];
			face.sphere.radius = 0;

			continue;
		}

		// Create plane
		faces[fi].plane=PLANE(cross_e01_e02.GetNormalized(),faces[fi].vertex0);

		// psd
		CollisionFace *face = &faces[fi];
		face->sphere.position = (face->vertex0 + face->vertex1 + face->vertex2) / 3;
		
		face->sphere.radius = face->sphere.position.GetSquareRangeTo(face->vertex0);
		float tmp = face->sphere.position.GetSquareRangeTo(face->vertex1);
		if(tmp > face->sphere.radius)
			face->sphere.radius = tmp;
		tmp = face->sphere.position.GetSquareRangeTo(face->vertex2);
		if(tmp > face->sphere.radius)
			face->sphere.radius = tmp;

		face->sphere.radius = sqrtf(face->sphere.radius);

		if(face->sphere.position.x - face->sphere.radius < mmin.x)
			mmin.x = face->sphere.position.x - face->sphere.radius;
		if(face->sphere.position.z - face->sphere.radius < mmin.y)
			mmin.y = face->sphere.position.z - face->sphere.radius;

		if(face->sphere.position.x + face->sphere.radius > mmax.x)
			mmax.x = face->sphere.position.x + face->sphere.radius;
		if(face->sphere.position.z + face->sphere.radius > mmax.y)
			mmax.y = face->sphere.position.z + face->sphere.radius;
	}

	tree = new StaticQuadtree<CollisionFace>(mmin, mmax);
	//tree = new Quadtree<CollisionFace>(mmin, mmax);
	for(int i = 0; i < face_amount; ++i)
	{
		CollisionFace &face = faces[i];
		if(face.sphere.radius < 0.001f)
			continue;

		//tree->insert(&face, face.sphere.position, face.sphere.radius);

		float mmin = min(face.vertex0.y, face.vertex1.y);
		mmin = min(mmin, face.vertex2.y);
		float mmax = max(face.vertex0.y, face.vertex1.y);
		mmax = max(mmax, face.vertex2.y);

		tree->insert(face, face.sphere.position, face.sphere.radius, mmin, mmax);
	}
}
Exemple #17
0
void FindPMV(MotionVector *MV_ptr, int x, int y, 
	     int *pmv0, int *pmv1, int block, int newgob, int half_pel)
{
  int p1,p2,p3;
  int xin1,xin2,xin3;
  int yin1,yin2,yin3;
  int vec1,vec2,vec3;
  int l8,o8,or8;

  l8 = o8 = or8 = 0;
 
  vec1 = (l8 ? 2 : 0) ; yin1 = y  ; xin1 = x-1;
  vec2 = (o8 ? 3 : 0) ; yin2 = y-1; xin2 = x;
  vec3 = (or8? 3 : 0) ; yin3 = y-1; xin3 = x+1;

  if (half_pel) {

    p1 = (x > 0) ? 
      2*((*(MV_ptr + yin1*Global::mbc + xin1)).x) + (*(MV_ptr+ yin1*Global::mbc + xin1)).x_half : 0;
    p2 = (y > 0) ? 
      2*((*(MV_ptr + yin2*Global::mbc + xin2)).x) + (*(MV_ptr + yin2*Global::mbc + xin2)).x_half : 2*NO_VEC;
    if((y > 0) && (x < Global::mbc - 1))
      p3 = 2*((*(MV_ptr+yin3*Global::mbc + xin3)).x) + ((*(MV_ptr + yin3*Global::mbc + xin3)).x_half);
    else if(x == Global::mbc - 1)
      p3 = 0;
    else			/* y == 0 && x != Global::mbc - 1 */
      p3 = 2*NO_VEC;
    }
  else {
    p1 =  (x > 0) ? 
      (2*((*(MV_ptr + yin1*Global::mbc + xin1)).x)) : 0;
    p2 =  (y > 0) ? 
      (2*((*(MV_ptr + yin2*Global::mbc + xin2)).x)) : 2*NO_VEC;
    if((y > 0) && (x < Global::mbc - 1))
      p3 = 2*((*(MV_ptr + yin3*Global::mbc + xin3)).x);
    else if(x == Global::mbc - 1)
      p3 = 0;
    else			/* y == 0 && x != Global::mbc - 1 */
      p3 = 2*NO_VEC;
  }

  if (newgob && (block == 0 || block == 1 || block == 2))
    p2 = 2*NO_VEC;

  if (p2 == 2*NO_VEC) { p2 = p3 = p1; }

  *pmv0 = p1+p2+p3 - mmax(p1,mmax(p2,p3)) - mmin(p1,mmin(p2,p3));
  if (half_pel) {
    p1 =  (x > 0) ? 
      (2*((*(MV_ptr + yin1*Global::mbc + xin1)).y)) + ((*(MV_ptr + yin1*Global::mbc + xin1)).y_half) : 0;
    p2 =  (y > 0) ? 
      2*((*(MV_ptr + yin2*Global::mbc + xin2)).y) + ((*(MV_ptr + yin2*Global::mbc + xin2)).y_half) : 2*NO_VEC;

    if((y > 0) && (x < Global::mbc - 1))
      p3 = 2*((*(MV_ptr + yin3*Global::mbc + xin3)).y) + ((*(MV_ptr + Global::mbc*yin3 + xin3)).y_half);
    else if(x == Global::mbc - 1)
      p3 = 0;
    else			/* y == 0 && x != Global::mbc - 1 */
      p3 = 2*NO_VEC;
 
  }
  else {
    p1 = (x > 0) ?
      (2*((*(MV_ptr + yin1*Global::mbc + xin1)).y)) : 0;
    p2 =  (y > 0) ?
      (2*((*(MV_ptr + yin2*Global::mbc + xin2)).y)) : 2*NO_VEC;
    if((y > 0) && (x < Global::mbc - 1))
      p3 = 2*((*(MV_ptr + yin3*Global::mbc + xin3)).y);
    else if(x == Global::mbc - 1)
      p3 = 0;
    else			/* y == 0 && x != Global::mbc - 1 */
      p3 = 2*NO_VEC;
  }    

 
  if (newgob && (block == 0 || block == 1 || block == 2))
    p2 = 2*NO_VEC;

  if (p2 == 2*NO_VEC) { p2 = p3 = p1; }

  *pmv1 = p1+p2+p3 - mmax(p1,mmax(p2,p3)) - mmin(p1,mmin(p2,p3));
  
  return;
}
Exemple #18
0
void datatable2::load_csv(std::string filename, char separatorchar, char commentchar, std::string startswith, std::string endswith, int firstline){
  //std::cout<<"datatable2::load_csv("<<filename<<")\n";
  //std::cout.flush();

  unsigned long lines=count_lines(filename);
  //std::cout<<"datatable2::load_csv("<<filename<<"): lines="<<lines<<"\n";
  //std::cout.flush();
  unsigned long line=0, col=0;
  // reserve enough lines for all lines in file (count lines in file)
  resize(1,lines-(firstline-1));
  clear(); // set accessible size to (0,0)
  //std::cout<<"lines: "<<inttostr(lines)<<std::endl;

  // now open the csv file
  csv_in_separator=separatorchar;
  csv_in_comment=commentchar;

  title_line="";
  csv_file=fopen(filename.c_str(), "rb");
  if (csv_file==NULL) DATATABLE2_ERROR(DATATABLE2_ERROR_FILE_NUM, DATATABLE2_ERROR_FILE_MESSAGE, "datatable2.load_csv("+filename+")");
  setvbuf(csv_file, NULL, _IOFBF ,1024*1024);
  col=0;
  line=0;
  // now parse the file
  double val;
  bool readthiscol=false;
  bool valueset=false;
  std::string linest="";
  //std::cout<<"startswith: '"<<startswith<<"'"<<std::endl;


  if (firstline>1) {
      int l=1;
      while ((!feof(csv_file))&&(l<firstline)) {
          /*char text[4096];
          fgets(text, 4096 , csv_file);
          //std::cout<<"ignore: '"<<text<<"'"<<std::endl;
          linest=text;*/
          char ch=0;
          while ((!feof(csv_file)) && (ch!='\n') && (ch!='\r')) {
              ch=fgetc(csv_file);
              char ch1=fgetc(csv_file);
              if (!((ch=='\n' && ch1=='\r')||(ch=='\r' && ch1=='\n'))) {
                  fseek(csv_file, -1, SEEK_CUR);
                  // if this isn't a \n\r or \r\n linebreak, we read a valid character and have to step back one character in the file
              }

          }
          if ((ch=='\n') || (ch=='\r')) l++;
      }
  }
  if (startswith.size()>0) {
      while ((!feof(csv_file))&&(linest.find(startswith)==std::string::npos)) {
          /*char text[4096];
          fgets(text, 4096 , csv_file);
          //std::cout<<"ignore: '"<<text<<"'"<<std::endl;
          linest=text;*/
          char ch=0;
          linest="";
          while ((!feof(csv_file)) && (ch!='\n') && (ch!='\r')) {
              ch=fgetc(csv_file);
              linest=linest+ch;
          }
      }
  }

  csv_endswith=endswith;

  while(get_token()!=datatable2_EOF) {
      /*switch (current_token) {
        case datatable2_COMMENT:
          //std::cout<<"datatable2_COMMENT\n";
          break;
        case datatable2_TITLECOMMENT: // the title comment line will be saved in title_line by get_token(), so it can be processed after parsing
          //std::cout<<"datatable2_TITLECOMMENT\n";
          break;
        case datatable2_LINEBREAK:
          //std::cout<<"datatable2_LINEBREAK\n";
          break;
        case datatable2_VALUE:
          //std::cout<<"datatable2_VALUE\n";
          break;
        case datatable2_SEPARATOR:
          //std::cout<<"datatable2_SEPARATOR\n";
          break;
        default: break;
      }*/

    switch (current_token) {
      case datatable2_COMMENT:
      case datatable2_TITLECOMMENT: // the title comment line will be saved in title_line by get_token(), so it can be processed after parsing
      case datatable2_LINEBREAK:
        if (readthiscol) line++;
        col=0;
        readthiscol=false;
        valueset=false;
        break;
      case datatable2_VALUE:
        val=0;
        readthiscol=true;
        // replace ',' by '.' to beeing able to read both decimal separators
        //std::cout<<"  '"<<current_value_string<<"'   ";
        if (current_value_string.size()>0)
          for (size_t i=0; i<current_value_string.size(); i++) {
            if (current_value_string[i]==',') current_value_string[i]='.';
          }
        val=atof(current_value_string.c_str());
        //if (line<100) std::cout<<"(c="<<col<<", r="<<line<<")  <=  '"<<current_value_string<<"'   "<<val<<"\n";
        resize(mmax(column_count,col+1), mmax(line_count,line+1));
        data[col][line].value= val;
        data[col][line].empty= false;
        valueset=true;

        // for space/tab separated files there will be no datatable2_SEPARATOR token!!! so we directly enter the next column
        if (isspace(csv_in_separator) || csv_in_separator=='0') {
            resize(mmax(column_count,col+1), mmax(line_count,line+1));
            valueset=false;
            col++;
        }
        break;
      case datatable2_SEPARATOR:
        readthiscol=true;
        if (!valueset){
          data[col][line].value= 0;
          data[col][line].empty= true;
        }
        col++;
        //resize(mmax(column_count,col+1), mmax(line_count,line+1));
        valueset=false;
        break;
      default: break;
    }
  }
  fclose(csv_file);
  clear_titles();
  // now parse title_line:
  if (title_line.size()>0) {
    int title=0;
    for (size_t i=0; i<title_line.size(); i++) {
      if (title_line[i]==csv_in_separator) {
        titles[title]=strstrip(titles[title]);
        title++;
      } else {
        if (((titles[title].size()==0)&& (title_line[i]>32))||
             ((titles[title].size()>0)&&(title_line[i]!='\n')&&(title_line[i]!='\r')))
        titles[title]+=title_line[i];
      }
      if (title>=(int)column_count) break;
    }
  }
  //std::cout<<"'"<<title_line<<"'"<<std::endl;
}
Exemple #19
0
  if (Mode == MODE_INTRA) { /* Intra */
    qcoeff[0] = mmax(1,mmin(254,coeff[0] >> 3)); /* was: /8 */

    if(QP == 8) {

      for(i = 1; i < 64; i++) {
	level = (abs(coeff[i])) >> 4;
	qcoeff[i] = mmin(127, mmax(-127,sign(coeff[i]) * level));
	if(qcoeff[i])
	  CBP = CBP_Mask;
      }
    } else {			/* QP != 8 */
      for(i = 1; i < 64; i++) {

	level = (abs(coeff[i])) / (2*QP);
	qcoeff[i] =  mmin(127,mmax(-127,sign(coeff[i]) * level));
	if(qcoeff[i])
	  CBP = CBP_Mask;
      }

    }	/* End QP == 8 */
  }
  else { /* non Intra */
    if(QP == 8) {
      for(i = 0; i < 64; i++) {
	tempje = abs(coeff[i]) - 4;
	if(tempje < 0) {
	  *(qcoeff++) = 0;
	} else {
	  level = tempje >> 4; /* Note 2*QP == 2*8 = 2^4 == ">>4" */
	  if((*(qcoeff++) = mmin(127,mmax(-127,(sign(coeff[i]) > 0) ?
Exemple #20
0
void simpleQPSolve(Matrix mH, Vector vG, Matrix mA, Vector vB,   // in
                   Vector vP, Vector vLambda, int *info)         // out
{
    const double tolRelFeasibility=1e-6;
//     int *info=NULL;
    int dim=mA.nColumn(), nc=mA.nLine(), ncr, i,j,k, lastJ=-2, *ii;
    MatrixTriangle M(dim);
    Matrix mAR, mZ(dim,dim-1), mHZ(dim,dim-1), mZHZ(dim-1,dim-1);
    Vector vTmp(mmax(nc,dim)), vYB(dim), vD(dim), vTmp2(dim), vTmp3(nc), vLast(dim), 
           vBR_QP, vLambdaScale(nc);
    VectorChar vLB(nc);
    double *lambda=vLambda, *br, *b=vB, violationMax, violationMax2,
           *rlambda,ax,al,dviolation, **a=mA, **ar=mAR, mymin, mymax, maxb, *llambda,
           **r,t, *scaleLambda=vLambdaScale;
    char finished=0, feasible=0, *lb=vLB;

    if (info) *info=0;

    // remove lines which are null
    k=0; vi_QP.setSize(nc); maxb=0.0;
    for (i=0; i<nc; i++)
    {
        mymin=INF; mymax=-INF;
        for (j=0; j<dim; j++)
        {
            mymin=mmin(mymin,a[i][j]);
            mymax=mmax(mymax,a[i][j]);
            if ((mymin!=mymax)||(mymin!=0.0)||(mymax!=0.0)) break;
        }
        if ((mymin!=mymax)||(mymin!=0.0)||(mymax!=0.0))
        {
            lambda[k]=lambda[i];
            maxb=mmax(maxb,condorAbs(b[i]));
            scaleLambda[k]=mA.euclidianNorm(i);
            vi_QP[k]=i;
            k++;
        }
    }
    nc=k; vi_QP.setSize(nc); ii=vi_QP; maxb=(1.0+maxb)*tolRelFeasibility;
    vLast.zero(); 
    
    for (i=0; i<nc; i++) if (lambda[i]!=0.0) lb[i]=2; else lb[i]=1;

    while (!finished)
    {
        finished=1;
        mAR.setSize(dim,dim); mAR.zero(); ar=mAR;
        vBR_QP.setSize(mmin(nc,dim)); br=vBR_QP;
        ncr=0;
        for (i=0; i<nc; i++)
            if (lambda[i]!=0.0)
            {
//                mAR.setLines(ncr,mA,ii[i],1);
                k=ii[i];
                t=scaleLambda[ncr];
                for (j=0; j<dim; j++) ar[ncr][j]=a[k][j]*t;
                br[ncr]=b[ii[i]]*t;
                ncr++;
            }
        mAR.setSize(ncr,dim);
        vBR_QP.setSize(ncr);
        vLastLambda_QP.copyFrom(vLambda); llambda=vLastLambda_QP;

        if (ncr==0)
        {
            // compute step
            vYB.copyFrom(vG);
            vYB.multiply(-1.0);
            if (mH.cholesky(M))
            {
                M.solveInPlace(vYB);
                M.solveTransposInPlace(vYB);
            } else
            {
                printf("warning: cholesky factorisation failed.\n");
                if (info) *info=2;
            }
            vLambda.zero();
        } else
        {
            Matrix mAR2=mAR.clone(), mQ2;
            MatrixTriangle mR2;
            mAR2.QR(mQ2,mR2);

            mAR.QR(mQ_QP,mR_QP, viPermut_QP); // content of mAR is destroyed here !
            bQRFailed_QP=0;

            r=mR_QP;
            for (i=0; i<ncr; i++)
                if (r[i][i]==0.0)
                {
                    // one constraint has been wrongly added.
                    bQRFailed_QP=1;
                    QPReconstructLambda(vLambda,vLambdaScale); vP.copyFrom(vLast); return; 
                }

            for (i=0; i<ncr; i++)
                if (viPermut_QP[i]!=i)
                {
                  //  printf("whoups.\n");
                }
            if (ncr<dim)
            {
                mQ_QP.getSubMatrix(mZ,0,ncr);

                // Z^t H Z
                mH.multiply(mHZ,mZ);
                mZ.transposeAndMultiply(mZHZ,mHZ);
                mQ_QP.setSize(dim,ncr);            
            }

            // form Yb
            vBR_QP.permutIn(vTmp,viPermut_QP);
            mR_QP.solveInPlace(vTmp);
            mQ_QP.multiply(vYB,vTmp);

            if (ncr<dim)
            {

                // ( vG + H vYB )^t Z : result in vD
                
                mH.multiply(vTmp,vYB);
                vTmp+=vG;
                vTmp.transposeAndMultiply(vD,mZ);

                // calculate current delta (result in vD)
                vD.multiply(-1.0);
                if (mZHZ.cholesky(M))
                {
                    M.solveInPlace(vD);
                    M.solveTransposInPlace(vD);
                }
                else
                {
                    printf("warning: cholesky factorisation failed.\n");
                    if (info) *info=2;
                };

                // evaluate vX* (result in vYB):
                mZ.multiply(vTmp, vD);
                vYB+=vTmp;
            }

            // evaluate vG* (result in vTmp2)
            mH.multiply(vTmp2,vYB);
            vTmp2+=vG;

            // evaluate lambda star (result in vTmp):
            mQ2.transposeAndMultiply(vTmp,vTmp2);
            mR2.solveTransposInPlace(vTmp);

            // evaluate lambda star (result in vTmp):
            mQ_QP.transposeAndMultiply(vTmp3,vTmp2);
            mR_QP.solveTransposInPlace(vTmp3);
            vTmp3.permutOut(vTmp,viPermut_QP);
            rlambda=vTmp;

            ncr=0;
            for (i=0; i<nc; i++)
                if (lambda[i]!=0.0)
                {
                    lambda[i]=rlambda[ncr];
                    ncr++;
                }
        } // end of test on ncr==0

        // find the most violated constraint j among non-active Linear constraints:
        j=-1;
        if (nc>0)
        {
            k=-1; violationMax=-INF; violationMax2=-INF;
            for (i=0; i<nc; i++)
            {
                if (lambda[i]<=0.0) // test to see if this constraint is not active 
                {
                    ax=mA.scalarProduct(ii[i],vYB);
                    dviolation=b[ii[i]]-ax;
                    if (llambda[i]==0.0)
                    {
                        // the constraint was not active this round
                        // thus, it can enter the competition for the next 
                        // active constraint

                        if (dviolation>maxb)
                        {
                            // the constraint should be activated
                            if (dviolation>violationMax2) 
                                { k=i; violationMax2=dviolation; }
                            al=mA.scalarProduct(ii[i],vLast)-ax; 
                            if (al>0.0) // test to see if we are going closer
                            {  
                                dviolation/=al;
                                if (dviolation>violationMax ) 
                                    { j=i; violationMax =dviolation; }
                            }
                        }
                    } else
                    {
                        lb[i]--;
                        if (feasible) 
                        {
                            if (lb[i]==0) 
                            {
                                vLambda.copyFrom(vLastLambda_QP);
                                if (lastJ>=0) lambda[lastJ]=0.0;
                                QPReconstructLambda(vLambda,vLambdaScale); 
                                vP.copyFrom(vYB); 
                                return; 
                            }
                        } else
                        {
                            if (lb[i]==0)
                            {
                                if (info) *info=1;
                                QPReconstructLambda(vLambda,vLambdaScale); 
                                vP.zero(); 
                                return;
                            }
                        }
                        finished=0;  // this constraint was wrongly activated.
                        lambda[i]=0.0;
                    }
                }
            }

            // !!! the order the tests is important here !!!
            if ((j==-1)&&(!feasible)) 
            { 
                feasible=1; 
                for (i=0; i<nc; i++) if (llambda[i]!=0.0) lb[i]=2; else lb[i]=1;
            }
            if (j==-1) { j=k; violationMax=violationMax2; } // change j to k after feasible is set
            if (ncr==mmin(dim,nc)) { 
                if (feasible) { // feasible must have been checked before
                    QPReconstructLambda(vLambda,vLambdaScale); vP.copyFrom(vYB); return; 
                } else
                {
                    if (info) *info=1;
                    QPReconstructLambda(vLambda,vLambdaScale); vP.zero(); return; 
                }
            }
            // activation of constraint only if ncr<mmin(dim,nc)
            if (j>=0) { lambda[j]=1e-5; finished=0; } // we need to activate a new constraint 
//            else if (ncr==dim){ 
//                QPReconstructLambda(vLambda); vP.copyFrom(vYB); return; }
        }

        // to prevent rounding error
        if (j==lastJ) { 
//        if (0) {
            QPReconstructLambda(vLambda,vLambdaScale); vP.copyFrom(vYB); return; }
        lastJ=j;

        vLast.copyFrom(vYB);
    }
    QPReconstructLambda(vLambda,vLambdaScale); vP.copyFrom(vYB); return;
}
{
	return a>b ? b : a;
}

static inline ULONG mmax(ULONG a,ULONG b)
{
	return a>b ? a : b;
}

VOID ObtainShineShadowPens (struct ColorMap *cmap, ULONG rgb, LONG &shine, LONG &shadow)
{
  ULONG r = (rgb & 0xff0000) >> 16;
  ULONG g = (rgb & 0x00ff00) >> 8;
  ULONG b = rgb & 0x0000ff;

  ULONG dark_r = mmax(64, r)-64;
  ULONG dark_g = mmax(64, g)-64;
  ULONG dark_b = mmax(64, b)-64;

  ULONG bright_r = mmin(191, r)+64;
  ULONG bright_g = mmin(191, g)+64;
  ULONG bright_b = mmin(191, b)+64;

  ULONG intencity = (r+g+b)/3;
  if(intencity >= 215)
  {
    bright_r = mmin(255, dark_r+32);
    bright_g = mmin(255, dark_g+32);
    bright_b = mmin(255, dark_b+32);

    dark_r = mmax(0, (LONG)dark_r-64);
void CONDOR( double rhoStart, double rhoEnd, int niter, 
              ObjectiveFunction *of, int nnode)
{
    rhoStart=mmax(rhoStart,rhoEnd);
    int dim=of->dim(), info, k, t, nerror;
    double rho=rhoStart, delta=rhoStart, rhoNew,
           lambda1, normD=rhoEnd+1.0, modelStep, reduction, r, valueOF, valueFk, bound, noise;
    Vector d, tmp;
    bool improvement, forceTRStep=true, evalNeeded;
    
    initConstrainedStep(of);

    // pre-create the MultInd indexes to prevent multi-thread problems:
    cacheMultInd.get(dim,1); cacheMultInd.get(dim,2);    

    parallelInit(nnode, dim, of);

    of->initData();
//    points=getFirstPoints(&ValuesF, &nPtsTotal, rhoStart,of);

    InterPolynomial poly(2, rho, Vector::emptyVector, of->data, of);
    if (poly.NewtonBasis==NULL)
    {
        printf("cannot construct lagrange basis.\n");
        exit(255);
    }

    
    
    //Base=poly.vBase;
    k=poly.kbest;
    valueFk=poly.valuesF[k];

    fprintf(stderr,"init part 1 finished.\n");

/*    InterPolynomial poly(dim,2,of);
    for (;;)
    {
        // find index k of the best (lowest) value of the function 
        k=findK(ValuesF, nPtsTotal, of, points);
        Base=points[k].clone();
    //    Base=of->xStart.clone();
        valueFk=ValuesF[k];
        // translation:
        t=nPtsTotal; while (t--) points[t]-=Base;

        // exchange index 0 and index k (to be sure best point is inside poly):
        tmp=points[k];
        points[k]=points[0];
        points[0]=tmp;
        ValuesF[k]=ValuesF[0];
        ValuesF[0]=valueFk;
        k=0;

        poly=InterPolynomial(2, nPtsTotal, points, ValuesF);
        if (poly.NewtonBasis!=NULL) break;

        // the construction of the first polynomial has failed
        // delete[] points;
        free(ValuesF);

        int kbest=findBest(of->data, of); // return 0 if startpoint is given
        Vector BaseStart=of->data.getLine(kbest,dim);
        double vBaseStart=((double**)of->data)[kbest][dim];
        points=GenerateData(rho, BaseStart, vBaseStart, of, &ValuesF);
        nPtsTotal=n;
    }
*/
    // update M:
    fullUpdateOfM(rho,poly.vBase,of->data,poly);
    
    fprintf(stderr,"init part 2 finished.\n");
    fprintf(stderr,"init finished.\n");

    // first of init all variables:
    parallelImprove(&poly, &k, rho, &valueFk, poly.vBase);

    // really start in parallel:
    startParallelThread();

    while (true)
    {
//        fprintf(stderr,"rho=%e; fo=%e; NF=%i\n", rho,valueFk,QP_NF);
        while (true)
        {
            // trust region step
            while (true)
            {
//                poly.print();
                parallelImprove(&poly, &k, rho, &valueFk, poly.vBase);

                niter--;
                if ((niter==0)
                   ||(of->isConstrained&&checkForTermination(poly.NewtonPoints[k], poly.vBase, rhoEnd)))
                {
                    poly.vBase+=poly.NewtonPoints[k];
                    fprintf(stderr,"rho=%e; fo=%e; NF=%i\n", rho,valueFk,of->getNFE());
                    of->valueBest=valueFk;
                    of->xBest=poly.vBase;
                    // to do : compute H and Lambda

                    Vector vG(dim);
                    Matrix mH(dim,dim);
                    poly.gradientHessian(poly.NewtonPoints[k],vG,mH);
                    of->finalize(vG,mH,FullLambda.clone());
                    return;
                }
   
                // to debug:
                fprintf(stderr,"Best Value Objective=%e (nfe=%i)\n", valueFk, of->getNFE());
                
                d=ConstrainedL2NormMinimizer(poly,k,delta,&info,1000,&lambda1,poly.vBase,of);

//                if (d.euclidianNorm()>delta)
//                {
//                    printf("Warning d to long: (%e > %e)\n", d.euclidianNorm(), delta);
//                }

                normD=mmin(d.euclidianNorm(), delta);
                d+=poly.NewtonPoints[k];

//              next line is equivalent to reduction=valueFk-poly(d); 
//              BUT is more precise (no rounding error)
                reduction=-poly.shiftedEval(d,valueFk);

                //if (normD<0.5*rho) { evalNeeded=true; break; }
                if ((normD<0.5*rho)&&(!forceTRStep)) { evalNeeded=true; break; }

                //  IF THE MODEL REDUCTION IS SMALL, THEN WE DO NOT SAMPLE FUNCTION
                //  AT THE NEW POINT. WE THEN WILL TRY TO IMPROVE THE MODEL.

                noise=0.5*mmax(of->noiseAbsolute*(1+of->noiseRelative), abs(valueFk)*of->noiseRelative);
                if ((reduction<noise)&&(!forceTRStep)) { evalNeeded=true; break; }
                forceTRStep=false; evalNeeded=false;

                if (quickHack) (*quickHack)(poly,k);
                tmp=poly.vBase+d; nerror=0; valueOF=of->eval(tmp, &nerror); 
                of->saveValue(tmp,valueOF,nerror);
                if (nerror)
                {
                    // evaluation failed
                    delta*=0.5;
                    if (normD>=2*rho) continue;
                    break;
                }
                if (!of->isFeasible(tmp, &r))
                {
                    fprintf(stderr, "violation: %e\n",r);
                }

                // update of delta:
                r=(valueFk-valueOF)/reduction;
                if (r<=0.1) delta=0.5*normD;
                else if (r<0.7) delta=mmax(0.5*delta, normD);
                     else delta=mmax(rho+ normD, mmax(1.25*normD, delta));
            // powell's heuristics:
                if (delta<1.5*rho) delta=rho;

                if (valueOF<valueFk) 
                {
                    t=poly.findAGoodPointToReplace(-1, rho, d,&modelStep);
                    k=t; valueFk=valueOF; 
                    improvement=true;
//                    fprintf(stderr,"Value Objective=%e\n", valueOF);
                } else
                {
                    t=poly.findAGoodPointToReplace(k, rho, d,&modelStep);
                    improvement=false;
//                    fprintf(stderr,".");
                };

                if (t<0) { poly.updateM(d, valueOF); break; }

                // If we are along constraints, it's more important to update
                // the polynomial with points which increase its quality.
                // Thus, we will skip this update to use only points coming
                // from checkIfValidityIsInBound

                if ((!of->isConstrained)||(improvement)||(reduction>0.0)||(normD<rho)) poly.replace(t, d, valueOF); 

                if (improvement) continue;
//                if (modelStep>4*rho*rho) continue;
                if (modelStep>2*rho) continue;
                if (normD>=2*rho) continue;
                break;
            }
            // model improvement step
            forceTRStep=true;

//            fprintf(stderr,"improvement step\n");
            bound=0.0;
            if (normD<0.5*rho) 
            {
                bound=0.5*sqr(rho)*lambda1;
                if (poly.nUpdateOfM<10) bound=0.0;
            }

            parallelImprove(&poly, &k, rho, &valueFk, poly.vBase);

            // !! change d (if needed):
            t=poly.checkIfValidityIsInBound(d, k, bound, rho );
            if (t>=0)
            {
                if (quickHack) (*quickHack)(poly,k);
                tmp=poly.vBase+d; nerror=0; valueOF=of->eval(tmp, &nerror); 
                if (nerror) 
                {
                    Vector GXk(dim);
                    Matrix H(dim,dim);
                    poly.NewtonBasis[t].gradientHessian(poly.NewtonPoints[k],GXk,H);
                    double rhot=rho,vmax;

                    while (nerror)
                    {
                        rhot*=.5;
			            d=LAGMAXModified(GXk,H,rhot,vmax);
	                    d+=poly.NewtonPoints[k];
                        tmp=poly.vBase+d; nerror=0; valueOF=of->eval(tmp, &nerror); 
                        of->saveValue(tmp,valueOF,nerror);
                    }
                }
                poly.replace(t, d, valueOF); 
                if ((valueOF<valueFk)&&
                    (of->isFeasible(tmp))) { k=t; valueFk=valueOF; };
                continue;
            }

            // the model is perfect for this value of rho:
            // OR
            // we have crossed a non_linear constraint which prevent us to advance
            if ((normD<=rho)||(reduction<0.0)) break;
        }

        
        
        // change rho because no improvement can now be made:
        if (rho<=rhoEnd) break;

        fprintf(stderr,"rho=%e; fo=%e; NF=%i\n", rho,valueFk,of->getNFE());

        if (rho<16*rhoEnd) rhoNew=rhoEnd;
        else if (rho<250*rhoEnd) rhoNew=sqrt(rho*rhoEnd);
             else rhoNew=0.1*rho;
        delta=mmax(0.5*rho,rhoNew);
        rho=rhoNew;

        
        // update of the polynomial: translation of x[k].
        // replace BASE by BASE+x[k]
        poly.translate(poly.NewtonPoints[k]);
    }
    parallelFinish();
    
    Vector vG(dim);
    Matrix mH(dim,dim);

    
    
    if (evalNeeded)
    {
        tmp=poly.vBase+d; nerror=0; valueOF=of->eval(tmp,&nerror); 
        of->saveValue(tmp,valueOF,nerror);
        if ((nerror)||(valueOF<valueFk))
        {
            poly.vBase+=poly.NewtonPoints[k];
            poly.gradientHessian(poly.NewtonPoints[k],vG,mH);
        }
        else
        {
            valueFk=valueOF; poly.vBase=tmp;
            poly.gradientHessian(d,vG,mH);
        }
    } else 
    {
        poly.vBase+=poly.NewtonPoints[k];
        poly.gradientHessian(poly.NewtonPoints[k],vG,mH);
    }


//    delete[] points; :not necessary: done in destructor of poly which is called automatically:
    fprintf(stderr,"rho=%e; fo=%e; NF=%i\n", rho,valueFk,of->getNFE());
    
    of->valueBest=valueFk;
    of->xBest=poly.vBase;
    of->finalize(vG,mH,FullLambda.clone());
    
}