void Polyhedron<Real>::addConvexPointToPolyhedron(
													const std::vector<plane<Real >> &planes,
													const std::vector<vector3<Real >> &vertices,
													const std::vector<PolyhedronEdge> &edges,
													const vector3<Real> &spot,
													std::vector<plane<Real >> &new_planes,
													std::vector<vector3<Real >> &new_vertices,
													std::vector<PolyhedronEdge> &new_edges)
	{
		//TODO wyprofilować i zoptymalizować

		/*
		 założenia:
		 1) żaden wierzchołek się nie powtarza
		 2) żadna płaszczyzna się nie powtarza
		 */

		vector3<Real> averagePoint(vector3<Real>::zero);

		Real scale = ((Real) 1.0) / vertices.size();
		for (uint i = 0; i < vertices.size(); ++i)
			averagePoint += vertices[i] * scale;

		new_vertices.reserve(vertices.size() + 1);
		new_vertices.clear();
		new_vertices.push_back(spot);
		int num_spot = 0; // new_vertices.size() -1;

		new_edges.clear();
		new_planes.clear();

		std::vector<bool> isPlaneUseful(planes.size());
		std::vector<int> oldNewVertexMapping(vertices.size());
		std::vector<int> oldNewPlaneMapping(planes.size());

		/*
		 klucz - indeks starego wierzchołka (!= spot) nowej krawędzi
		 wartość - druga ściana która wspóldzieli nową krawędź lub pusta gdy nieznana
		 */
		std::map<int, int> oldEdgesToNewWalls;

		for (uint i = 0; i < oldNewVertexMapping.size(); ++i)
			oldNewVertexMapping[i] = -1; //unused
		for (uint i = 0; i < oldNewPlaneMapping.size(); ++i)
			oldNewPlaneMapping[i] = -1; //unused


		for (uint i = 0; i < planes.size(); ++i)
		{
			bool planeUseful = (planes[i].distance(spot) >= -std::max(error, std::fabs(error * planes[i].d)));
			isPlaneUseful[i] = planeUseful;
			if (planeUseful)
			{
				new_planes.push_back(planes[i]);
				oldNewPlaneMapping[i] = new_planes.size() - 1;
			}
		}

		for (uint i = 0; i < edges.size(); ++i)
		{
			char usefulness = 0;
			if (isPlaneUseful[edges[i].num_p1])
				usefulness++;
			if (isPlaneUseful[edges[i].num_p2])
				usefulness++;

			if (usefulness == 0)
				continue;

			/*
			 wierczhołkom mogły pozmieniać się numery, następne 10 linijek to
			 załatwia
			 */
			int new_num_v1 = oldNewVertexMapping[edges[i].num_v1];
			if (new_num_v1 == -1)
			{
				new_vertices.push_back(vertices[edges[i].num_v1]);
				new_num_v1 = new_vertices.size() - 1;
				oldNewVertexMapping[edges[i].num_v1] = new_num_v1;
			}

			int new_num_v2 = oldNewVertexMapping[edges[i].num_v2];
			if (new_num_v2 == -1)
			{
				new_vertices.push_back(vertices[edges[i].num_v2]);
				new_num_v2 = new_vertices.size() - 1;
				oldNewVertexMapping[edges[i].num_v2] = new_num_v2;
			}

			/*
			 płaszczyznom też mogły się zmienić numery, ale tu test na -1
			 (wyrzucenie złej płaszczyzny) zanużymy w podprzypadku.
			 */

			int new_num_p1 = oldNewPlaneMapping[edges[i].num_p1];
			int new_num_p2 = oldNewPlaneMapping[edges[i].num_p2];

			if (usefulness == 2) // obie płaszczyzny istnieją, super.
			{
				//PolyhedronEdge(uint _num_v1, uint _num_v2, uint _num_p1, uint _num_p2)
				new_edges.push_back(PolyhedronEdge(new_num_v1, new_num_v2, new_num_p1, new_num_p2));
			}
			else
			{ // jedna istnieje, druga nie.
				if (new_num_p1 == -1) // dla ułatwienia, zawsze druga nieistnieje
				{
					new_num_p1 = new_num_p2;
					new_num_p2 = -1;
				}

				// tworzę nową ścianę
				plane<Real> new_plane(new_vertices[new_num_v1], new_vertices[new_num_v2], spot);
				
				/*
				 plane<Real> new_plane2(plane<Real>::stablePlaneFromPoints(new_vertices[new_num_v1], new_vertices[new_num_v2], spot));
				
				NEWLOG("p1:[%f\t][%f\t][%f\t][%f\t]\np2:[%f\t][%f\t][%f\t][%f\t]",
					 new_plane.normal.x, new_plane.normal.y, new_plane.normal.z, new_plane.d,
					 new_plane2.normal.x, new_plane2.normal.y, new_plane2.normal.z, new_plane2.d);
				*/
				
				if (new_plane.distance(averagePoint) < -std::max(error, std::fabs(error * new_plane.d)))
					new_plane.flip();

				new_planes.push_back(new_plane);
				new_num_p2 = new_planes.size() - 1;

				//dodaję STARĄ krawędź

				new_edges.push_back(PolyhedronEdge(new_num_v1, new_num_v2, new_num_p1, new_num_p2));

				/*
				 próbuję dodać od 0 do 2 NOWYCH KRAWĘDZI
				 TUTAJ new_num_p1 jest już BEZUŻYTECZNE, (wskazuje starą ścianę, już załatwioną)
				 new_num_p2 wskazuje nowoutworzoną ścianę 
				 new_num_v1 i new_num_v2 wskazują stare wierzchołki
				 
				 poniższy kod działa tak:
				 dla każdego ze starych wierzchołków (new_num_v1, new_num_v2)
				 mam krawędź (stary_wierzchołek, spot) którą identyfikuję
				 za pomocą indeksu starego wierzchołka (wallKey)
				 
				 sprawdzam w mapie: jeśli druga ściana przyległa do tej krawędzi
				 już istnieje, to mogę dodać krawędź do zbioru nowych
				 (bo wreszcie znam wszystkie arg. konstruktora)
				 jeśli jeszcze nie istenieje, to zostawiam informacje o tej ścianie
				 i czekam, aż krawędź zostanie dodana przy okazji dodawania ściany
				 przyległej.
				 */
				std::map<int, int>::iterator secondWall;

				// najpierw sprawdzamy ścianę przyległą z new_num_v1
				int wallKey = new_num_v1;
				secondWall = oldEdgesToNewWalls.find(wallKey);

				if (secondWall == oldEdgesToNewWalls.end()) // nie znamy drugiej ściany dla tej krawędzi.
				{
					oldEdgesToNewWalls[wallKey] = new_num_p2; // to ją dodajemy i kiedyś do tego wrócimy
					//NEWLOG("pkt %d czeka", wallKey);
				}
				else // wiemy z którą ścianą ta krawędź będzie współdzielona
				{
					//NEWLOG("pkt %d się doczekał", secondWall->first);
					new_edges.push_back(PolyhedronEdge(new_num_v1, num_spot, new_num_p2, secondWall->second));
				}
				// teraz sprawdzamy ścianę przyległa z new_num_v2

				wallKey = new_num_v2;
				secondWall = oldEdgesToNewWalls.find(wallKey);

				if (secondWall == oldEdgesToNewWalls.end()) // nie znamy drugiej ściany dla tej krawędzi.
				{
					oldEdgesToNewWalls[wallKey] = new_num_p2; // to ją dodajemy i kiedyś do tego wrócimy
					//NEWLOG("pkt %d czeka", wallKey);
				}
				else // wiemy z którą ścianą ta krawędź będzie współdzielona
				{
					//NEWLOG("pkt %d się doczekał", secondWall->first);
					new_edges.push_back(PolyhedronEdge(new_num_v2, num_spot, new_num_p2, secondWall->second));
				}
			}
		}
	}
/***********************************************************************//**
 * @brief Reserves space for parameters in container
 *
 * @param[in] num Number of parameters.
 *
 * Reserves space for @p num parameters in the container.
 ***************************************************************************/
inline
void GOptimizerPars::reserve(const int& num)
{
    m_pars.reserve(num);
    return;
}
Exemple #3
0
 void AppendArray(std::vector<T> &vec, T* arr, unsigned int size) {
     vec.reserve(vec.size() + size);
     for (unsigned int i = 0; i < size; i++)
         vec.push_back(arr[i]);
 }
