Search Results

Search found 62 results on 3 pages for 'yaw reuben'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • I need help with Widget and PendingIntents

    - by YaW
    Hi, I've asked here a question about Task Killers and widgets stop working (SO Question) but now, I have reports of user that they don't use any Task Killer and the widgets didn't work after a while. I have a Nexus One and I don't have this problem. I don't know if this is a problem of memory or something. Based on the API: A PendingIntent itself is simply a reference to a token maintained by the system describing the original data used to retrieve it. This means that, even if its owning application's process is killed, the PendingIntent itself will remain usable from other processes that have been given it. So, I don't know why widget stop working, if Android doesn't kill the PendingIntent by itself, what's the problem? This is my manifest code: <receiver android:name=".widget.InstantWidget" android:label="@string/app_name"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_provider" /> </receiver> And the widget code: public class InstantWidget extends AppWidgetProvider { public static ArrayList<Integer> alWidgetsId = new ArrayList<Integer>(); private static final String PREFS_NAME = "com.cremagames.instant.InstantWidget"; private static final String PREF_PREFIX_NOM = "nom_"; private static final String PREF_PREFIX_RAW = "raw_"; /** * Esto se llama cuando se crea el widget. Metemos en las preferencias los valores de nombre y raw para tenerlos en proximos reboot. * @param context * @param appWidgetManager * @param appWidgetId * @param nombreSound * @param rawSound */ static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId, String nombreSound, int rawSound){ //Guardamos en las prefs los valores SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit(); prefs.putString(PREF_PREFIX_NOM + appWidgetId, nombreSound); prefs.putInt(PREF_PREFIX_RAW + appWidgetId, rawSound); prefs.commit(); //Actualizamos la interfaz updateWidgetGrafico(context, appWidgetManager, appWidgetId, nombreSound, rawSound); } /** * Actualiza la interfaz gráfica del widget (pone el nombre y crea el intent con el raw) * @param context * @param appWidgetManager * @param appWidgetId * @param nombreSound * @param rawSound */ private static void updateWidgetGrafico(Context context, AppWidgetManager appWidgetManager, int appWidgetId, String nombreSound, int rawSound){ RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget); //Nombre del Button remoteViews.setTextViewText(R.id.tvWidget, nombreSound); //Creamos el PendingIntent para el onclik del boton Intent active = new Intent(context, InstantWidget.class); active.setAction(String.valueOf(appWidgetId)); active.putExtra("sonido", rawSound); PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0); actionPendingIntent.cancel(); actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0); remoteViews.setOnClickPendingIntent(R.id.btWidget, actionPendingIntent); appWidgetManager.updateAppWidget(appWidgetId, remoteViews); } public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); //Esto se usa en la 1.5 para que se borre bien el widget if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) { final int appWidgetId = intent.getExtras().getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) { this.onDeleted(context, new int[] { appWidgetId }); } } else { //Listener de los botones for(int i=0; i<alWidgetsId.size(); i++){ if (intent.getAction().equals(String.valueOf(alWidgetsId.get(i)))) { int sonidoRaw = 0; try { sonidoRaw = intent.getIntExtra("sonido", 0); } catch (NullPointerException e) { } MediaPlayer mp = MediaPlayer.create(context, sonidoRaw); mp.start(); mp.setOnCompletionListener(completionListener); } } super.onReceive(context, intent); } } /** Al borrar el widget, borramos también las preferencias **/ public void onDeleted(Context context, int[] appWidgetIds) { for(int i=0; i<appWidgetIds.length; i++){ //Recogemos las preferencias SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit(); prefs.remove(PREF_PREFIX_NOM + appWidgetIds[i]); prefs.remove(PREF_PREFIX_RAW + appWidgetIds[i]); prefs.commit(); } super.onDeleted(context, appWidgetIds); } /**Este método se llama cada vez que se refresca un widget. En nuestro caso, al crearse y al reboot del telefono. Al crearse lo único que hace es guardar el id en el arrayList Al reboot, vienen varios ID así que los recorremos y guardamos todos y también recuperamos de las preferencias el nombre y el sonido*/ public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { for(int i=0; i<appWidgetIds.length; i++){ //Metemos en el array los IDs de los widgets alWidgetsId.add(appWidgetIds[i]); //Recogemos las preferencias SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0); String nomSound = prefs.getString(PREF_PREFIX_NOM + appWidgetIds[i], null); int rawSound = prefs.getInt(PREF_PREFIX_RAW + appWidgetIds[i], 0); //Si están creadas, actualizamos la interfaz if(nomSound != null){ updateWidgetGrafico(context, appWidgetManager, appWidgetIds[i], nomSound, rawSound); } } } MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener(){ public void onCompletion(MediaPlayer mp) { if(mp != null){ mp.stop(); mp.release(); mp = null; } } }; } Sorry for the comments in Spanish. I have the possibility to put differents widgets on the desktop, that's why I use the widgetId as the "unique id" for the PendingIntent. Any ideas please? The 70% of the functionality of my app is the widgets, and it isn't working for some users :( Thanks in advance and sorry for my English.

    Read the article

  • Set a OGG in raw folder as Ringtone/Notification?

    - by YaW
    Hi, I have some ogg audios in my raw folder and I'm trying to set one of them as a Ringtone (or Notification, Alarm... whatever). I've been looking at the source code of RingDroid and I can see how is this done using the ContentValues and MediaStore, but in all the examples I've seen, the audio files is in the SDCard. Is it possible to set the ringtone directly from the raw folder? If not, how can I make a copy of the raw file to a folder in the SD? Thanks in advance.

    Read the article

  • Marquee in various TextView at the same time?

    - by YaW
    Hi, I have a dinamic layout wich has one to six TextViews. All the TextViews are created in the Activity (programatically) and all are created equally. I want to marquee the text in the TextViews, but I don't know how to do it. Apparently, the TextView needs to be focused for the marquee works fine, but how i focus six TextViews at the same time? I think that's not possible, so, is there any workaround? Is it possible to get the marquee working without having the focus? This is the code of the TextViews: //TextView TextView tvTitulo = new TextView(this); tvTitulo.setText("Some loooooooooooooooooooooong text"); tvTitulo.setTypeface(null, Typeface.BOLD); //Marquee tvTitulo.setSingleLine(); tvTitulo.setEllipsize(TruncateAt.MARQUEE); tvTitulo.setHorizontallyScrolling(true); tvTitulo.setFocusableInTouchMode(true); If I remove the line tvTitulo.setFocusableInTouchMode(true); the marquee is not working at all. If I don't remove the line, only one of the TextViews is getting the marquee working. Greetings

    Read the article

  • How to keep the session of user login?

    - by YaW
    Hi, I have an app that requires user to register. I've got the app conected to PHP in my server to do the logic of register/login and so, this is not problem at all. But, I want to keep a session of the user in local, so the user doesn't have to login again every time he runs the app. So, I want something like this: First time user, he opens the app, register and login. Do some stuff with the app and closes it. Open the app again, the user is recognized so he doesn't need to login again. I only need to store an ID and a Username (both fetched from the DB in the login php method). What's the best way to do this?? I've thought about doing a custom preference, store the data in files or even a local DB (sqlite). Any suggestions?

    Read the article

  • downloaded zip file returns zero has 0 bytes as size

    - by Yaw Reuben
    I have written a Java web application that allows a user to download files from a server. These files are quite large and so are zipped together before download. It works like this: 1. The user gets a list of files that match his/her criteria 2. If the user likes a file and wants to download he/she selects it by checking a checkbox 3. The user then clicks "download" 4. The files are then zipped and stored on a server 5. The user this then presented with a page which contains a link to the downloadable zip file 6. However on downloading the zip file the file that is downloaded is 0 bytes in size I have checked the remote server and the zip file is being created properly, all that is left is to serve the file the user somehow, can you see where I might be going wrong, or suggest a better way to serve the zip file. The code that creates the link is: <% String zipFileURL = (String) request.getAttribute("zipFileURL"); %> <p><a href="<% out.print(zipFileURL); %> ">Zip File Link</a></p> The code that creates the zipFileURL variable is: public static String zipFiles(ArrayList<String> fileList, String contextRootPath) { //time-stamping Date date = new Date(); Timestamp timeStamp = new Timestamp(date.getTime()); Iterator fileListIterator = fileList.iterator(); String zipFileURL = ""; try { String ZIP_LOC = contextRootPath + "WEB-INF" + SEP + "TempZipFiles" + SEP; BufferedInputStream origin = null; zipFileURL = ZIP_LOC + "FITS." + timeStamp.toString().replaceAll(":", ".").replaceAll(" ", ".") + ".zip"; FileOutputStream dest = new FileOutputStream(ZIP_LOC + "FITS." + timeStamp.toString().replaceAll(":", ".").replaceAll(" ", ".") + ".zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream( dest)); // out.setMethod(ZipOutputStream.DEFLATED); byte data[] = new byte[BUFFER]; while(fileListIterator.hasNext()) { String fileName = (String) fileListIterator.next(); System.out.println("Adding: " + fileName); FileInputStream fi = new FileInputStream(fileName); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fileName); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } origin.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } return zipFileURL; }

    Read the article

  • ISAPI_Rewrite: Zend PHP Framework project setup

    - by Yaw Reuben
    How do I go about getting the isapi_rewrite working on IIS 6.0? My shared hosting account supports ISAPI_Rewrite - I've run the provided tests to confirm. I'm only able to access the index page of my Zend PHP project, but get the 404 error for other actions in my index controller class definition. I've basically placed the code: [ISAPI_Rewrite] RepeatLimit 20 RewriteRule (?!\.(js|ico|gif|jpg|png|css|swf))$ index.php in an httpd.ini access file in my wwwroot directory. Is there anything I'm missing?

    Read the article

  • Dismiss a custom dialog?

    - by YaW
    Hi, I'm trying to make a custom dialog to show a view in this dialog. This is the Builder code: //Getting the layout LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_dialog_simple, (ViewGroup) findViewById(R.id.rlDialogSimple)); //Change Text and on click TextView tvDialogSimple = (TextView) layout.findViewById(R.id.tvDialogSimple); tvDialogSimple.setText(R.string.avisoComprobar); Button btDialogSimple = (Button) layout.findViewById(R.id.btDialogSimple); btDialogSimple.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Do some stuff //Here i want to close the dialog } }); AlertDialog.Builder builder = new AlertDialog.Builder(AcPanelEditor.this); builder.setView(layout); AlertDialog alert = builder.create(); alert.show(); So, i want to dismiss the dialog in the onClick of btDialogSimple. How i can do it? I don't know how to call the dismiss method from inside a onclicklistener. My buttons have a custom layout, so i don't want to make a builder.setPositiveButton. Any ideas?

    Read the article

  • How to set a __str__ method for all ctype Structure classes?

    - by Reuben Thomas
    [Since asking this question, I've found: http://www.cs.unc.edu/~gb/blog/2007/02/11/ctypes-tricks/ which gives a good answer.] I just wrote a __str__ method for a ctype-generated Structure class 'foo' thus: def foo_to_str(self): s = [] for i in foo._fields_: s.append('{}: {}'.format(i[0], foo.\_\_getattribute__(self, i[0]))) return '\n'.join(s) foo.\_\_str__ = foo_to_str But this is a fairly natural way to produce a __str__ method for any Structure class. How can I add this method directly to the Structure class, so that all Structure classes generated by ctypes get it? (I am using the h2xml and xml2py scripts to auto-generate ctypes code, and this offers no obvious way to change the names of the classes output, so simply subclassing Structure, Union &c. and adding my __str__ method there would involve post-processing the output of xml2py.)

    Read the article

  • PendingIntent in Widget + TaskKiller

    - by YaW
    Hi, I've developed an Application (called Instant Buttons) and the app has a widget feature. This widget uses PendingIntent for the onClick of the widget. My PendingIntent code is something like this: Intent active = new Intent(context, InstantWidget.class); active.setAction(String.valueOf(appWidgetId)); active.putExtra("blabla", blabla); //Some data PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0); actionPendingIntent.cancel(); actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0); remoteViews.setOnClickPendingIntent(R.id.button, actionPendingIntent); The onReceive gets the intent and do some stuff with the MediaPlayer class to reproduce a sound. I have reports from some users that the widgets stop working after a while and with some research i've discovered is because the Task Killers. It seems that when you kill the app in the TaskKiller, the PendingIntent is erased from memory, so when you click the widget, it doesn't know what to do. Is there any solution for this? Is my code wrong or something or it's the default behavior of the PendingIntent? Is there something I can use to avoid the TaskKiller to stop my widgets from working?? Greetings.

    Read the article

  • Wordpress loop not showing 'else' when no posts exist

    - by Reuben
    When no posts exist I'm used to seeing the message after the else, and I'm not sure why it's not showing it now? Code: <?php $args = array( 'post_type' => 'event', 'posts_per_page' => 1, 'post_status' => 'future', 'order' => 'ASC' ); $loop = new WP_Query( $args ); if ( have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="event_preview_title"><?php the_title(); ?></div> <div class="event_details"> <div class="event_date"><?php the_time('m/d/y'); ?></div> <div class="event_time"><?php the_time('g:i A'); ?></div> </div> <?php the_post_thumbnail( array(65,65) ); ?> <a class="clickthrough" href="<?php bloginfo('wpurl'); ?>/events"></a> <?php endwhile; else: ?> <p>Bluebird Books may be coming soon to a neighborhood near you!<br /> We are currently on hiatus planning our next season's schedule. New tour dates will be posted to this page once confirmed. Meanwhile, inquiries about appearances and programs are welcomed! If you are interested in having Bluebird visit your business, school, or special event, please contact us.</p> <?php endif; ?> Thanks!

    Read the article

  • Change ID to text in paragraph with jQuery

    - by Reuben
    I would like to take what text is in my p tag and make that the p tags parent (div) that ID. I would also like to add a _ for any spaces in the p tag. Example: <div class="circle"><p>Apple</p></div> <div class="circle"><p>Banana</p></div> <div class="circle"><p>Carrot Juice</p></div> to <div id="Apple" class="circle"><p>Apple</p></div> <div id="Banana" class="circle"><p>Banana</p></div> <div id="Carrot_Juice" class="circle"><p>Carrot Juice</p></div>

    Read the article

  • How do I detect a Word table with (horizontally) merged cells?

    - by Reuben
    When a Word table contains horizontally merged cells, accessing aTable.Columns.First or performing a For Each over aTable.Columns will result in an error. Is there a way to determine if a table contains horizontally merged cells without resulting in an error? I've read Determine if a Word cell is merged, but that is about detecting if a particular Word table cell is merged, rather than does the whole table have any merged cells.

    Read the article

  • what does AngleVectors method in quake 3 source code does

    - by kypronite
    I just downloaded quake 3 for learning purposes. I know some of some linear algebra(basic vector math ie: dot,cross product). However I can't decipher what below method does, I know what is yaw,pitch and roll. But I can't connect these with vector. Worse, I'm not sure this fall under what math 'category', so I don't really know how to google. Hence the question here. Anyone? void AngleVectors( const vec3_t angles, vec3_t forward, vec3_t right, vec3_t up) { float angle; static float sr, sp, sy, cr, cp, cy; // static to help MS compiler fp bugs angle = angles[YAW] * (M_PI*2 / 360); sy = sin(angle); cy = cos(angle); angle = angles[PITCH] * (M_PI*2 / 360); sp = sin(angle); cp = cos(angle); angle = angles[ROLL] * (M_PI*2 / 360); sr = sin(angle); cr = cos(angle); if (forward) { forward[0] = cp*cy; forward[1] = cp*sy; forward[2] = -sp; } if (right) { right[0] = (-1*sr*sp*cy+-1*cr*-sy); right[1] = (-1*sr*sp*sy+-1*cr*cy); right[2] = -1*sr*cp; } if (up) { up[0] = (cr*sp*cy+-sr*-sy); up[1] = (cr*sp*sy+-sr*cy); up[2] = cr*cp; } } ddddd

    Read the article

  • (Quaternion based) Trouble moving foward based on model rotation

    - by ChocoMan
    Using quaternions, I'm having trouble moving my model in its facing direction. Currently the model moves can move in all cardinal directions with no problems. The problem comes when I rotate the move as it still travelling in the direction of world space. Meaning, if I'm moving forward, backward or any other direction while rotating the model, the model acts like its a figure skater spinning while traveling in the same direction. How do I update the direction of travel proper with the facing direction of the model? Rotates model on Y-axis: Yaw = pController.ThumbSticks.Right.X * MathHelper.ToRadians(speedAngleMAX); AddRotation = Quaternion.CreateFromYawPitchRoll(yaw, 0, 0); ModelLoad.MRotation *= AddRotation; MOrientation = Matrix.CreateFromQuaternion(ModelLoad.MRotation); Moves model forward: // Move Forward if (pController.IsButtonDown(Buttons.LeftThumbstickUp)) { SpeedX = (float)(Math.Sin(ModelLoad.ModelRotation)) * FWDSpeedMax * pController.ThumbSticks.Left.Y * (float)gameTime.ElapsedGameTime.TotalSeconds; SpeedZ = (float)(Math.Cos(ModelLoad.ModelRotation)) * FWDSpeedMax * pController.ThumbSticks.Left.Y * (float)gameTime.ElapsedGameTime.TotalSeconds; // Update model position ModelLoad._modelPos += Vector3.Forward * SpeedZ; ModelLoad._modelPos += Vector3.Left * SpeedX; }

    Read the article

  • How is the gimbal locked problem solved using accumulative matrix transformations

    - by Luke San Antonio
    I am reading the online "Learning Modern 3D Graphics Programming" book by Jason L. McKesson As of now, I am up to the gimbal lock problem and how to solve it using quaternions. However right here, at the Quaternions page. Part of the problem is that we are trying to store an orientation as a series of 3 accumulated axial rotations. Orientations are orientations, not rotations. And orientations are certainly not a series of rotations. So we need to treat the orientation of the ship as an orientation, as a specific quantity. I guess this is the first spot I start to get confused, the reason is because I don't see the dramatic difference between orientations and rotations. I also don't understand why an orientation cannot be represented by a series of rotations... Also: The first thought towards this end would be to keep the orientation as a matrix. When the time comes to modify the orientation, we simply apply a transformation to this matrix, storing the result as the new current orientation. This means that every yaw, pitch, and roll applied to the current orientation will be relative to that current orientation. Which is precisely what we need. If the user applies a positive yaw, you want that yaw to rotate them relative to where they are current pointing, not relative to some fixed coordinate system. The concept, I understand, however I don't understand how if accumulating matrix transformations is a solution to this problem, how the code given in the previous page isn't just that. Here's the code: void display() { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glutil::MatrixStack currMatrix; currMatrix.Translate(glm::vec3(0.0f, 0.0f, -200.0f)); currMatrix.RotateX(g_angles.fAngleX); DrawGimbal(currMatrix, GIMBAL_X_AXIS, glm::vec4(0.4f, 0.4f, 1.0f, 1.0f)); currMatrix.RotateY(g_angles.fAngleY); DrawGimbal(currMatrix, GIMBAL_Y_AXIS, glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)); currMatrix.RotateZ(g_angles.fAngleZ); DrawGimbal(currMatrix, GIMBAL_Z_AXIS, glm::vec4(1.0f, 0.3f, 0.3f, 1.0f)); glUseProgram(theProgram); currMatrix.Scale(3.0, 3.0, 3.0); currMatrix.RotateX(-90); //Set the base color for this object. glUniform4f(baseColorUnif, 1.0, 1.0, 1.0, 1.0); glUniformMatrix4fv(modelToCameraMatrixUnif, 1, GL_FALSE, glm::value_ptr(currMatrix.Top())); g_pObject->Render("tint"); glUseProgram(0); glutSwapBuffers(); } To my understanding, isn't what he is doing (modifying a matrix on a stack) considered accumulating matrices, since the author combined all the individual rotation transformations into one matrix which is being stored on the top of the stack. My understanding of a matrix is that they are used to take a point which is relative to an origin (let's say... the model), and make it relative to another origin (the camera). I'm pretty sure this is a safe definition, however I feel like there is something missing which is blocking me from understanding this gimbal lock problem. One thing that doesn't make sense to me is: If a matrix determines the difference relative between two "spaces," how come a rotation around the Y axis for, let's say, roll, doesn't put the point in "roll space" which can then be transformed once again in relation to this roll... In other words shouldn't any further transformations to this point be in relation to this new "roll space" and therefore not have the rotation be relative to the previous "model space" which is causing the gimbal lock. That's why gimbal lock occurs right? It's because we are rotating the object around set X, Y, and Z axes rather than rotating the object around it's own, relative axes. Or am I wrong? Since apparently this code I linked in isn't an accumulation of matrix transformations can you please give an example of a solution using this method. So in summary: What is the difference between a rotation and an orientation? Why is the code linked in not an example of accumulation of matrix transformations? What is the real, specific purpose of a matrix, if I had it wrong? How could a solution to the gimbal lock problem be implemented using accumulation of matrix transformations? Also, as a bonus: Why are the transformations after the rotation still relative to "model space?" Another bonus: Am I wrong in the assumption that after a transformation, further transformations will occur relative to the current? Also, if it wasn't implied, I am using OpenGL, GLSL, C++, and GLM, so examples and explanations in terms of these are greatly appreciated, if not necessary. The more the detail the better! Thanks in advance...

    Read the article

  • How to maintain encapsulation with composition in C++?

    - by iFreilicht
    I am designing a class Master that is composed from multiple other classes, A, Base, C and D. These four classes have absolutely no use outside of Master and are meant to split up its functionality into manageable and logically divided packages. They also provide extensible functionality as in the case of Base, which can be inherited from by clients. But, how do I maintain encapsulation of Master with this design? So far, I've got two approaches, which are both far from perfect: 1. Replicate all accessors: Just write accessor-methods for all accessor-methods of all classes that Master is composed of. This leads to perfect encapsulation, because no implementation detail of Master is visible, but is extremely tedious and makes the class definition monstrous, which is exactly what the composition should prevent. Also, adding functionality to one of the composees (is that even a word?) would require to re-write all those methods in Master. An additional problem is that inheritors of Base could only alter, but not add functionality. 2. Use non-assignable, non-copyable member-accessors: Having a class accessor<T> that can not be copied, moved or assigned to, but overrides the operator-> to access an underlying shared_ptr, so that calls like Master->A()->niceFunction(); are made possible. My problem with this is that it kind of breaks encapsulation as I would now be unable to change my implementation of Master to use a different class for the functionality of niceFunction(). Still, it is the closest I've gotten without using the ugly first approach. It also fixes the inheritance issue quite nicely. A small side question would be if such a class already existed in std or boost. EDIT: Wall of code I will now post the code of the header files of the classes discussed. It may be a bit hard to understand, but I'll give my best in explaining all of it. 1. GameTree.h The foundation of it all. This basically is a doubly-linked tree, holding GameObject-instances, which we'll later get to. It also has it's own custom iterator GTIterator, but I left that out for brevity. WResult is an enum with the values SUCCESS and FAILED, but it's not really important. class GameTree { public: //Static methods for the root. Only one root is allowed to exist at a time! static void ConstructRoot(seed_type seed, unsigned int depth); inline static bool rootExists(){ return static_cast<bool>(rootObject_); } inline static weak_ptr<GameTree> root(){ return rootObject_; } //delta is in ms, this is used for velocity, collision and such void tick(unsigned int delta); //Interaction with the tree inline weak_ptr<GameTree> parent() const { return parent_; } inline unsigned int numChildren() const{ return static_cast<unsigned int>(children_.size()); } weak_ptr<GameTree> getChild(unsigned int index) const; template<typename GOType> weak_ptr<GameTree> addChild(seed_type seed, unsigned int depth = 9001){ GOType object{ new GOType(seed) }; return addChildObject(unique_ptr<GameTree>(new GameTree(std::move(object), depth))); } WResult moveTo(weak_ptr<GameTree> newParent); WResult erase(); //Iterators for for( : ) loop GTIterator& begin(){ return *(beginIter_ = std::move(make_unique<GTIterator>(children_.begin()))); } GTIterator& end(){ return *(endIter_ = std::move(make_unique<GTIterator>(children_.end()))); } //unloading should be used when objects are far away WResult unloadChildren(unsigned int newDepth = 0); WResult loadChildren(unsigned int newDepth = 1); inline const RenderObject& renderObject() const{ return gameObject_->renderObject(); } //Getter for the underlying GameObject (I have not tested the template version) weak_ptr<GameObject> gameObject(){ return gameObject_; } template<typename GOType> weak_ptr<GOType> gameObject(){ return dynamic_cast<weak_ptr<GOType>>(gameObject_); } weak_ptr<PhysicsObject> physicsObject() { return gameObject_->physicsObject(); } private: GameTree(const GameTree&); //copying is only allowed internally GameTree(shared_ptr<GameObject> object, unsigned int depth = 9001); //pointer to root static shared_ptr<GameTree> rootObject_; //internal management of a child weak_ptr<GameTree> addChildObject(shared_ptr<GameTree>); WResult removeChild(unsigned int index); //private members shared_ptr<GameObject> gameObject_; shared_ptr<GTIterator> beginIter_; shared_ptr<GTIterator> endIter_; //tree stuff vector<shared_ptr<GameTree>> children_; weak_ptr<GameTree> parent_; unsigned int selfIndex_; //used for deletion, this isn't necessary void initChildren(unsigned int depth); //constructs children }; 2. GameObject.h This is a bit hard to grasp, but GameObject basically works like this: When constructing a GameObject, you construct its basic attributes and a CResult-instance, which contains a vector<unique_ptr<Construction>>. The Construction-struct contains all information that is needed to construct a GameObject, which is a seed and a function-object that is applied at construction by a factory. This enables dynamic loading and unloading of GameObjects as done by GameTree. It also means that you have to define that factory if you inherit GameObject. This inheritance is also the reason why GameTree has a template-function gameObject<GOType>. GameObject can contain a RenderObject and a PhysicsObject, which we'll later get to. Anyway, here's the code. class GameObject; typedef unsigned long seed_type; //this declaration magic means that all GameObjectFactorys inherit from GameObjectFactory<GameObject> template<typename GOType> struct GameObjectFactory; template<> struct GameObjectFactory<GameObject>{ virtual unique_ptr<GameObject> construct(seed_type seed) const = 0; }; template<typename GOType> struct GameObjectFactory : GameObjectFactory<GameObject>{ GameObjectFactory() : GameObjectFactory<GameObject>(){} unique_ptr<GameObject> construct(seed_type seed) const{ return unique_ptr<GOType>(new GOType(seed)); } }; //same as with the factories. this is important for storing them in vectors template<typename GOType> struct Construction; template<> struct Construction<GameObject>{ virtual unique_ptr<GameObject> construct() const = 0; }; template<typename GOType> struct Construction : Construction<GameObject>{ Construction(seed_type seed, function<void(GOType*)> func = [](GOType* null){}) : Construction<GameObject>(), seed_(seed), func_(func) {} unique_ptr<GameObject> construct() const{ unique_ptr<GameObject> gameObject{ GOType::factory.construct(seed_) }; func_(dynamic_cast<GOType*>(gameObject.get())); return std::move(gameObject); } seed_type seed_; function<void(GOType*)> func_; }; typedef struct CResult { CResult() : constructions{} {} CResult(CResult && o) : constructions(std::move(o.constructions)) {} CResult& operator= (CResult& other){ if (this != &other){ for (unique_ptr<Construction<GameObject>>& child : other.constructions){ constructions.push_back(std::move(child)); } } return *this; } template<typename GOType> void push_back(seed_type seed, function<void(GOType*)> func = [](GOType* null){}){ constructions.push_back(make_unique<Construction<GOType>>(seed, func)); } vector<unique_ptr<Construction<GameObject>>> constructions; } CResult; //finally, the GameObject class GameObject { public: GameObject(seed_type seed); GameObject(const GameObject&); virtual void tick(unsigned int delta); inline Matrix4f trafoMatrix(){ return physicsObject_->transformationMatrix(); } //getter inline seed_type seed() const{ return seed_; } inline CResult& properties(){ return properties_; } inline const RenderObject& renderObject() const{ return *renderObject_; } inline weak_ptr<PhysicsObject> physicsObject() { return physicsObject_; } protected: virtual CResult construct_(seed_type seed) = 0; CResult properties_; shared_ptr<RenderObject> renderObject_; shared_ptr<PhysicsObject> physicsObject_; seed_type seed_; }; 3. PhysicsObject That's a bit easier. It is responsible for position, velocity and acceleration. It will also handle collisions in the future. It contains three Transformation objects, two of which are optional. I'm not going to include the accessors on the PhysicsObject class because I tried my first approach on it and it's just pure madness (way over 30 functions). Also missing: the named constructors that construct PhysicsObjects with different behaviour. class Transformation{ Vector3f translation_; Vector3f rotation_; Vector3f scaling_; public: Transformation() : translation_{ 0, 0, 0 }, rotation_{ 0, 0, 0 }, scaling_{ 1, 1, 1 } {}; Transformation(Vector3f translation, Vector3f rotation, Vector3f scaling); inline Vector3f translation(){ return translation_; } inline void translation(float x, float y, float z){ translation(Vector3f(x, y, z)); } inline void translation(Vector3f newTranslation){ translation_ = newTranslation; } inline void translate(float x, float y, float z){ translate(Vector3f(x, y, z)); } inline void translate(Vector3f summand){ translation_ += summand; } inline Vector3f rotation(){ return rotation_; } inline void rotation(float pitch, float yaw, float roll){ rotation(Vector3f(pitch, yaw, roll)); } inline void rotation(Vector3f newRotation){ rotation_ = newRotation; } inline void rotate(float pitch, float yaw, float roll){ rotate(Vector3f(pitch, yaw, roll)); } inline void rotate(Vector3f summand){ rotation_ += summand; } inline Vector3f scaling(){ return scaling_; } inline void scaling(float x, float y, float z){ scaling(Vector3f(x, y, z)); } inline void scaling(Vector3f newScaling){ scaling_ = newScaling; } inline void scale(float x, float y, float z){ scale(Vector3f(x, y, z)); } void scale(Vector3f factor){ scaling_(0) *= factor(0); scaling_(1) *= factor(1); scaling_(2) *= factor(2); } Matrix4f matrix(){ return WMatrix::Translation(translation_) * WMatrix::Rotation(rotation_) * WMatrix::Scale(scaling_); } }; class PhysicsObject; typedef void tickFunction(PhysicsObject& self, unsigned int delta); class PhysicsObject{ PhysicsObject(const Transformation& trafo) : transformation_(trafo), transformationVelocity_(nullptr), transformationAcceleration_(nullptr), tick_(nullptr) {} PhysicsObject(PhysicsObject&& other) : transformation_(other.transformation_), transformationVelocity_(std::move(other.transformationVelocity_)), transformationAcceleration_(std::move(other.transformationAcceleration_)), tick_(other.tick_) {} Transformation transformation_; unique_ptr<Transformation> transformationVelocity_; unique_ptr<Transformation> transformationAcceleration_; tickFunction* tick_; public: void tick(unsigned int delta){ tick_ ? tick_(*this, delta) : 0; } inline Matrix4f transformationMatrix(){ return transformation_.matrix(); } } 4. RenderObject RenderObject is a base class for different types of things that could be rendered, i.e. Meshes, Light Sources or Sprites. DISCLAIMER: I did not write this code, I'm working on this project with someone else. class RenderObject { public: RenderObject(float renderDistance); virtual ~RenderObject(); float renderDistance() const { return renderDistance_; } void setRenderDistance(float rD) { renderDistance_ = rD; } protected: float renderDistance_; }; struct NullRenderObject : public RenderObject{ NullRenderObject() : RenderObject(0.f){}; }; class Light : public RenderObject{ public: Light() : RenderObject(30.f){}; }; class Mesh : public RenderObject{ public: Mesh(unsigned int seed) : RenderObject(20.f) { meshID_ = 0; textureID_ = 0; if (seed == 1) meshID_ = Model::getMeshID("EM-208_heavy"); else meshID_ = Model::getMeshID("cube"); }; unsigned int getMeshID() const { return meshID_; } unsigned int getTextureID() const { return textureID_; } private: unsigned int meshID_; unsigned int textureID_; }; I guess this shows my issue quite nicely: You see a few accessors in GameObject which return weak_ptrs to access members of members, but that is not really what I want. Also please keep in mind that this is NOT, by any means, finished or production code! It is merely a prototype and there may be inconsistencies, unnecessary public parts of classes and such.

    Read the article

  • How does this snippet of code create a ray direction vector?

    - by Isaac Waller
    In the Minecraft source code, this code is used to create a direction vector for a ray from pitch and yaw:' float f1 = MathHelper.cos(-rotationYaw * 0.01745329F - 3.141593F); float f3 = MathHelper.sin(-rotationYaw * 0.01745329F - 3.141593F); float f5 = -MathHelper.cos(-rotationPitch * 0.01745329F); float f7 = MathHelper.sin(-rotationPitch * 0.01745329F); return Vec3D.createVector(f3 * f5, f7, f1 * f5); I was wondering how it worked, and what is the constant 0.01745329F?

    Read the article

  • way to do if(x > x2) x = x2 with rotation?

    - by CyanPrime
    Alright, so I got this walking code, and some collision detection, now the collision detection returns a Vector3f of the closest point on the triangle that the projected position is at (pos + move), so then I project my position again in the walking method/function and if the projected position's x is the nearest point'x the projected position's x becomes the nearist point's x. same with their z points, but if I'm moving in a different direction from 0 degrees XZ how would I rotate the equation/condition? Here is what I got so far, and it's not working, as I go through walls, and such. Vector3f move = new Vector3f(0,0,0); move.x = (float)-Math.cos(Math.toRadians(yaw)); move.z = (float)-Math.sin(Math.toRadians(yaw)); // System.out.println("slopeNormal.z: " + slopeNormal.z + "move.z: " + move.z); move.normalise(); move.scale(movementSpeed * delta); float horizontaldotproduct = move.x * slopeNormal.x + move.z * slopeNormal.z; move.y = -horizontaldotproduct * slopeNormal.y; Vector3f dest = colCheck(pos, move, model, drawDist, movementSpeed, delta); Vector3f projPos = new Vector3f(pos); Vector3f.add(projPos, move, projPos); if(projPos.x > 0 && dest.x > 0 && projPos.x < dest.x) projPos.x = dest.x; else if(projPos.x < 0 && dest.x < 0 && projPos.x > dest.x) projPos.x = dest.x; if(projPos.z > 0 && dest.z > 0 && projPos.z < dest.z) projPos.z = dest.z; else if(projPos.z < 0 && dest.z < 0 && projPos.z > dest.z) projPos.z = dest.z; pos = new Vector3f(projPos);

    Read the article

  • Mouse input not updating in custom XNA/Winforms panel

    - by ChocoMan
    I have a custom Panel residing within my WinForm. the custom Panel holds the XNA rendering. So far, I've rendered an 3D test model. What I'm doing now is trying to handle the input.Using a camera from another working game, keyboard input works fine moving the camera in all 6 directions. But when it comes to handling the mouse to yaw and pitch the camera, nothing happens. I've searched about to see if anyone has come across this problem, but found no testable solutions to my problem. Does anyone understand as to what may be causing the Mouse not to be called when moved? Within MainForm constructor: public MainForm() { InitializeComponent(); Mouse.WindowHandle = panel3D.Handle; } Panel3D.cs Custom XNA Panel class FreeCamera.cs FreeCamera class

    Read the article

  • Creating an OpenGL FPS camera: I have the position and orientation vectors, now what?

    - by Synthetix
    I have been struggling to create a first person camera in OpenGL ES 2.0 without using gluLookAt(). I grab the camera's orientation vectors (the way it's looking) from the current modelview matrix, and use that to calculate the new forward/backward (Z) translation value. I then calculate the strafe (X) value from the dot product of Z and Y (which is always 1.0). So, I have all the information I need to create a view matrix, but how do I do that without using gluLookAt? Almost all the examples I've seen use gluLookAt, but no such function exists in OpenGL ES 2.0. Besides, one of the moderators on cprogramming.com mentioned that gluLookAt is not appropriate for FPS cameras: http://cboard.cprogramming.com/game-programming/135390-how-properly-move-strafe-yaw-pitch-camera-opengl-glut-using-glulookat.html I am really confused by all the conflicting information I'm getting. I just want to create a first person camera that goes forward (W,S keys), side-to-side (A,D keys) and rotates around its center (Y axis only), Wolfenstein style. Any help on this would be much appreciated!

    Read the article

  • DHCP Relay V DHCP Local Cisco v 3com

    - by DefSol
    Howdy, I have a client who has a WAN with 7 sites. At one site in particular, randomly about 4-5 clients do not get an IP address. The local gateway is a cisco 871 and relay's to a windows server in a Data Center running a valid scope for the subnet. If I put in a cisco 1800 and configure a dhcp scope (disabling the scope on the server) all clients get an ip address and everything is right with the world. The Wan providing keeps saying it's a local issue although we can work around with the 1800. The provider says a 3Com switch is at fault and the 1800 does not have a local switch, and because the 871 does, means the internal switching will receive a different uplink policy. The 3Com is the only managed switch in the subnet. Any ideas greatly appreciated. Reuben

    Read the article

  • DHCP Relay V DHCP Local Cisoc v 3com

    - by DefSol
    Howdy, I have a client who has a WAN with 7 sites. At one site in particular, randomly about 4-5 clients do not get an IP address. The local gateway is a cisco 871 and relay's to a windows server in a Data Center running a valid scope for the subnet. If I put in a cisco 1800 and configure a dhcp scope (disabling the scope on the server) all clients get an ip address and everything is right with the world. The Wan providing keeps saying it's a local issue although we can work around with the 1800. The provider says a 3Com switch is at fault and the 1800 does not have a local switch, and because the 871 does, means the internal switching will receive a different uplink policy. The 3Com is the only managed switch in the subnet. Any ideas greatly appreciated. Reuben

    Read the article

  • aspnet membeship logon page and https redirect

    - by DefSol
    Hello, I have a gridview control that has on onclick event bound to every cell. Once a user clicks on a cell it directs them to a booking confirmation page and passes 3 url variables. This booking page is behind a aspnet membership and thus if the user is not logged in they are served the login page. The login page has a redirect to https connection in the onload event using the IsSecure property. The issue is once the user logs in, then is returned to the booking confirmation page I lose 2 of the url vars. If I remove the https redirect, everything works fine, but the user logs on on a http connection, which is not cool. Appreciate and help thanks Reuben

    Read the article

  • Arbitrary Rotation about a Sphere

    - by Der
    I'm coding a mechanic which allows a user to move around the surface of a sphere. The position on the sphere is currently stored as theta and phi, where theta is the angle between the z-axis and the xz projection of the current position (i.e. rotation about the y axis), and phi is the angle from the y-axis to the position. I explained that poorly, but it is essentially theta = yaw, phi = pitch Vector3 position = new Vector3(0,0,1); position.X = (float)Math.Sin(phi) * (float)Math.Sin(theta); position.Y = (float)Math.Sin(phi) * (float)Math.Cos(theta); position.Z = (float)Math.Cos(phi); position *= r; I believe this is accurate, however I could be wrong. I need to be able to move in an arbitrary pseudo two dimensional direction around the surface of a sphere at the origin of world space with radius r. For example, holding W should move around the sphere in an upwards direction relative to the orientation of the player. I believe I should be using a Quaternion to represent the position/orientation on the sphere, but I can't think of the correct way of doing it. Spherical geometry is not my strong suit. Essentially, I need to fill the following block: public void Move(Direction dir) { switch (dir) { case Direction.Left: // update quaternion to rotate left break; case Direction.Right: // update quaternion to rotate right break; case Direction.Up: // update quaternion to rotate upward break; case Direction.Down: // update quaternion to rotate downward break; } }

    Read the article

< Previous Page | 1 2 3  | Next Page >