void
PlotterAdapter3d::project3dNoCopy( std::vector<MC2Point>::iterator begin,
                                   std::vector<MC2Point>::iterator end,
                                   std::vector<MC2Point>& res,
                                   int scalefactor )
{
   // Do the needful.

#ifdef __unix__
   #undef mc2dbg
   //#define mc2dbg cout
   #define mc2dbg mc2dbg8
#endif
   
   res.clear();
   res.reserve( std::distance( begin, end ) );

   checkScreenAndUpdateMembers( scalefactor );
   
   m_clippedPoints.clear();
   m_clippedPoints.insert( m_clippedPoints.end(), begin, end );

   m_clipUtil.clipPolyToBBoxFast( m_clipBox, m_clippedPoints );
   
   begin = m_clippedPoints.begin();
   end = m_clippedPoints.end();

   mc2dbg << "M_Height: " << m_height << " m_width: " << m_width << endl;
   
   mc2dbg << "3D: tmppoly = [];" << endl;
   for (std::vector<MC2Point>::const_iterator it = begin; it != end; ++it ) {


      int intorigx = it->getX();
      int intorigy = it->getY();

      int intx = -m_intPa*intorigx + m_intPa_times_m_Vd;
      int inty = m_intPb_times_m_Vf*intorigy + m_intPb_times_m_Vh;
      int intw = -m_intVj*intorigy -m_intVl;




//      if ( fabs(x) >= 1 || fabs(y) >= 1 || fabs(z) >= 1 ) {
//         mc2dbg << "Outside [-1,1]^3 :  x " << x << ",y " << y << ",z " << z << endl;
//      }

      
//      int intxw = intwidth*(-intx/intw+1)/2;
//      int intyw = inthorizHeight + (intheight - inthorizHeight)*(-inty/intw+2)/2;
     

      int nominatorX = (m_intWidth*intx);
      int denominatorX = intw*2;
      
      int tmpIntxw = nominatorX / denominatorX;
      if ((nominatorX % denominatorX) >= (denominatorX/2)) {
         ++ tmpIntxw;
      }

      int intxw = int(-tmpIntxw + m_intWidth/2);

      // Old
//      int intxwold = int(-(m_intWidth*intx)/intw/2 + m_intWidth/2);
      
      
      int nominatorY = ((m_intHeight - m_intHorizHeight)*(inty));
      int denominatorY = intw*2;
      
      int tmpIntyw = (nominatorY / denominatorY);
      if ((nominatorY % denominatorY) >= (denominatorY/2)) {
         ++ tmpIntyw;
      }

      int intyw = int(m_intHorizHeight 
         -tmpIntyw + (m_intHeight - m_intHorizHeight));
         // Old version.
//      int intywold = int(m_intHorizHeight + 
//         ((m_intHeight - m_intHorizHeight)*(-inty))/intw/2 + (m_intHeight - m_intHorizHeight));

#if 0
//      if ( rint(xw) != intxw || rint(yw) != intyw) {

         cout << "xw = " << xw << ", rint(xw) = " << rint(xw) << ", intxw = " << intxw << ", intxwold = " << intxwold
              << ", yw = " << yw << ", rint(yw) = " << rint(yw) << ", intyw = " << intyw << ", intywold = " << intywold << endl;
         if ( w < 0 ) {
            mc2dbg << "w " << w << endl;
         }

//      }
#endif
      MC2Point p( intxw, intyw );
//      MC2Point p( static_cast<int>(rint(xw)), static_cast<int>(rint(yw)) );
      mc2dbg << "orig: " << *it << ", trans: " << p << endl;
//      mc2dbg << "3D: " << "tmppoly = [ tmppoly " << p.getX() << " " << p.getY() << " " << (z+1)/2 << " ];" << endl;

      res.push_back( p ); 
   }
   
   mc2dbg << "3D: newpolys = append( newpolys, tmppoly );" << endl;  
}
Exemple #5
0
bool
DPXOutput::open (const std::string &name, const ImageSpec &userspec,
                 OpenMode mode)
{
    close ();  // Close any already-opened file

    if (mode != Create) {
        error ("%s does not support subimages or MIP levels", format_name());
        return false;
    }

    m_spec = userspec;  // Stash the spec

    // open the image
    m_stream = new OutStream();
    if (! m_stream->Open(name.c_str ())) {
        error ("Could not open file \"%s\"", name.c_str ());
        return false;
    }

    // Check for things this format doesn't support
    if (m_spec.width < 1 || m_spec.height < 1) {
        error ("Image resolution must be at least 1x1, you asked for %d x %d",
                       m_spec.width, m_spec.height);
                       return false;
    }

    if (m_spec.depth < 1)
        m_spec.depth = 1;
    else if (m_spec.depth > 1) {
        error ("DPX does not support volume images (depth > 1)");
        return false;
    }

    if (m_spec.format == TypeDesc::UINT8
        || m_spec.format == TypeDesc::INT8)
        m_datasize = dpx::kByte;
    else if (m_spec.format == TypeDesc::UINT16
        || m_spec.format == TypeDesc::INT16)
        m_datasize = dpx::kWord;
    else if (m_spec.format == TypeDesc::FLOAT
        || m_spec.format == TypeDesc::HALF) {
        m_spec.format = TypeDesc::FLOAT;
        m_datasize = dpx::kFloat;
    } else if (m_spec.format == TypeDesc::DOUBLE)
        m_datasize = dpx::kDouble;
    else {
        // use 16-bit unsigned integers as a failsafe
        m_spec.format = TypeDesc::UINT16;
        m_datasize = dpx::kWord;
    }

    // check if the client is giving us raw data to write
    m_wantRaw = m_spec.get_int_attribute ("dpx:RawData", 0) != 0;
    
    // check if the client wants endianness reverse to native
    // assume big endian per Jeremy's request, unless little endian is
    // explicitly specified
    std::string tmpstr = m_spec.get_string_attribute ("oiio:Endian", littleendian() ? "little" : "big");
    m_wantSwap = (littleendian() != Strutil::iequals (tmpstr, "little"));

    m_dpx.SetOutStream (m_stream);

    // start out the file
    m_dpx.Start ();

    // some metadata
    std::string project = m_spec.get_string_attribute ("DocumentName", "");
    std::string copyright = m_spec.get_string_attribute ("Copyright", "");
    tmpstr = m_spec.get_string_attribute ("DateTime", "");
    if (tmpstr.size () >= 19) {
        // libdpx's date/time format is pretty close to OIIO's (libdpx uses
        // %Y:%m:%d:%H:%M:%S%Z)
        // NOTE: the following code relies on the DateTime attribute being properly
        // formatted!
        // assume UTC for simplicity's sake, fix it if someone complains
        tmpstr[10] = ':';
        tmpstr.replace (19, -1, "Z");
    }
    m_dpx.SetFileInfo (name.c_str (),                       // filename
        tmpstr.c_str (),                                    // cr. date
        OIIO_INTRO_STRING,                                  // creator
        project.empty () ? NULL : project.c_str (),         // project
        copyright.empty () ? NULL : copyright.c_str (),     // copyright
        m_spec.get_int_attribute ("dpx:EncryptKey", ~0),    // encryption key
        m_wantSwap);

    // image info
    m_dpx.SetImageInfo (m_spec.width, m_spec.height);

    // determine descriptor
    m_desc = get_descriptor_from_string
        (m_spec.get_string_attribute ("dpx:ImageDescriptor", ""));

    // transfer function
    dpx::Characteristic transfer;
    
    std::string colorspace = m_spec.get_string_attribute ("oiio:ColorSpace", "");
    if (Strutil::iequals (colorspace, "Linear"))  transfer = dpx::kLinear;
    else if (Strutil::iequals (colorspace, "GammaCorrected")) transfer = dpx::kUserDefined;
    else if (Strutil::iequals (colorspace, "Rec709")) transfer = dpx::kITUR709;
    else if (Strutil::iequals (colorspace, "KodakLog")) transfer = dpx::kLogarithmic;
    else {
        std::string dpxtransfer = m_spec.get_string_attribute ("dpx:Transfer", "");
        transfer = get_characteristic_from_string (dpxtransfer);
    }
    
    // colorimetric
    m_cmetr = get_characteristic_from_string
        (m_spec.get_string_attribute ("dpx:Colorimetric", "User defined"));

    // select packing method
    dpx::Packing packing;
    tmpstr = m_spec.get_string_attribute ("dpx:Packing", "Filled, method A");
    if (Strutil::iequals (tmpstr, "Packed"))
        packing = dpx::kPacked;
    else if (Strutil::iequals (tmpstr, "Filled, method B"))
        packing = dpx::kFilledMethodB;
    else
        packing = dpx::kFilledMethodA;

    // calculate target bit depth
    int bitDepth = m_spec.format.size () * 8;
    if (m_spec.format == TypeDesc::UINT16) {
        bitDepth = m_spec.get_int_attribute ("oiio:BitsPerSample", 16);
        if (bitDepth != 10 && bitDepth != 12 && bitDepth != 16) {
            error ("Unsupported bit depth %d", bitDepth);
            return false;
        }
    }
    m_dpx.header.SetBitDepth (0, bitDepth);

    // Bug workaround: libDPX doesn't appear to correctly support
    // "filled method A" for 12 bit data.  Does anybody care what
    // packing/filling we use?  Punt and just use "packed".
    if (bitDepth == 12)
        packing = dpx::kPacked;
    
    // see if we'll need to convert or not
    if (m_desc == dpx::kRGB || m_desc == dpx::kRGBA) {
        // shortcut for RGB(A) that gets the job done
        m_bytes = m_spec.scanline_bytes ();
        m_wantRaw = true;
    } else {
        m_bytes = dpx::QueryNativeBufferSize (m_desc, m_datasize, m_spec.width, 1);
        if (m_bytes == 0 && !m_wantRaw) {
            error ("Unable to deliver native format data from source data");
            return false;
        } else if (m_bytes < 0) {
            // no need to allocate another buffer
            if (!m_wantRaw)
                m_bytes = m_spec.scanline_bytes ();
            else
                m_bytes = -m_bytes;
        }
    }

    if (m_bytes < 0)
        m_bytes = -m_bytes;

    m_dpx.SetElement (0, m_desc, bitDepth, transfer, m_cmetr,
        packing, dpx::kNone, (m_spec.format == TypeDesc::INT8
            || m_spec.format == TypeDesc::INT16) ? 1 : 0,
        m_spec.get_int_attribute ("dpx:LowData", 0xFFFFFFFF),
        m_spec.get_float_attribute ("dpx:LowQuantity", std::numeric_limits<float>::quiet_NaN()),
        m_spec.get_int_attribute ("dpx:HighData", 0xFFFFFFFF),
        m_spec.get_float_attribute ("dpx:HighQuantity", std::numeric_limits<float>::quiet_NaN()),
        m_spec.get_int_attribute ("dpx:EndOfLinePadding", 0),
        m_spec.get_int_attribute ("dpx:EndOfImagePadding", 0));

    m_dpx.header.SetXScannedSize (m_spec.get_float_attribute
        ("dpx:XScannedSize", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetYScannedSize (m_spec.get_float_attribute
        ("dpx:YScannedSize", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetFramePosition (m_spec.get_int_attribute
        ("dpx:FramePosition", 0xFFFFFFFF));
    m_dpx.header.SetSequenceLength (m_spec.get_int_attribute
        ("dpx:SequenceLength", 0xFFFFFFFF));
    m_dpx.header.SetHeldCount (m_spec.get_int_attribute
        ("dpx:HeldCount", 0xFFFFFFFF));
    m_dpx.header.SetFrameRate (m_spec.get_float_attribute
        ("dpx:FrameRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetShutterAngle (m_spec.get_float_attribute
        ("dpx:ShutterAngle", std::numeric_limits<float>::quiet_NaN()));
    // FIXME: should we write the input version through or always default to 2.0?
    /*tmpstr = m_spec.get_string_attribute ("dpx:Version", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetVersion (tmpstr.c_str ());*/
    tmpstr = m_spec.get_string_attribute ("dpx:Format", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetFormat (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:FrameId", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetFrameId (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:SlateInfo", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetSlateInfo (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:SourceImageFileName", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetSourceImageFileName (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:InputDevice", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetInputDevice (tmpstr.c_str ());
    tmpstr = m_spec.get_string_attribute ("dpx:InputDeviceSerialNumber", "");
    if (tmpstr.size () > 0)
        m_dpx.header.SetInputDeviceSerialNumber (tmpstr.c_str ());
    m_dpx.header.SetInterlace (m_spec.get_int_attribute ("dpx:Interlace", 0xFF));
    m_dpx.header.SetFieldNumber (m_spec.get_int_attribute ("dpx:FieldNumber", 0xFF));
    m_dpx.header.SetHorizontalSampleRate (m_spec.get_float_attribute
        ("dpx:HorizontalSampleRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetVerticalSampleRate (m_spec.get_float_attribute
        ("dpx:VerticalSampleRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetTemporalFrameRate (m_spec.get_float_attribute
        ("dpx:TemporalFrameRate", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetTimeOffset (m_spec.get_float_attribute
        ("dpx:TimeOffset", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetBlackLevel (m_spec.get_float_attribute
        ("dpx:BlackLevel", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetBlackGain (m_spec.get_float_attribute
        ("dpx:BlackGain", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetBreakPoint (m_spec.get_float_attribute
        ("dpx:BreakPoint", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetWhiteLevel (m_spec.get_float_attribute
        ("dpx:WhiteLevel", std::numeric_limits<float>::quiet_NaN()));
    m_dpx.header.SetIntegrationTimes (m_spec.get_float_attribute
        ("dpx:IntegrationTimes", std::numeric_limits<float>::quiet_NaN()));
    float aspect = m_spec.get_float_attribute ("PixelAspectRatio", 1.0f);
    int aspect_num, aspect_den;
    float_to_rational (aspect, aspect_num, aspect_den);
    m_dpx.header.SetAspectRatio (0, aspect_num);
    m_dpx.header.SetAspectRatio (1, aspect_den);

    tmpstr = m_spec.get_string_attribute ("dpx:TimeCode", "");
    int tmpint = m_spec.get_int_attribute ("dpx:TimeCode", ~0);
    if (tmpstr.size () > 0)
        m_dpx.header.SetTimeCode (tmpstr.c_str ());
    else if (tmpint != ~0)
        m_dpx.header.timeCode = tmpint;
    m_dpx.header.userBits = m_spec.get_int_attribute ("dpx:UserBits", ~0);
    tmpstr = m_spec.get_string_attribute ("dpx:SourceDateTime", "");
    if (tmpstr.size () >= 19) {
        // libdpx's date/time format is pretty close to OIIO's (libdpx uses
        // %Y:%m:%d:%H:%M:%S%Z)
        // NOTE: the following code relies on the DateTime attribute being properly
        // formatted!
        // assume UTC for simplicity's sake, fix it if someone complains
        tmpstr[10] = ':';
        tmpstr.replace (19, -1, "Z");
        m_dpx.header.SetSourceTimeDate (tmpstr.c_str ());
    }
    
    // commit!
    if (!m_dpx.WriteHeader ()) {
        error ("Failed to write DPX header");
        return false;
    }

    // user data
    ImageIOParameter *user = m_spec.find_attribute ("dpx:UserData");
    if (user && user->datasize () > 0) {
        if (user->datasize () > 1024 * 1024) {
            error ("User data block size exceeds 1 MB");
            return false;
        }
        // FIXME: write the missing libdpx code
        /*m_dpx.SetUserData (user->datasize ());
        if (!m_dpx.WriteUserData ((void *)user->data ())) {
            error ("Failed to write user data");
            return false;
        }*/
    }

    // reserve space for the image data buffer
    m_buf.reserve (m_bytes * m_spec.height);

    return true;
}
Exemple #6
0
bool GetFileString::GetTString(std::vector<T>& From, std::vector<T>& To, bool bBigEndian)
{
	typedef eol<T> eol;

	bool ExitCode = true;
	T* ReadBufPtr = ReadPos < ReadSize ? From.data() + ReadPos / sizeof(T) : nullptr;

	To.clear();

	// Обработка ситуации, когда у нас пришёл двойной \r\r, а потом не было \n.
	// В этом случаем считаем \r\r двумя MAC окончаниями строк.
	if (bCrCr)
	{
		To.emplace_back(T(eol::cr));
		bCrCr = false;
	}
	else
	{
		EolType Eol = FEOL_NONE;
		for (;;)
		{
			if (ReadPos >= ReadSize)
			{
				if (!(SrcFile.Read(From.data(), ReadBufCount*sizeof(T), ReadSize) && ReadSize))
				{
					if (To.empty())
					{
						ExitCode = false;
					}
					break;
				}

				if (bBigEndian && sizeof(T) != 1)
				{
					_swab(reinterpret_cast<char*>(From.data()), reinterpret_cast<char*>(From.data()), static_cast<int>(ReadSize));
				}

				ReadPos = 0;
				ReadBufPtr = From.data();
			}
			if (Eol == FEOL_NONE)
			{
				// UNIX
				if (*ReadBufPtr == eol::lf)
				{
					Eol = FEOL_UNIX;
				}
				// MAC / Windows? / Notepad?
				else if (*ReadBufPtr == eol::cr)
				{
					Eol = FEOL_MAC;
				}
			}
			else if (Eol == FEOL_MAC)
			{
				// Windows
				if (*ReadBufPtr == eol::lf)
				{
					Eol = FEOL_WINDOWS;
				}
				// Notepad?
				else if (*ReadBufPtr == eol::cr)
				{
					Eol = FEOL_MAC2;
				}
				else
				{
					break;
				}
			}
			else if (Eol == FEOL_WINDOWS || Eol == FEOL_UNIX)
			{
				break;
			}
			else if (Eol == FEOL_MAC2)
			{
				// Notepad
				if (*ReadBufPtr == eol::lf)
				{
					Eol = FEOL_NOTEPAD;
				}
				else
				{
					// Пришёл \r\r, а \n не пришёл, поэтому считаем \r\r двумя MAC окончаниями строк
					To.pop_back();
					bCrCr = true;
					break;
				}
			}
			else
			{
				break;
			}

			ReadPos += sizeof(T);

			if (To.size() == To.capacity())
				To.reserve(To.size() * 2);

			To.emplace_back(*ReadBufPtr);
			ReadBufPtr++;
		}
	}
	To.push_back(0);
	return ExitCode;
}
Exemple #7
0
MStatus mapBlendShape::deform(MDataBlock& data, 
							  MItGeometry& itGeo, 
							  const MMatrix& localToWorldMatrix, 
							  unsigned int geomIndex)
{
    MStatus status;

	// get the blendMesh 
	MDataHandle hBlendMesh = data.inputValue( aBlendMesh, &status );
    CHECK_MSTATUS_AND_RETURN_IT( status );
    MObject oBlendMesh = hBlendMesh.asMesh();
    if (oBlendMesh.isNull())
    {
        return MS::kSuccess;
    }

	MFnMesh fnMesh( oBlendMesh, &status );
    CHECK_MSTATUS_AND_RETURN_IT( status );
    MPointArray blendPoints;
    fnMesh.getPoints( blendPoints );

	// get the dirty flags for the input and blendMap
	bool inputGeomClean = data.isClean(inputGeom, &status);
	bool blendMapClean  = data.isClean(aBlendMap, &status);

	if (!blendMapClean) {
		lumValues.reserve(itGeo.count());
	}
	
	MDoubleArray uCoords, vCoords;
	MVectorArray resultColors;
	MDoubleArray resultAlphas;

	uCoords.setLength(1);
	vCoords.setLength(1);

	bool hasTextureNode;
	bool useBlendMap = data.inputValue(aUseBlendMap).asBool();
	float blendMapMultiplier = data.inputValue(aBlendMapMultiplier).asFloat();

	if (blendMapMultiplier<=0.0) {
		useBlendMap = false;
	}

	if (useBlendMap) {
		hasTextureNode = MDynamicsUtil::hasValidDynamics2dTexture(thisMObject(), aBlendMap);
	}

	float env = data.inputValue(envelope).asFloat();
    MPoint point;
	float2 uvPoint;
    float w, lum;

    for ( ; !itGeo.isDone(); itGeo.next() )
    {
		lum = 1.0;

		if (useBlendMap) {
			if (!blendMapClean) {
				fnMesh.getUVAtPoint(blendPoints[itGeo.index()], uvPoint);

				if (hasTextureNode) {
					uCoords[0] = uvPoint[0];
					vCoords[0] = uvPoint[1];
					MDynamicsUtil::evalDynamics2dTexture(thisMObject(), aBlendMap, uCoords, vCoords, &resultColors, &resultAlphas);
					lum = float(resultColors[0][0]);
				}
				lumValues[itGeo.index()] = lum;
			} else {
				lum = lumValues[itGeo.index()];
			}
		}

        point = itGeo.position();
        w = weightValue( data, geomIndex, itGeo.index() );
        point += (blendPoints[itGeo.index()] - point) * env * w * lum * blendMapMultiplier;
        itGeo.setPosition( point );
    }

	return MS::kSuccess;
}
int main(int argc, char *argv[]) {
#ifdef COPP_MACRO_SYS_POSIX
    puts("###################### context coroutine (stack using default allocator[mmap]) ###################");
#elif defined(COPP_MACRO_SYS_WIN)
    puts("###################### context coroutine (stack using default allocator[VirtualAlloc]) ###################");
#else
    puts("###################### context coroutine (stack using default allocator ###################");
#endif
    printf("########## Cmd:");
    for (int i = 0; i < argc; ++i) {
        printf(" %s", argv[i]);
    }
    puts("");

    if (argc > 1) {
        max_task_number = atoi(argv[1]);
    }

    if (argc > 2) {
        switch_count = atoi(argv[2]);
    }

    size_t stack_size = 16 * 1024;
    if (argc > 3) {
        stack_size = atoi(argv[3]) * 1024;
    }

    time_t begin_time = time(NULL);
    clock_t begin_clock = clock();

    // create coroutines
    task_arr.reserve(static_cast<size_t>(max_task_number));
    while (task_arr.size() < static_cast<size_t>(max_task_number)) {
        my_task_t::ptr_t new_task = my_task_t::create(my_task_action, stack_size);
        if (!new_task) {
            fprintf(stderr, "create coroutine task failed, real size is %d.\n", static_cast<int>(task_arr.size()));
            fprintf(stderr, "maybe sysconf [vm.max_map_count] extended.\n");
            max_task_number = static_cast<int>(task_arr.size());
            break;
        }
        task_arr.push_back(new_task);
    }

    time_t end_time = time(NULL);
    clock_t end_clock = clock();
    printf("create %d task, cost time: %d s, clock time: %d ms, avg: %lld ns\n", max_task_number, static_cast<int>(end_time - begin_time),
           CALC_MS_CLOCK(end_clock - begin_clock), CALC_NS_AVG_CLOCK(end_clock - begin_clock, max_task_number));

    begin_time = end_time;
    begin_clock = end_clock;

    // start a task
    for (int i = 0; i < max_task_number; ++i) {
        task_arr[i]->start();
    }

    // yield & resume from runner
    bool continue_flag = true;
    long long real_switch_times = static_cast<long long>(0);

    while (continue_flag) {
        continue_flag = false;
        for (int i = 0; i < max_task_number; ++i) {
            if (false == task_arr[i]->is_completed()) {
                continue_flag = true;
                ++real_switch_times;
                task_arr[i]->resume();
            }
        }
    }

    end_time = time(NULL);
    end_clock = clock();
    printf("switch %d tasks %lld times, cost time: %d s, clock time: %d ms, avg: %lld ns\n", max_task_number, real_switch_times,
           static_cast<int>(end_time - begin_time), CALC_MS_CLOCK(end_clock - begin_clock),
           CALC_NS_AVG_CLOCK(end_clock - begin_clock, real_switch_times));

    begin_time = end_time;
    begin_clock = end_clock;

    task_arr.clear();

    end_time = time(NULL);
    end_clock = clock();
    printf("remove %d tasks, cost time: %d s, clock time: %d ms, avg: %lld ns\n", max_task_number, static_cast<int>(end_time - begin_time),
           CALC_MS_CLOCK(end_clock - begin_clock), CALC_NS_AVG_CLOCK(end_clock - begin_clock, max_task_number));

    return 0;
}
Exemple #9
0
 AggregatorImpl() {
     m_trie.reserve(4096);
 }
Exemple #10
0
void compute_gForce(const double theta, Particle::Vector &ptcl, bool verbose = true, bool dump_morton = false)
{
  using namespace std;

  // Setup timer
  using _time = chrono::system_clock;


  // Build octree
  const int n_bodies = ptcl.size();
  static Octree::Body::Vector octBodies;
  octBodies.clear();
  octBodies.reserve(n_bodies);

  const auto t_build_tree_beg = _time::now();
  if (verbose)
    fprintf(stderr, " -- Build octree -- \n");

  vec3 rmin(+HUGE);
  vec3 rmax(-HUGE);

  for (int i = 0; i < n_bodies; i++)
  {
    octBodies.push_back(Octree::Body(ptcl[i],i));
    rmin = mineach(rmin, ptcl[i].pos);
    rmax = maxeach(rmax, ptcl[i].pos);
  }

  const vec3 centre = (rmax + rmin)*0.5;
  const vec3 vsize  =  rmax - rmin;
  const real  size  = __max(__max(vsize.x, vsize.y), vsize.z);
  real size2 = 1.0;
  while (size2 > size) size2 *= 0.5;
  while (size2 < size) size2 *= 2.0;


  const int n_nodes = n_bodies;
  Octree tree(centre, size2, n_nodes, theta);
  
  for (int i = 0; i < n_bodies; i++)
  {
    tree.insert(octBodies[i]);
  }
  if (verbose)
    fprintf(stderr, "ncell= %d nnode= %d nleaf= %d n_nodes= %d  depth= %d np= %d\n",
        tree.get_ncell(), tree.get_nnode(), tree.get_nleaf(), n_nodes, tree.get_depth(), tree.get_np());
  const auto t_build_tree_end = _time::now();

  const auto t_boundaries_beg = _time::now();
  tree.computeBoundaries();
  if (verbose)
  {
    const boundary root_innerBnd = tree.root_innerBoundary();
    fprintf(stderr, " rootBnd_inner= %g %g %g  size= %g %g %g \n",
        root_innerBnd.center().x,
        root_innerBnd.center().y,
        root_innerBnd.center().z,
        root_innerBnd.hlen().x,
        root_innerBnd.hlen().y,
        root_innerBnd.hlen().z);
    const boundary root_outerBnd = tree.root_outerBoundary();
    fprintf(stderr, " rootBnd_outer= %g %g %g  size= %g %g %g \n",
        root_outerBnd.center().x,
        root_outerBnd.center().y,
        root_outerBnd.center().z,
        root_outerBnd.hlen().x,
        root_outerBnd.hlen().y,
        root_outerBnd.hlen().z);
    fprintf(stderr, "rootCentre:= %g %g %g  rootSize= %g \n",
        tree.get_rootCentre().x,
        tree.get_rootCentre().y,
        tree.get_rootCentre().z,
        tree.get_rootSize());
  }
  const auto t_boundaries_end = _time::now();
  
  const auto t_sanity_check_beg = _time::now();
  assert(tree.sanity_check() == n_bodies);
  const auto t_sanity_check_end = _time::now();

  const auto t_build_leaf_list_beg = _time::now();
  tree.buildLeafList();
  const auto t_build_leaf_list_end = _time::now();
 

  const auto t_build_group_list_beg = _time::now();
  static octGroup::Vector groupList;
  groupList.clear();
  groupList.reserve(tree.nLeaf());
  tree.buildGroupList</* SORT */ 0 ? true : false>(groupList);
  const int ngroup = groupList.size();
  const auto t_build_group_list_end = _time::now();


  if (verbose)
    fprintf(stderr, " Computing multipole \n");
  const auto t_compute_multipole_beg = _time::now();
  const Octree::dMultipole rootM = tree.computeMultipole(ptcl);
  const auto t_compute_multipole_end = _time::now();
  if (verbose)
  {
    fprintf(stderr,  " Mass= %g \n", rootM.monopole().mass());
    const vec3 mpos = rootM.monopole().mpos();
    fprintf(stderr, " Monopole= %g %g %g  \n", mpos.x, mpos.y, mpos.z);
    fprintf(stderr, " Quadrupole: xx= %g yy= %g zz= %g trace= %g  xy= %g xz= %g zz= %g \n",
        rootM.quadrupole().xx(),
        rootM.quadrupole().yy(),
        rootM.quadrupole().zz(),
        rootM.quadrupole().trace(),
        rootM.quadrupole().xy(),
        rootM.quadrupole().xz(),
        rootM.quadrupole().yz());
  }
    
  if (verbose)
    fprintf(stderr, " Computing gForce \n");
  const auto t_compute_gforce_beg = _time::now();
  {
    real   gpot = 0.0;
    double mtot = 0.0;
    double fx = 0, fy = 0, fz = 0;
    unsigned long long npc = 0, npp = 0;
#ifdef _OPENMP
#pragma omp parallel for reduction(+:mtot, gpot, fx, fy, fz, npc, npp)
#endif
    for (int i = 0; i < ngroup; i++)
    {
      const octGroup &group = groupList[i];
      float4 force[NGROUP] __attribute__ ((aligned(64)));

      const std::pair<int, int> ninter = tree.gForce(group, force);
      npp += ninter.first;
      npc += ninter.second;

      for (int j = 0; j < group.nb(); j++)
      {
        const int idx = group[j].idx();
        const Particle &p = ptcl[idx];
        mtot += p.mass;
        fx += p.mass * force[j].x();
        fy += p.mass * force[j].y();
        fz += p.mass * force[j].z();
        gpot += 0.5*p.mass*force[j].w();
      }
    }
    assert(mtot > 0.0);
    if (verbose)
    {
      fprintf(stderr , "<Ng>= %g\n", (double)n_bodies/ngroup);
      fprintf(stderr, " Npp= %g  Npc= %g\n",
          (double)npp/n_bodies, (double)npc/n_bodies);
      fprintf(stderr, " mtot= %g  ftot= %g %g %g  gpot= %g\n",
          mtot, fx/mtot, fy/mtot, fz/mtot, gpot/mtot);
    }
  }
  const auto t_compute_gforce_end = _time::now();

  const auto t_reorder_beg = _time::now();
  {
    if (verbose)
      fprintf(stderr, " --  Morton reorder -- \n");
    static std::vector<int> morton_list;
    morton_list.reserve(n_bodies);
    tree.tree_dump<true>(morton_list);
    if (verbose)
      fprintf(stderr, "morton_list.size()= %d  n_bodies= %d\n",
          (int)morton_list.size(), n_bodies);
    for (std::vector<int>::iterator it = morton_list.begin(); it != morton_list.end(); it++)
      assert(*it < n_bodies);
    assert((int)morton_list.size() == n_bodies);
  
    if (verbose)
      fprintf(stderr, " -- Update order -- \n");

    static Particle::Vector sortedPtcl;
    sortedPtcl.clear();
    sortedPtcl.reserve(n_bodies);
    for (std::vector<int>::iterator it = morton_list.begin(); it != morton_list.end(); it++)
    {
      assert(*it < n_bodies);
      sortedPtcl.push_back(ptcl[octBodies[*it].idx()]);
    }
    swap(sortedPtcl,ptcl);
  }
  const auto t_reorder_end = _time::now();


  if (verbose)
  {
    using _time_type = decltype(_time::now());
    auto duration = [](const _time_type& t0, const _time_type& t1)
    {
      return chrono::duration_cast<chrono::duration<double>>(t1-t0).count();
    };
    fprintf(stderr, " Timing info: \n");
    fprintf(stderr, " -------------\n");
    fprintf(stderr, "   Tree:     %g sec \n", duration(t_build_tree_beg, t_build_tree_end));
    fprintf(stderr, "   Boundary: %g sec \n", duration(t_boundaries_beg, t_boundaries_end));
    fprintf(stderr, "   Sanity:   %g sec \n", duration(t_sanity_check_beg, t_sanity_check_end));
    fprintf(stderr, "   LeafList: %g sec \n", duration(t_build_leaf_list_beg, t_build_leaf_list_end));
    fprintf(stderr, "   GroupLst: %g sec \n", duration(t_build_group_list_beg, t_build_group_list_end));
    fprintf(stderr, "   MultiP:   %g sec \n", duration(t_compute_multipole_beg, t_compute_multipole_end));
    fprintf(stderr, "   gForce:   %g sec \n", duration(t_compute_gforce_beg, t_compute_gforce_end));
    fprintf(stderr, "   Reorder:  %g sec \n", duration(t_reorder_beg, t_reorder_end));
  }

}
 Cell() { entries.reserve(16); }
    void init_exact_species()
    {
      _H2_species_id = 0;
      _N2_species_id = 47;
      _HCNO_species_id = 43;

      _species_exact.reserve(53);
      _species_exact.push_back("H2");
      _species_exact.push_back("H");
      _species_exact.push_back("O");
      _species_exact.push_back("O2");
      _species_exact.push_back("OH");
      _species_exact.push_back("H2O");
      _species_exact.push_back("HO2");
      _species_exact.push_back("H2O2");
      _species_exact.push_back("C");
      _species_exact.push_back("CH");
      _species_exact.push_back("CH2");
      _species_exact.push_back("CH2(S)");
      _species_exact.push_back("CH3");
      _species_exact.push_back("CH4");
      _species_exact.push_back("CO");
      _species_exact.push_back("CO2");
      _species_exact.push_back("HCO");
      _species_exact.push_back("CH2O");
      _species_exact.push_back("CH2OH");
      _species_exact.push_back("CH3O");
      _species_exact.push_back("CH3OH");
      _species_exact.push_back("C2H");
      _species_exact.push_back("C2H2");
      _species_exact.push_back("C2H3");
      _species_exact.push_back("C2H4");
      _species_exact.push_back("C2H5");
      _species_exact.push_back("C2H6");
      _species_exact.push_back("HCCO");
      _species_exact.push_back("CH2CO");
      _species_exact.push_back("HCCOH");
      _species_exact.push_back("N");
      _species_exact.push_back("NH");
      _species_exact.push_back("NH2");
      _species_exact.push_back("NH3");
      _species_exact.push_back("NNH");
      _species_exact.push_back("NO");
      _species_exact.push_back("NO2");
      _species_exact.push_back("N2O");
      _species_exact.push_back("HNO");
      _species_exact.push_back("CN");
      _species_exact.push_back("HCN");
      _species_exact.push_back("H2CN");
      _species_exact.push_back("HCNN");
      _species_exact.push_back("HCNO");
      _species_exact.push_back("HOCN");
      _species_exact.push_back("HNCO");
      _species_exact.push_back("NCO");
      _species_exact.push_back("N2");
      _species_exact.push_back("AR");
      _species_exact.push_back("C3H7");
      _species_exact.push_back("C3H8");
      _species_exact.push_back("CH2CHO");
      _species_exact.push_back("CH3CHO");
    }
 void add( const entry& p )
 {
     if( points.size() == points.capacity() ) { points.reserve( 2048 ); } // quick and dirty
     points.push_back( p );
 }
Exemple #14
0
template <typename PointT> void
pcl::MinCutSegmentation<PointT>::extract (std::vector <pcl::PointIndices>& clusters)
{
  clusters.clear ();

  bool segmentation_is_possible = initCompute ();
  if ( !segmentation_is_possible )
  {
    deinitCompute ();
    return;
  }

  if ( graph_is_valid_ && unary_potentials_are_valid_ && binary_potentials_are_valid_ )
  {
    clusters.reserve (clusters_.size ());
    std::copy (clusters_.begin (), clusters_.end (), std::back_inserter (clusters));
    deinitCompute ();
    return;
  }

  clusters_.clear ();
  bool success = true;

  if ( !graph_is_valid_ )
  {
    success = buildGraph ();
    if (success == false)
    {
      deinitCompute ();
      return;
    }
    graph_is_valid_ = true;
    unary_potentials_are_valid_ = true;
    binary_potentials_are_valid_ = true;
  }

  if ( !unary_potentials_are_valid_ )
  {
    success = recalculateUnaryPotentials ();
    if (success == false)
    {
      deinitCompute ();
      return;
    }
    unary_potentials_are_valid_ = true;
  }

  if ( !binary_potentials_are_valid_ )
  {
    success = recalculateBinaryPotentials ();
    if (success == false)
    {
      deinitCompute ();
      return;
    }
    binary_potentials_are_valid_ = true;
  }

  //IndexMap index_map = boost::get (boost::vertex_index, *graph_);
  ResidualCapacityMap residual_capacity = boost::get (boost::edge_residual_capacity, *graph_);

  max_flow_ = boost::boykov_kolmogorov_max_flow (*graph_, source_, sink_);

  assembleLabels (residual_capacity);

  deinitCompute ();
}
  void CompleteLinkage::operator()(DistanceMatrix<float> & original_distance, std::vector<BinaryTreeNode> & cluster_tree, const float threshold /*=1*/) const
  {
    // attention: clustering process is done by clustering the indices
    // pointing to elements in inputvector and distances in inputmatrix

    // input MUST have >= 2 elements!
    if (original_distance.dimensionsize() < 2)
    {
      throw ClusterFunctor::InsufficientInput(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Distance matrix to start from only contains one element");
    }

    std::vector<std::set<Size> > clusters(original_distance.dimensionsize());
    for (Size i = 0; i < original_distance.dimensionsize(); ++i)
    {
      clusters[i].insert(i);
    }

    cluster_tree.clear();
    cluster_tree.reserve(original_distance.dimensionsize() - 1);

    // Initial minimum-distance pair
    original_distance.updateMinElement();
    std::pair<Size, Size> min = original_distance.getMinElementCoordinates();

    Size overall_cluster_steps(original_distance.dimensionsize());
    startProgress(0, original_distance.dimensionsize(), "clustering data");

    while (original_distance(min.first, min.second) < threshold)
    {
      //grow the tree
      cluster_tree.push_back(BinaryTreeNode(*(clusters[min.second].begin()), *(clusters[min.first].begin()), original_distance(min.first, min.second)));
      if (cluster_tree.back().left_child > cluster_tree.back().right_child)
      {
        std::swap(cluster_tree.back().left_child, cluster_tree.back().right_child);
      }

      if (original_distance.dimensionsize() > 2)
      {
        //pick minimum-distance pair i,j and merge them

        //pushback elements of second to first (and then erase second)
        clusters[min.second].insert(clusters[min.first].begin(), clusters[min.first].end());
        // erase first one
        clusters.erase(clusters.begin() + min.first);

        //update original_distance matrix
        //complete linkage: new distance between clusters is the minimum distance between elements of each cluster
        //lance-williams update for d((i,j),k): 0.5* d(i,k) + 0.5* d(j,k) + 0.5* |d(i,k)-d(j,k)|
        for (Size k = 0; k < min.second; ++k)
        {
          float dik = original_distance.getValue(min.first, k);
          float djk = original_distance.getValue(min.second, k);
          original_distance.setValueQuick(min.second, k, (0.5f * dik + 0.5f * djk + 0.5f * std::fabs(dik - djk)));
        }
        for (Size k = min.second + 1; k < original_distance.dimensionsize(); ++k)
        {
          float dik = original_distance.getValue(min.first, k);
          float djk = original_distance.getValue(min.second, k);
          original_distance.setValueQuick(k, min.second, (0.5f * dik + 0.5f * djk + 0.5f * std::fabs(dik - djk)));
        }

        //reduce
        original_distance.reduce(min.first);

        //update minimum-distance pair
        original_distance.updateMinElement();

        //get new min-pair
        min = original_distance.getMinElementCoordinates();
      }
      else
      {
        break;
      }
      setProgress(overall_cluster_steps - original_distance.dimensionsize());

      //repeat until only two cluster remains or threshold exceeded, last step skips matrix operations
    }
    //fill tree with dummy nodes
    Size sad(*clusters.front().begin());
    for (Size i = 1; i < clusters.size() && (cluster_tree.size() < cluster_tree.capacity()); ++i)
    {
      cluster_tree.push_back(BinaryTreeNode(sad, *clusters[i].begin(), -1.0));
    }
    //~ while(cluster_tree.size() < cluster_tree.capacity())
    //~ {
    //~ cluster_tree.push_back(BinaryTreeNode(0,1,-1.0));
    //~ }

    endProgress();
  }
Exemple #16
0
 void create_palette(std::vector<rgb> & palette)
 {
     reduce();
     palette.reserve(colors_);
     create_palette(palette, root_);
 }
Exemple #17
0
    void SimulatorFullyImplicitBlackoilPolymer<GridT>::
    computeRepRadiusPerfLength(const Opm::EclipseState&        eclipseState,
                               const size_t                    timeStep,
                               const GridT&                    grid,
                               std::vector<double>&            wells_rep_radius,
                               std::vector<double>&            wells_perf_length,
                               std::vector<double>&            wells_bore_diameter)
    {

        // TODO, the function does not work for parallel running
        // to be fixed later.
        int number_of_cells = Opm::UgGridHelpers::numCells(grid);
        const int* global_cell = Opm::UgGridHelpers::globalCell(grid);
        const int* cart_dims = Opm::UgGridHelpers::cartDims(grid);
        auto cell_to_faces = Opm::UgGridHelpers::cell2Faces(grid);
        auto begin_face_centroids = Opm::UgGridHelpers::beginFaceCentroids(grid);

        if (eclipseState.getSchedule().numWells() == 0) {
            OPM_MESSAGE("No wells specified in Schedule section, "
                        "initializing no wells");
            return;
        }

        const size_t n_perf = wells_rep_radius.size();

        wells_rep_radius.clear();
        wells_perf_length.clear();
        wells_bore_diameter.clear();

        wells_rep_radius.reserve(n_perf);
        wells_perf_length.reserve(n_perf);
        wells_bore_diameter.reserve(n_perf);

        std::map<int,int> cartesian_to_compressed;

        setupCompressedToCartesian(global_cell, number_of_cells,
                                   cartesian_to_compressed);

        const auto& schedule = eclipseState.getSchedule();
        auto wells           = schedule.getWells(timeStep);

        int well_index = 0;

        for (auto wellIter= wells.begin(); wellIter != wells.end(); ++wellIter) {
             const auto* well = (*wellIter);

             if (well->getStatus(timeStep) == WellCommon::SHUT) {
                 continue;
             }
             {   // COMPDAT handling
                 const auto& completionSet = well->getCompletions(timeStep);
                 for (size_t c=0; c<completionSet.size(); c++) {
                     const auto& completion = completionSet.get(c);
                     if (completion.getState() == WellCompletion::OPEN) {
                         int i = completion.getI();
                         int j = completion.getJ();
                         int k = completion.getK();

                         const int* cpgdim = cart_dims;
                         int cart_grid_indx = i + cpgdim[0]*(j + cpgdim[1]*k);
                         std::map<int, int>::const_iterator cgit = cartesian_to_compressed.find(cart_grid_indx);
                         if (cgit == cartesian_to_compressed.end()) {
                             OPM_THROW(std::runtime_error, "Cell with i,j,k indices " << i << ' ' << j << ' '
                                       << k << " not found in grid (well = " << well->name() << ')');
                         }
                         int cell = cgit->second;

                         {
                             double radius = 0.5*completion.getDiameter();
                             if (radius <= 0.0) {
                                 radius = 0.5*unit::feet;
                                 OPM_MESSAGE("**** Warning: Well bore internal radius set to " << radius);
                             }

                             const std::array<double, 3> cubical =
                             WellsManagerDetail::getCubeDim<3>(cell_to_faces, begin_face_centroids, cell);

                             WellCompletion::DirectionEnum direction = completion.getDirection();

                             double re; // area equivalent radius of the grid block
                             double perf_length; // the length of the well perforation

                             switch (direction) {
                                 case Opm::WellCompletion::DirectionEnum::X:
                                     re = std::sqrt(cubical[1] * cubical[2] / M_PI);
                                     perf_length = cubical[0];
                                     break;
                                 case Opm::WellCompletion::DirectionEnum::Y:
                                     re = std::sqrt(cubical[0] * cubical[2] / M_PI);
                                     perf_length = cubical[1];
                                     break;
                                 case Opm::WellCompletion::DirectionEnum::Z:
                                     re = std::sqrt(cubical[0] * cubical[1] / M_PI);
                                     perf_length = cubical[2];
                                     break;
                                 default:
                                     OPM_THROW(std::runtime_error, " Dirtecion of well is not supported ");
                             }

                             double repR = std::sqrt(re * radius);
                             wells_rep_radius.push_back(repR);
                             wells_perf_length.push_back(perf_length);
                             wells_bore_diameter.push_back(2. * radius);
                         }
                     } else {
                         if (completion.getState() != WellCompletion::SHUT) {
                             OPM_THROW(std::runtime_error, "Completion state: " << WellCompletion::StateEnum2String( completion.getState() ) << " not handled");
                         }
                     }

                 }
            }
            well_index++;
        }
    }
void GenerateSphereGeometry(IRenderDevice *pDevice,
                            const float fEarthRadius,
                            int iGridDimension, 
                            const int iNumRings,
                            class ElevationDataSource *pDataSource,
                            float fSamplingStep,
                            float fSampleScale,
                            std::vector<HemisphereVertex> &VB,
                            std::vector<Uint32> &StitchIB,
                            std::vector<RingSectorMesh> &SphereMeshes)
{
    if( (iGridDimension - 1) % 4 != 0 )
    {
        VERIFY_EXPR(false);
        iGridDimension = RenderingParams().m_iRingDimension;
    }
    const int iGridMidst = (iGridDimension-1)/2;
    const int iGridQuart = (iGridDimension-1)/4;

    const int iLargestGridScale = iGridDimension << (iNumRings-1);
    
    RingMeshBuilder RingMeshBuilder(pDevice, VB, iGridDimension, SphereMeshes);

    int iStartRing = 0;
    VB.reserve( (iNumRings-iStartRing) * iGridDimension * iGridDimension );
    for(int iRing = iStartRing; iRing < iNumRings; ++iRing)
    {
        int iCurrGridStart = (int)VB.size();
        VB.resize(VB.size() + iGridDimension * iGridDimension);
        float fGridScale = 1.f / (float)(1<<(iNumRings-1 - iRing));
        // Fill vertex buffer
        for(int iRow = 0; iRow < iGridDimension; ++iRow)
            for(int iCol = 0; iCol < iGridDimension; ++iCol)
            {
                auto &CurrVert = VB[iCurrGridStart + iCol + iRow*iGridDimension];
                auto &f3Pos = CurrVert.f3WorldPos;
                f3Pos.x = static_cast<float>(iCol) / static_cast<float>(iGridDimension-1);
                f3Pos.z = static_cast<float>(iRow) / static_cast<float>(iGridDimension-1);
                f3Pos.x = f3Pos.x*2 - 1;
                f3Pos.z = f3Pos.z*2 - 1;
                f3Pos.y = 0;
                float fDirectionScale = 1;
                if( f3Pos.x != 0 || f3Pos.z != 0 )
                {
                    float fDX = fabs(f3Pos.x);
                    float fDZ = fabs(f3Pos.z);
                    float fMaxD = std::max(fDX, fDZ);
                    float fMinD = std::min(fDX, fDZ);
                    float fTan = fMinD/fMaxD;
                    fDirectionScale = 1 / sqrt(1 + fTan*fTan);
                }
            
                f3Pos.x *= fDirectionScale*fGridScale;
                f3Pos.z *= fDirectionScale*fGridScale;
                f3Pos.y = sqrt( std::max(0.f, 1.f - (f3Pos.x*f3Pos.x + f3Pos.z*f3Pos.z)) );

                f3Pos.x *= fEarthRadius;
                f3Pos.z *= fEarthRadius;
                f3Pos.y *= fEarthRadius;

                ComputeVertexHeight(CurrVert, pDataSource, fSamplingStep, fSampleScale);
                f3Pos.y -= fEarthRadius;
            }

        // Align vertices on the outer boundary
        if( iRing < iNumRings-1 )
        {
            for(int i=1; i < iGridDimension-1; i+=2)
            {
                // Top & bottom boundaries
                for(int iRow=0; iRow < iGridDimension; iRow += iGridDimension-1)
                {
                    const auto &V0 = VB[iCurrGridStart + i - 1 + iRow*iGridDimension].f3WorldPos;
                          auto &V1 = VB[iCurrGridStart + i + 0 + iRow*iGridDimension].f3WorldPos;
                    const auto &V2 = VB[iCurrGridStart + i + 1 + iRow*iGridDimension].f3WorldPos;
                    V1 = (V0+V2)/2.f;
                }

                // Left & right boundaries
                for(int iCol=0; iCol < iGridDimension; iCol += iGridDimension-1)
                {
                    const auto &V0 = VB[iCurrGridStart + iCol + (i - 1)*iGridDimension].f3WorldPos;
                          auto &V1 = VB[iCurrGridStart + iCol + (i + 0)*iGridDimension].f3WorldPos;
                    const auto &V2 = VB[iCurrGridStart + iCol + (i + 1)*iGridDimension].f3WorldPos;
                    V1 = (V0+V2)/2.f;
                }
            }


            // Add triangles stitching this ring with the next one
            int iNextGridStart = (int)VB.size();
            VERIFY_EXPR( iNextGridStart == iCurrGridStart + iGridDimension*iGridDimension);

            // Bottom boundary
            for(int iCol=0; iCol < iGridDimension-1; iCol += 2)
            {
                StitchIB.push_back(iNextGridStart + (iGridQuart + iCol/2) + iGridQuart * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + (iCol+1) + 0 * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + (iCol+0) + 0 * iGridDimension); 

                StitchIB.push_back(iNextGridStart + (iGridQuart + iCol/2) + iGridQuart * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + (iCol+2) + 0 * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + (iCol+1) + 0 * iGridDimension); 

                StitchIB.push_back(iNextGridStart + (iGridQuart + iCol/2)   + iGridQuart * iGridDimension); 
                StitchIB.push_back(iNextGridStart + (iGridQuart + iCol/2+1) + iGridQuart * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + (iCol+2) + 0 * iGridDimension); 
            }

            // Top boundary
            for(int iCol=0; iCol < iGridDimension-1; iCol += 2)
            {
                StitchIB.push_back(iCurrGridStart + (iCol+0) + (iGridDimension-1) * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + (iCol+1) + (iGridDimension-1) * iGridDimension); 
                StitchIB.push_back(iNextGridStart + (iGridQuart + iCol/2) + iGridQuart* 3 * iGridDimension); 

                StitchIB.push_back(iCurrGridStart + (iCol+1) + (iGridDimension-1) * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + (iCol+2) + (iGridDimension-1) * iGridDimension); 
                StitchIB.push_back(iNextGridStart + (iGridQuart + iCol/2) + iGridQuart* 3 * iGridDimension); 

                StitchIB.push_back(iCurrGridStart + (iCol+2) + (iGridDimension-1) * iGridDimension); 
                StitchIB.push_back(iNextGridStart + (iGridQuart + iCol/2 + 1) + iGridQuart* 3 * iGridDimension); 
                StitchIB.push_back(iNextGridStart + (iGridQuart + iCol/2)     + iGridQuart* 3 * iGridDimension); 
            }

            // Left boundary
            for(int iRow=0; iRow < iGridDimension-1; iRow += 2)
            {
                StitchIB.push_back(iNextGridStart + iGridQuart + (iGridQuart+ iRow/2) * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + 0 + (iRow+0) * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + 0 + (iRow+1) * iGridDimension); 

                StitchIB.push_back(iNextGridStart + iGridQuart + (iGridQuart+ iRow/2) * iGridDimension);  
                StitchIB.push_back(iCurrGridStart + 0 + (iRow+1) * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + 0 + (iRow+2) * iGridDimension); 

                StitchIB.push_back(iNextGridStart + iGridQuart + (iGridQuart + iRow/2 + 1) * iGridDimension); 
                StitchIB.push_back(iNextGridStart + iGridQuart + (iGridQuart + iRow/2)     * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + 0 + (iRow+2) * iGridDimension); 
            }

            // Right boundary
            for(int iRow=0; iRow < iGridDimension-1; iRow += 2)
            {
                StitchIB.push_back(iCurrGridStart + (iGridDimension-1) + (iRow+1) * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + (iGridDimension-1) + (iRow+0) * iGridDimension); 
                StitchIB.push_back(iNextGridStart + iGridQuart*3 + (iGridQuart+ iRow/2) * iGridDimension); 

                StitchIB.push_back(iCurrGridStart + (iGridDimension-1) + (iRow+2) * iGridDimension); 
                StitchIB.push_back(iCurrGridStart + (iGridDimension-1) + (iRow+1) * iGridDimension); 
                StitchIB.push_back(iNextGridStart + iGridQuart*3 + (iGridQuart+ iRow/2) * iGridDimension); 

                StitchIB.push_back(iCurrGridStart + (iGridDimension-1) + (iRow+2) * iGridDimension); 
                StitchIB.push_back(iNextGridStart + iGridQuart*3 + (iGridQuart+ iRow/2)     * iGridDimension); 
                StitchIB.push_back(iNextGridStart + iGridQuart*3 + (iGridQuart+ iRow/2 + 1) * iGridDimension); 
            }
        }


        // Generate indices for the current ring
        if( iRing == 0 )
        {
            RingMeshBuilder.CreateMesh( iCurrGridStart, 0,                   0, iGridMidst+1, iGridMidst+1, QUAD_TRIANG_TYPE_00_TO_11);
            RingMeshBuilder.CreateMesh( iCurrGridStart, iGridMidst,          0, iGridMidst+1, iGridMidst+1, QUAD_TRIANG_TYPE_01_TO_10);
            RingMeshBuilder.CreateMesh( iCurrGridStart, 0,          iGridMidst, iGridMidst+1, iGridMidst+1, QUAD_TRIANG_TYPE_01_TO_10);
            RingMeshBuilder.CreateMesh( iCurrGridStart, iGridMidst, iGridMidst, iGridMidst+1, iGridMidst+1, QUAD_TRIANG_TYPE_00_TO_11);
        }
        else
        {
            RingMeshBuilder.CreateMesh( iCurrGridStart,            0,            0,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_00_TO_11);
            RingMeshBuilder.CreateMesh( iCurrGridStart,   iGridQuart,            0,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_00_TO_11);

            RingMeshBuilder.CreateMesh( iCurrGridStart,   iGridMidst,            0,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_01_TO_10);
            RingMeshBuilder.CreateMesh( iCurrGridStart, iGridQuart*3,            0,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_01_TO_10);
                                        
            RingMeshBuilder.CreateMesh( iCurrGridStart,            0,   iGridQuart,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_00_TO_11);
            RingMeshBuilder.CreateMesh( iCurrGridStart,            0,   iGridMidst,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_01_TO_10);
                                        
            RingMeshBuilder.CreateMesh( iCurrGridStart, iGridQuart*3,   iGridQuart,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_01_TO_10);
            RingMeshBuilder.CreateMesh( iCurrGridStart, iGridQuart*3,   iGridMidst,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_00_TO_11);

            RingMeshBuilder.CreateMesh( iCurrGridStart,            0, iGridQuart*3,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_01_TO_10);
            RingMeshBuilder.CreateMesh( iCurrGridStart,   iGridQuart, iGridQuart*3,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_01_TO_10);

            RingMeshBuilder.CreateMesh( iCurrGridStart,   iGridMidst, iGridQuart*3,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_00_TO_11);
            RingMeshBuilder.CreateMesh( iCurrGridStart, iGridQuart*3, iGridQuart*3,   iGridQuart+1, iGridQuart+1, QUAD_TRIANG_TYPE_00_TO_11);
        }
    }
    
    // We do not need per-vertex normals as we use normal map to shade terrain
    // Sphere tangent vertex are computed in the shader
#if 0
    // Compute normals
    const float3 *pV0 = nullptr;
    const float3 *pV1 = &VB[ IB[0] ].f3WorldPos;
    const float3 *pV2 = &VB[ IB[1] ].f3WorldPos;
    float fSign = +1;
    for(Uint32 Ind=2; Ind < m_uiIndicesInIndBuff; ++Ind)
    {
        fSign = -fSign;
        pV0 = pV1;
        pV1 = pV2;
        pV2 =  &VB[ IB[Ind] ].f3WorldPos;
        float3 Rib0 = *pV0 - *pV1;
        float3 Rib1 = *pV1 - *pV2;
        float3 TriN;
        D3DXVec3Cross(&TriN, &Rib0, &Rib1);
        float fLength = D3DXVec3Length(&TriN);
        if( fLength > 0.1 )
        {
            TriN /= fLength*fSign;
            for(int i=-2; i <= 0; ++i)
                VB[ IB[Ind+i] ].f3Normal += TriN;
        }
    }
    for(auto VBIt=VB.begin(); VBIt != VB.end(); ++VBIt)
    {
        float fLength = D3DXVec3Length(&VBIt->f3Normal);
        if( fLength > 1 )
            VBIt->f3Normal /= fLength;
    }

    // Adjust normals on boundaries
    for(int iRing = iStartRing; iRing < iNumRings-1; ++iRing)
    {
        int iCurrGridStart = (iRing-iStartRing) * iGridDimension*iGridDimension;
        int iNextGridStart = (iRing-iStartRing+1) * iGridDimension*iGridDimension;
        for(int i=0; i < iGridDimension; i+=2)
        {
            for(int Bnd=0; Bnd < 2; ++Bnd)
            {
                const int CurrGridOffsets[] = {0, iGridDimension-1};
                const int NextGridPffsets[] = {iGridQuart, iGridQuart*3};
                // Left and right boundaries
                {
                    auto &CurrGridN = VB[iCurrGridStart + CurrGridOffsets[Bnd] + i*iGridDimension].f3Normal;
                    auto &NextGridN = VB[iNextGridStart + NextGridPffsets[Bnd] + (iGridQuart+i/2)*iGridDimension].f3Normal;
                    auto NewN = CurrGridN + NextGridN;
                    D3DXVec3Normalize(&NewN, &NewN);
                    CurrGridN = NextGridN = NewN;
                    if( i > 1 )
                    {
                        auto &PrevCurrGridN = VB[iCurrGridStart + CurrGridOffsets[Bnd] + (i-2)*iGridDimension].f3Normal;
                        auto MiddleN = PrevCurrGridN + NewN;
                        D3DXVec3Normalize( &VB[iCurrGridStart + CurrGridOffsets[Bnd] + (i-1)*iGridDimension].f3Normal, &MiddleN);
                    }
                }

                // Bottom and top boundaries
                {
                    auto &CurrGridN = VB[iCurrGridStart +                i + CurrGridOffsets[Bnd]*iGridDimension].f3Normal;
                    auto &NextGridN = VB[iNextGridStart + (iGridQuart+i/2) + NextGridPffsets[Bnd]*iGridDimension].f3Normal;
                    auto NewN = CurrGridN + NextGridN;
                    D3DXVec3Normalize(&NewN, &NewN);
                    CurrGridN = NextGridN = NewN;
                    if( i > 1 )
                    {
                        auto &PrevCurrGridN = VB[iCurrGridStart + (i-2) + CurrGridOffsets[Bnd]*iGridDimension].f3Normal;
                        auto MiddleN = PrevCurrGridN + NewN;
                        D3DXVec3Normalize( &VB[iCurrGridStart + (i-1) + CurrGridOffsets[Bnd]*iGridDimension].f3Normal, &MiddleN);
                    }
                }
            }
        }
    }
#endif
}
void MetaDirectory::getMetaData(std::vector<CPtr<MetaData> > &resul) const noexcept
{
    resul.resize(0);
    resul.reserve(m_Content.size());
    resul.insert(resul.begin(), m_Content.begin(), m_Content.end());
}
void MONEEWorldObserver::reset()
{
    double tmpReal = 0;
    int tmpInt = 0;
    gProperties.checkAndGetPropertyValue("gMaxCommDist", &tmpReal, true);
    gMaxCommDistSquared = tmpReal * tmpReal;

    gProperties.checkAndGetPropertyValue("gColorChangeTarget", &tmpInt, true);
    _colorChangeTarget = tmpInt;
    gProperties.checkAndGetPropertyValue("gColorChangeIteration", &tmpInt, true);
    _colorChangeIteration = tmpInt;

    gUseDitchSensors = false;

    G_COLOR_WHITE = SDL_MapRGB(gForegroundImage->format, 0xFF, 0xFF, 0xFF);

    // initialize squared distance matrix
    gDistSquared.assign(gAgentCounter * gAgentCounter, .0);
    //for (int i = 0; i != gAgentCounter; i++) (gDistSquared.at(i)).reserve(gAgentCounter);

    // initialize communication network data
    gBoolRadioNetworkArray.assign(gAgentCounter * gAgentCounter, true);
    //for (int i = 0; i != gAgentCounter; i++) (gRadioNetworkArray.at(i)).reserve(gAgentCounter);

    if (gEnergyMode) {
        // Should be declared before agent models are created
        gProperties.checkAndGetPropertyValue("gPuckColors", &gPuckColors, true);

        double w = 10.0; //gBackgroundImage-
        double h = gBackgroundImage->h;

        gPuckMap.resize(w);
        for (int i = 0; i < w; i++) gPuckMap[i].resize(h);

        double xMean, yMean, xSigma, ySigma;

        std::vector<int> puckCount;
        puckCount.reserve(gPuckColors);
        gPuckGens.reserve(gPuckColors);

        gPuckCount = 0;

        for (int puckGenIdx = 0; puckGenIdx < gPuckColors; puckGenIdx++) {
            std::stringstream ss;
            ss << "puckGen[" << puckGenIdx << "]";
            std::string base = ss.str();
            gProperties.checkAndGetPropertyValue(base +".xMean", &tmpReal, true);
            xMean = w * tmpReal;
            gProperties.checkAndGetPropertyValue(base + ".yMean", &tmpReal, true);
            yMean = h * tmpReal;
            gProperties.checkAndGetPropertyValue(base + ".xSigma", &tmpReal, true);
            xSigma = w * tmpReal;
            gProperties.checkAndGetPropertyValue(base + ".ySigma", &tmpReal, true);
            ySigma = h * tmpReal;
            PuckGen newPuckGen(xMean, yMean, xSigma, ySigma, Puck::PALETTE[puckGenIdx]);
            gPuckGens.push_back(newPuckGen);

            gProperties.checkAndGetPropertyValue(base + ".count", &tmpInt, true);
            puckCount.push_back(tmpInt);
            gPuckCount += tmpInt;
        }

        gPucks.reserve(gPuckCount);

        for (Uint8 i = 0; i < puckCount.size(); i++) {
            int pucksToGo = puckCount[i];
            while (pucksToGo > 0) {
                Puck newPuck(&gPuckGens[i]);
                gPucks.push_back(newPuck);
                pucksToGo--;
            }
        }
    }

    gUseDitchSensors = false;

    G_COLOR_WHITE = SDL_MapRGB(gForegroundImage->format, 0xFF, 0xFF, 0xFF);

    if (gEnergyMode) {
        // Randomly place pucks on the field.
        for (int i = 0; i < gPuckCount; i++) {
            gPucks[i].replace(false);
        }
    }


    timer = new Timer();
    timer->start();
}
Exemple #21
0
inline void test() {
    std::cout << "Testing cache misses ..." << std::endl;
    static std::vector<int> source;
    source.reserve(getTestSize());
    for (int i = 0; i < getTestSize(); ++i)
        source.push_back(i);
    
    std::random_shuffle(source.begin(), source.end());

    auto test0 = [&]{
        std::vector<int> vecStd;
        vecStd.reserve(source.size());
        for (int i = 0; i < getTestSize(); ++i)
            vecStd.push_back(source[i]);
        eraseContainer(vecStd);
    };
    
    auto test1 = [&]{
        std::list<int> listStd;
        for (int i = 0; i < getTestSize(); ++i)
            listStd.push_back(source[i]);
        eraseContainer(listStd);
    };
    
    auto test2 = [&]{
        Vector<int> vecCustom;
        vecCustom.reset((int)getTestSize());
        for (int i = 0; i < getTestSize(); ++i)
            vecCustom.add(source[i]);
        eraseContainer(vecCustom);
    };
    
    auto test3 = [&]{
        List<int> listCustom;
        for (int i = 0; i < getTestSize(); ++i)
            listCustom.add(source[i]);

        eraseContainer(listCustom);
    };
    
    //-----
    
    auto numRuns = 256;
    auto l1size = 32 * 1024 / sizeof(float) /*ints*/;
    auto size = l1size * 16;
    std::unique_ptr<float[]> array(new float[size]);
    std::fill(array.get(), array.get() + size, 0.f);
    
    auto test4 = [&] {
        for (int i=0; i<numRuns; i++)
            for (int j=0; j<size; j++)
                array[j] = 2.3*array[j]+1.2;
    };
    
    auto test5 = [&] {
        int blockstart = 0;
        const auto numBuckets = size/l1size;
        for (int b=0; b<numBuckets; b++) {
            for (int i=0; i<numRuns; i++) {
                for (int j=0; j<l1size; j++)
                    array[blockstart+j] = 2.3*array[blockstart+j]+1.2;
            }
            blockstart += l1size;
        }
    };
    
    ADD_BENCHMARK("CacheMiss \t std::vector", test0);
    ADD_BENCHMARK("CacheMiss \t std::list", test1);
    ADD_BENCHMARK("CacheMiss \t custom vector", test2);
    ADD_BENCHMARK("CacheMiss \t custom vector", test3);
    //ADD_BENCHMARK("CacheMiss \t linear add", test4);
    //ADD_BENCHMARK("CacheMiss \t bucket add", test5);

    benchpress::run_benchmarks(benchpress::options());
    
}
Exemple #22
0
// ------------------------------------------------------------------------------------------------
void GetImporterInstanceList(std::vector< BaseImporter* >& out)
{
	// ----------------------------------------------------------------------------
	// Add an instance of each worker class here
	// (register_new_importers_here)
	// ----------------------------------------------------------------------------
	out.reserve(64);
#if (!defined ASSIMP_BUILD_NO_X_IMPORTER)
	out.push_back( new XFileImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_OBJ_IMPORTER)
	out.push_back( new ObjFileImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_3DS_IMPORTER)
	out.push_back( new Discreet3DSImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_MD3_IMPORTER)
	out.push_back( new MD3Importer());
#endif
#if (!defined ASSIMP_BUILD_NO_MD2_IMPORTER)
	out.push_back( new MD2Importer());
#endif
#if (!defined ASSIMP_BUILD_NO_PLY_IMPORTER)
	out.push_back( new PLYImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_MDL_IMPORTER)
	out.push_back( new MDLImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_ASE_IMPORTER)
	out.push_back( new ASEImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_HMP_IMPORTER)
	out.push_back( new HMPImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_SMD_IMPORTER)
	out.push_back( new SMDImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_MDC_IMPORTER)
	out.push_back( new MDCImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_MD5_IMPORTER)
	out.push_back( new MD5Importer());
#endif
#if (!defined ASSIMP_BUILD_NO_STL_IMPORTER)
	out.push_back( new STLImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_LWO_IMPORTER)
	out.push_back( new LWOImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_DXF_IMPORTER)
	out.push_back( new DXFImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_NFF_IMPORTER)
	out.push_back( new NFFImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_RAW_IMPORTER)
	out.push_back( new RAWImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_OFF_IMPORTER)
	out.push_back( new OFFImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_AC_IMPORTER)
	out.push_back( new AC3DImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_BVH_IMPORTER)
	out.push_back( new BVHLoader());
#endif
#if (!defined ASSIMP_BUILD_NO_IRRMESH_IMPORTER)
	out.push_back( new IRRMeshImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_IRR_IMPORTER)
	out.push_back( new IRRImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_Q3D_IMPORTER)
	out.push_back( new Q3DImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_B3D_IMPORTER)
	out.push_back( new B3DImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_COLLADA_IMPORTER)
	out.push_back( new ColladaLoader());
#endif
#if (!defined ASSIMP_BUILD_NO_TERRAGEN_IMPORTER)
	out.push_back( new TerragenImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_CSM_IMPORTER)
	out.push_back( new CSMImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_3D_IMPORTER)
	out.push_back( new UnrealImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_LWS_IMPORTER)
	out.push_back( new LWSImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_OGRE_IMPORTER)
	out.push_back( new Ogre::OgreImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_MS3D_IMPORTER)
	out.push_back( new MS3DImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_COB_IMPORTER)
	out.push_back( new COBImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_BLEND_IMPORTER)
	out.push_back( new BlenderImporter());
#endif
#if (!defined ASSIMP_BUILD_NO_Q3BSP_IMPORTER)
	out.push_back( new Q3BSPFileImporter() );
#endif
#if (!defined ASSIMP_BUILD_NO_NDO_IMPORTER)
	out.push_back( new NDOImporter() );
#endif
#if (!defined ASSIMP_BUILD_NO_IFC_IMPORTER)
	out.push_back( new IFCImporter() );
#endif
#if ( !defined ASSIMP_BUILD_NO_XGL_IMPORTER )
	out.push_back( new XGLImporter() );
#endif
#if ( !defined ASSIMP_BUILD_NO_FBX_IMPORTER )
	out.push_back( new FBXImporter() );
#endif
#if ( !defined ASSIMP_BUILD_NO_ASSBIN_IMPORTER )
	out.push_back( new AssbinImporter() );
#endif
}
Exemple #23
0
bool Punycode::decodePunycode(StringRef InputPunycode,
                              std::vector<uint32_t> &OutCodePoints) {
  OutCodePoints.clear();
  OutCodePoints.reserve(InputPunycode.size());

  // -- Build the decoded string as UTF32 first because we need random access.
  uint32_t n = initial_n;
  int i = 0;
  int bias = initial_bias;
  /// let output = an empty string indexed from 0
  // consume all code points before the last delimiter (if there is one)
  //  and copy them to output,
  size_t lastDelimiter = InputPunycode.find_last_of(delimiter);
  if (lastDelimiter != StringRef::npos) {
    for (char c : InputPunycode.slice(0, lastDelimiter)) {
      // fail on any non-basic code point
      if (static_cast<unsigned char>(c) > 0x7f)
        return true;
      OutCodePoints.push_back(c);
    }
    // if more than zero code points were consumed then consume one more
    //  (which will be the last delimiter)
    InputPunycode =
        InputPunycode.slice(lastDelimiter + 1, InputPunycode.size());
  }
  
  while (!InputPunycode.empty()) {
    int oldi = i;
    int w = 1;
    for (int k = base; ; k += base) {
      // consume a code point, or fail if there was none to consume
      if (InputPunycode.empty())
        return true;
      char codePoint = InputPunycode.front();
      InputPunycode = InputPunycode.slice(1, InputPunycode.size());
      // let digit = the code point's digit-value, fail if it has none
      int digit = digit_index(codePoint);
      if (digit < 0)
        return true;
      
      i = i + digit * w;
      int t = k <= bias ? tmin
            : k >= bias + tmax ? tmax
            : k - bias;
      if (digit < t)
        break;
      w = w * (base - t);
    }
    bias = adapt(i - oldi, OutCodePoints.size() + 1, oldi == 0);
    n = n + i / (OutCodePoints.size() + 1);
    i = i % (OutCodePoints.size() + 1);
    // if n is a basic code point then fail
    if (n < 0x80)
      return true;
    // insert n into output at position i
    OutCodePoints.insert(OutCodePoints.begin() + i, n);
    i++;
  }
  
  return true;
}
unsigned int RangeDetector::computeInterestPoints(const LaserReading& reading, const std::vector<double>& signal, std::vector<InterestPoint*>& point, 
						  std::vector< std::vector<unsigned int> >& indexes, std::vector<unsigned int>& maxRangeMapping) const
{
    point.clear();
    point.reserve(reading.getRho().size());
    const std::vector<Point2D>& worldPoints = reading.getWorldCartesian();
    for(unsigned int i = 0; i < indexes.size(); i++){
		for(unsigned int j = 0; j < indexes[i].size(); j++){
			OrientedPoint2D pose;
			unsigned int pointIndex = maxRangeMapping[indexes[i][j]];
			
			// Reomoving the detection in the background and pushing it to the foreground
			double rangeBefore = (pointIndex > 1)? reading.getRho()[pointIndex - 1] : reading.getMaxRange();
			double rangeAfter = (pointIndex < worldPoints.size() - 1)? reading.getRho()[pointIndex + 1] : reading.getMaxRange();
			double rangeCurrent = reading.getRho()[pointIndex];
			if(rangeBefore < rangeAfter){
				if(rangeBefore < rangeCurrent){
					pointIndex = pointIndex - 1;
				}
			} else if(rangeAfter < rangeCurrent){
				pointIndex = pointIndex + 1;
			}
			
			// Removing max range reading
			if(reading.getRho()[pointIndex] >= reading.getMaxRange()){
				continue;
			}

			pose.x =  (reading.getWorldCartesian()[pointIndex]).x;
			pose.y =  (reading.getWorldCartesian()[pointIndex]).y;
			pose.theta = 0.0;
			
			bool exists = false;
			for(unsigned int k = 0; !exists && k < point.size(); k++){
				exists = exists || (fabs(pose.x - point[k]->getPosition().x) <= 0.2 &&  fabs(pose.y - point[k]->getPosition().y) <= 0.2);
			}
			if(exists) continue;

	    unsigned int first = indexes[i][j] - floor((int)m_filterBank[i].size()/2.0);
	    unsigned int last = indexes[i][j] + floor((int)m_filterBank[i].size()/2.0);
	    std::vector<Point2D> support(last - first + 1);
	    for(unsigned int p = 0; p < support.size(); p++) {
		support[p] = Point2D(worldPoints[maxRangeMapping[p + first]]);
	    }
			
			LineParameters param = computeNormals(support);
			pose.theta = normAngle(param.alpha, - M_PI);

			double maxDistance = -1e20;
			for(unsigned int k = 0; k < support.size(); k++){
				double distance = sqrt((pose.x - support[k].x)*(pose.x - support[k].x) + (pose.y - support[k].y)*(pose.y - support[k].y));
				maxDistance = maxDistance < distance ? distance : maxDistance;
			}
			InterestPoint *interest = new InterestPoint(pose, maxDistance);
	// 	    InterestPoint *interest = new InterestPoint(pose, m_scales[i]);
			interest->setScaleLevel(i);
			interest->setSupport(support);
			point.push_back(interest);
		}
    }
    return point.size();
}
void compositionSpace::createComposition()
{
  //Variables

  /*util*/       int   util2ThirdOfCycleAmount;
  /*util*/       int   utilCCInt;

  //Init

  /*inten*/      float phaseOfIntensitySine=0.;
  /*inten*/      int   intensityAureanProg=0;
  /*inten*/      int   intenHistoryX=0;
  /*inten*/      int   intenHistoryY=0;
  /*counter*/    int   createCompositionUtilCounter=0;//Global index

  /*GlobalParam*/      cyclePhase=0;
  /*GlobalParam*/      addtoSineIWNeedChange.reserve(TOTALVOICEAMOUNT);
  /*GlobalParam*/      totalLength=0;

  for(int i=0;i<TOTALVOICEAMOUNT;i++){
  /*GlobalParam*/      addtoSineIWNeedChange[i] = 0;
  }

  /*GlobalParam*/      loopLimit = 0;

  /*GlobalParam*/      totalVoiceAmount = TOTALVOICEAMOUNT;


  /*GlobalParam*/      globalIntensityX.reserve(2000);
  /*GlobalParam*/      globalIntensityY.reserve(2000);//dummy

  /*GlobalParam*/      compositionInfo.reserve(3);
                       //reserve seq



  //Generation

  cycleAmount=(3+(rand()%4))*2; //amount of cycles
  std::cout << "cycles " << cycleAmount << std::endl;

  //This needs to be initialized after the number of cycles has been decided
  /*GlobalParam*/      compositionInfo[0].reserve(cycleAmount);
                       //[0] is the amount of voices
  /*GlobalParam*/      compositionInfo[1].reserve(cycleAmount);
                       //[1] is the length of the cycle in notes
  /*GlobalParam*/      compositionInfo[2].reserve(cycleAmount);
                       //[2] is the length of the cycle in repetitions

  /*GlobalParam2*/     voiceSeq.reserve(totalVoiceAmount);

  /*util*/ util2ThirdOfCycleAmount=(int)(2*cycleAmount/3);

  for(int i=0;i<cycleAmount;i++){

    compositionInfo[0][i]=std::min((int)(intensityAureanProg/8),3)+1;//voices
    std::cout << "voices " << compositionInfo[0][i] << std::endl;

    /*util*/utilCCInt=rand()%(((intensityAureanProg%3)+2)+2);
    compositionInfo[1][i]=2+utilCCInt;//notes
    /*length*/totalLength+=compositionInfo[1][i];//add notes to total length

    /*util*/utilCCInt=rand()%3;
    compositionInfo[2][i]=2+utilCCInt;//repetitions

    // golden ratio * sine + random

    for(int ii=0;ii<compositionInfo[1][i];ii++){

      //Golden ratio

      //The intensity grows for the first 2/3 parts of the piece and then
      //decreases twice as fast until the end.
      //As the amount of notes per cycle is not allways the same there is
      //still some variation in such a predcitable pattern

      /*util*/utilCCInt=i>util2ThirdOfCycleAmount;
      /*util*/utilCCInt=utilCCInt==1 ?
        intensityAureanProg-2 : intensityAureanProg+1;
      intensityAureanProg=std::min(std::max(utilCCInt,0),40);//clamp

      // sine

      //the frequency of the phase is actually the amount of cycles

      phaseOfIntensitySine=fmod(phaseOfIntensitySine+(1./cycleAmount),1.0);

      //random offset

      //brownian motion limited to a certain area
      //X
      /*util*/utilCCInt=rand()%5;
      /*util*/utilCCInt=intenHistoryX-2+rand()%5;
      intenHistoryX=std::min(std::max(utilCCInt,-20),20);

      //Y
      /*util*/utilCCInt=rand()%5;
      /*util*/utilCCInt=intenHistoryY-2+rand()%5;
      intenHistoryY=std::min(std::max(utilCCInt,-20),20);


      //Absolute Global Intensity
      /*util*/utilCCInt=(int)(intensityAureanProg*3*sin(phaseOfIntensitySine));
      /*util*/utilCCInt=intenHistoryX+utilCCInt;
      /*util*/utilCCInt=std::max(std::min(utilCCInt,30),-30);
      globalIntensityX[createCompositionUtilCounter]=utilCCInt;

      /*util*/utilCCInt=(int)(intensityAureanProg*3*sin(phaseOfIntensitySine));
      /*util*/utilCCInt=intenHistoryY+utilCCInt;
      /*util*/utilCCInt=std::max(std::min(utilCCInt,30),-30);
      globalIntensityY[createCompositionUtilCounter]=utilCCInt;

      /*counter*/createCompositionUtilCounter++;//Global index

    }//end for notes per cycle

  }//end for cycleAmount

  //Fill those voiceSeqs
  for(int i=0;i<totalVoiceAmount;i++){
    voiceSeq[i].setParam(i,1.0+((float)i/2.0));
    voiceSeq[i].fill(totalLength);
  }
}
Exemple #26
0
void stackgetcallstack(duint csp, std::vector<CALLSTACKENTRY> & callstackVector, bool cache)
{
    if(cache)
    {
        SHARED_ACQUIRE(LockCallstackCache);
        auto found = CallstackCache.find(csp);
        if(found != CallstackCache.end())
        {
            callstackVector = found->second;
            return;
        }
        callstackVector.clear();
        return;
    }

    // Gather context data
    CONTEXT context;
    memset(&context, 0, sizeof(CONTEXT));

    context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER;

    if(SuspendThread(hActiveThread) == -1)
        return;

    if(!GetThreadContext(hActiveThread, &context))
        return;

    if(ResumeThread(hActiveThread) == -1)
        return;

    // Set up all frame data
    STACKFRAME64 frame;
    ZeroMemory(&frame, sizeof(STACKFRAME64));

#ifdef _M_IX86
    DWORD machineType = IMAGE_FILE_MACHINE_I386;
    frame.AddrPC.Offset = context.Eip;
    frame.AddrPC.Mode = AddrModeFlat;
    frame.AddrFrame.Offset = context.Ebp;
    frame.AddrFrame.Mode = AddrModeFlat;
    frame.AddrStack.Offset = csp;
    frame.AddrStack.Mode = AddrModeFlat;
#elif _M_X64
    DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
    frame.AddrPC.Offset = context.Rip;
    frame.AddrPC.Mode = AddrModeFlat;
    frame.AddrFrame.Offset = context.Rsp;
    frame.AddrFrame.Mode = AddrModeFlat;
    frame.AddrStack.Offset = csp;
    frame.AddrStack.Mode = AddrModeFlat;
#endif

    const int MaxWalks = 50;
    // Container for each callstack entry (50 pre-allocated entries)
    callstackVector.clear();
    callstackVector.reserve(MaxWalks);

    for(auto i = 0; i < MaxWalks; i++)
    {
        if(!StackWalk64(
                    machineType,
                    fdProcessInfo->hProcess,
                    hActiveThread,
                    &frame,
                    &context,
                    StackReadProcessMemoryProc64,
                    SymFunctionTableAccess64,
                    StackGetModuleBaseProc64,
                    StackTranslateAddressProc64))
        {
            // Maybe it failed, maybe we have finished walking the stack
            break;
        }

        if(frame.AddrPC.Offset != 0)
        {
            // Valid frame
            CALLSTACKENTRY entry;
            memset(&entry, 0, sizeof(CALLSTACKENTRY));

            StackEntryFromFrame(&entry, (duint)frame.AddrFrame.Offset + sizeof(duint), (duint)frame.AddrPC.Offset, (duint)frame.AddrReturn.Offset);
            callstackVector.push_back(entry);
        }
        else
        {
            // Base reached
            break;
        }
    }

    EXCLUSIVE_ACQUIRE(LockCallstackCache);
    if(CallstackCache.size() > MAX_CALLSTACK_CACHE)
        CallstackCache.clear();
    CallstackCache[csp] = callstackVector;
}
Exemple #27
0
/***********************************************************************//**
 * @brief Reserves space for regions in container
 *
 * @param[in] num Number of regions
 *
 * Reserves space for @p num regions in the container.
 ***************************************************************************/
inline
void GSkyRegions::reserve(const int& num)
{
    m_regions.reserve(num);
    return;
}
Exemple #28
0
bool Simulation::assembleBogusFrictionProblem( 
        CollidingGroup& collisionGroup,
        bogus::MecheFrictionProblem& mecheProblem, 
        std::vector<unsigned> &globalIds,
        VecXx& vels, 
        VecXx& impulses,
        VecXu& startDofs, 
        VecXu& nDofs )
{

    unsigned nContacts = collisionGroup.second.size();

    std::vector<unsigned> nndofs;
    unsigned nSubsystems = collisionGroup.first.size(); 
    globalIds.reserve( nSubsystems );

    nndofs.resize( nSubsystems );
    nDofs.resize( nSubsystems );
    startDofs.resize( nSubsystems );

    unsigned dofCount = 0;
    unsigned subCount = 0;
    std::vector<unsigned> dofIndices;

    // Computes the number of DOFs per strand and the total number of contacts
    for( IndicesMap::const_iterator it = collisionGroup.first.begin();
         it != collisionGroup.first.end(); 
         ++it )
    {
        startDofs[ subCount ] = dofCount;
        dofIndices.push_back( dofCount );
        const unsigned sIdx = it->first;
        globalIds.push_back( sIdx );
        nDofs[subCount] = m_steppers[sIdx]->m_futureVelocities.rows();
        nndofs[subCount] = m_steppers[sIdx]->m_futureVelocities.rows();
        nContacts += m_externalContacts[sIdx].size();
        dofCount += m_steppers[sIdx]->m_futureVelocities.rows();
        ++subCount;
    }

    if( nContacts == 0 ){
        return false; // needs to be false to break out of solvecollidinggroup if statement
    }

    // Prepare the steppers
#pragma omp parallel for
    for ( unsigned i = 0; i < globalIds.size(); ++i )
    { // make sure steppers are ready for us to read their info/members... solve if not yet solved, reset where necessary
        m_steppers[ globalIds[i] ]->prepareForExternalSolve();
    }

    std::vector < SymmetricBandMatrixSolver<double, 10>* > MassMat;
    MassMat.resize( nSubsystems );

    VecXx forces( dofCount );

    vels.resize( dofCount );
    impulses.resize( nContacts * 3 );
    impulses.setZero();

    VecXx mu( nContacts );

    std::vector < Eigen::Matrix< double, 3, 3 > > E; E.resize( nContacts );

    VecXx u_frees( nContacts * 3 );
    u_frees.setZero();

    int ObjA[ nContacts ];
    int ObjB[ nContacts ];

    std::vector < SparseRowMatx* > H_0; H_0.resize( nContacts );
    std::vector < SparseRowMatx* > H_1; H_1.resize( nContacts );

    unsigned objectId = 0, collisionId = 0, currDof = 0;

    // Setting up objects and adding external constraints
    for ( IndicesMap::const_iterator it = collisionGroup.first.begin(); it != collisionGroup.first.end(); ++it )
    {
        const unsigned sIdx = it->first;
        ImplicitStepper& stepper = *m_steppers[sIdx];

        JacobianSolver *M = &stepper.linearSolver();
        MassMat[ objectId++ ] = M;

        if( m_params.m_alwaysUseNonLinear )
        {
            forces.segment( currDof, stepper.rhs().size() ) = -stepper.rhs();
            currDof += stepper.rhs().size();
        }
        else
        {
            forces.segment( currDof, stepper.impulse_rhs().size() ) = -stepper.impulse_rhs();
            currDof += stepper.impulse_rhs().size();
        }

        CollidingPairs & externalCollisions = m_externalContacts[sIdx];
        for ( unsigned i = 0; i < externalCollisions.size(); ++i, ++collisionId )
        {
            CollidingPair& c = externalCollisions[i];

            mu[ collisionId ] = c.m_mu;
            E [ collisionId ] = c.m_transformationMatrix;
            // u_frees.segment<3>( ( collisionId ) * 3 ) = c.objects.first.freeVel - c.objects.second.freeVel;
            ObjA[ collisionId ] = (int) it->second;
            ObjB[ collisionId ] = -1;
            H_0 [ collisionId ] = c.objects.first.defGrad;
            H_1 [ collisionId ] = NULL;
        }
    }

    // Setting up RodRod constraints
#pragma omp parallel for
    for ( unsigned i = 0; i < collisionGroup.second.size(); ++i )
    {
        CollidingPair& collision = collisionGroup.second[i];
        const int oId1 = collisionGroup.first.find( collision.objects.first.globalIndex )->second;
        const int oId2 = collisionGroup.first.find( collision.objects.second.globalIndex )->second;

        mu[ collisionId + i ] = collision.m_mu;
        E [ collisionId + i ] = collision.m_transformationMatrix;
        // u_frees.segment<3>( ( collisionId + i ) * 3 ) = collision.objects.first.freeVel - collision.objects.second.freeVel;
        ObjA[ collisionId + i ] = oId1;
        ObjB[ collisionId + i ] = oId2;
        H_0 [ collisionId + i ] = collision.objects.first.defGrad;
        H_1 [ collisionId + i ] = collision.objects.second.defGrad;
    }
    assert( collisionId + collisionGroup.second.size() == nContacts );

    mecheProblem.fromPrimal( 
                    nSubsystems,
                    nndofs,
                    MassMat, 
                    forces,
                    nContacts, 
                    mu, 
                    E, 
                    u_frees, // this is what we want the velocity to be given resting contact, set it to zero?
                    ObjA, 
                    ObjB, 
                    H_0, 
                    H_1,
                    dofIndices );

    return true;
}
Exemple #29
0
void SceneGraph::present(SceneNode *camera)
{
    glAssertError();
    glCullFace(GL_BACK);
    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glPolygonMode(GL_FRONT, GL_FILL);
    glDisable(GL_BLEND);
    glDepthMask(GL_TRUE);
    glAssertError();

    //  setup camera
    CameraInfo ci;
    camera->prepare(ci);
    ci = *camera->as<CameraSceneNode>()->cam_;

    glEnable(GL_LIGHT0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    Vec3 pos(1, 2, 3);
    normalize(pos);
    Matrix m(ci.mmat_);
    m.setTranslation(Vec3(0, 0, 0));
    multiply(m, pos);
    glLightfv(GL_LIGHT0, GL_POSITION, &pos.x);

    Rgba ambLight(0.25f, 0.2f, 0.3f);
    glLightfv(GL_LIGHT0, GL_AMBIENT, &ambLight.r);
    Rgba diffLight(0.75f, 0.75f, 0.6f);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, &diffLight.r);
    Rgba specLight(0.75f, 0.75f, 0.6f);
    glLightfv(GL_LIGHT0, GL_SPECULAR, &diffLight.r);
    Rgba zero(0, 0, 0);
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, &zero.r);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    Vec3 sz(ctx_->size());
    float fy = tanf(ci.fovY / 360.0f * (float)3.1415927f);
    float fx = fy * sz.x / sz.y;
    glFrustum(-fx, fx, -fy, fy, 0.9f, 10000.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glAssertError();

    //  prepare all objects
    for (std::set<SceneNode*>::iterator ptr(scene_.begin()), end(scene_.end());
        ptr != end; ++ptr)
    {
        if ((*ptr) != camera)
        {
            (*ptr)->prepare(ci);
        }
    }

    //  render all objects
    static std::vector<std::pair<float, SceneNode *> > toDraw;
    toDraw.reserve(8000);
    Vec3 camBack(ci.back);

    for (int pno = 0; pno < p_num_passes; ++pno)
    {
        int pass = (1 << pno);
        toDraw.clear();
        for (std::set<SceneNode*>::iterator ptr(scene_.begin()), end(scene_.end());
            ptr != end; ++ptr)
        {
            if (((*ptr)->pass_ & pass) != 0)
            {
                toDraw.push_back(std::pair<float, SceneNode *>(dot((*ptr)->worldPos(), camBack), *ptr));
            }
        }
        if (pass == p_transparent)
        {
            //  transparency is sorted back-to-front
            std::sort(toDraw.begin(), toDraw.end(), CompareFarNear());
        }
        else
        {
            //  everything else is sorted front-to-back, to get early z rejection
            std::sort(toDraw.begin(), toDraw.end(), CompareNearFar());
        }
        for (std::vector<std::pair<float, SceneNode *> >::iterator
            ptr(toDraw.begin()), end(toDraw.end());
            ptr != end;
            ++ptr)
        {
            (*ptr).second->render(ci, pass);
        }
    }

    glAssertError();
}
Exemple #30
0
 bool FillTransformVectorFromPySequence(PyObject* datalist, std::vector<ConstTransformRcPtr> &data)
 {
     data.clear();
     
     if(PyListOrTuple_Check(datalist))
     {
         int sequenceSize = PyListOrTuple_GET_SIZE(datalist);
         data.reserve(sequenceSize);
         
         for(int i=0; i < sequenceSize; i++)
         {
             PyObject* item = PyListOrTuple_GET_ITEM(datalist, i);
             ConstTransformRcPtr val;
             try
             {
                 val = GetConstTransform(item, true);
             }
             catch(...)
             {
                 data.clear();
                 return false;
             }
             
             data.push_back( val );
         }
         return true;
     }
     else
     {
         PyObject *item;
         PyObject *iter = PyObject_GetIter(datalist);
         if (iter == NULL)
         {
             PyErr_Clear();
             return false;
         }
         while((item = PyIter_Next(iter)) != NULL)
         {
             ConstTransformRcPtr val;
             try
             {
                 val = GetConstTransform(item, true);
             }
             catch(...)
             {
                 Py_DECREF(item);
                 Py_DECREF(iter);
                 
                 data.clear();
                 return false;
             }
             
             data.push_back(val);
             Py_DECREF(item);
         }
         
         Py_DECREF(iter);
         if (PyErr_Occurred())
         {
             PyErr_Clear();
             data.clear();
             return false;
         }
         
         return true;
     }
 }