Search Results

Search found 711 results on 29 pages for 'pos'.

Page 6/29 | < Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >

  • How To Compile YACC And LEX?

    - by nisha
    Actually I'm having YACC file as pos.yacc and LEX file name is pos1.lex.. while compilling I'm getting the folowing error... malathy@malathy:~$ cc lex.yy.c y.tab.c -ly -ll pos1.lex %{ #include "y.tab.h" int yylval; %} DIGIT [0-9]+ %% {DIGIT} {yylval=atoi(yytext);return DIGIT;} [\n ] {} . {return *yytext;} %% yacc file is pos.yacc %token DIGIT %% s:e {printf("%d\n",$1);} e:DIGIT {$$=$1;} |e e "+" {$$=$1+$2;} |e e "*" {$$=$1*$2;} |e e "-" {$$=$1-$2;} |e e "/" {$$=$1/$2;} ; %% main() { yyparse(); } yyerror() { printf("Error"); } so while compiling i m getting like malathy@malathy:~$ cc lex.yy.c y.tab.c -ly -ll pos.y: In function ‘yyerror’: pos.y:16: warning: incompatible implicit declaration of built-in function ‘printf’ pos.y: In function ‘yyparse’: pos.y:4: warning: incompatible implicit declaration of built-in function ‘printf’

    Read the article

  • VB.NET Syntax Coding

    - by Yiu Korochko
    I know many people ask how some of these are done, but I do not understand the context in which to use the answers, so... I'm building a code editor for a subversion of Python language, and I found a very decent way of highlighting keywords in the RichTextBox through this: bluwords.Add(KEYWORDS GO HERE) If scriptt.Text.Length > 0 Then Dim selectStart2 As Integer = scriptt.SelectionStart scriptt.Select(0, scriptt.Text.Length) scriptt.SelectionColor = Color.Black scriptt.DeselectAll() For Each oneWord As String In bluwords Dim pos As Integer = 0 Do While scriptt.Text.ToUpper.IndexOf(oneWord.ToUpper, pos) >= 0 pos = scriptt.Text.ToUpper.IndexOf(oneWord.ToUpper, pos) scriptt.Select(pos, oneWord.Length) scriptt.SelectionColor = Color.Blue pos += 1 Loop Next scriptt.SelectionStart = selectStart2 End If (scriptt is the richtextbox) But when any decent amount of code is typed (or loaded via OpenFileDialog) chunks of the code go missing, the syntax selection falls apart, and it just plain ruins it. I'm looking for a more efficient way of doing this, maybe something more like visual studio itself...because there is NO NEED to highlight all text, set it black, then redo all of the syntaxing, and the text begins to over-right if you go back to insert characters between text. Also, in this version of Python, hash (#) is used for comments on comment only lines and double hash (##) is used for comments on the same line. Now I saw that someone had asked about this exact thing, and the working answer to select to the end of the line was something like: ^\'[^\r\n]+$|''[^\r\n]+$ which I cannot seem to get into practice. I also wanted to select text between quotes and turn it turquoise, such as between the first quotation mark and the second, the text is turquoise, and the same between the 3rd and 4th etcetera... Any help is appreciated!

    Read the article

  • Is There a Better Way to Feed Different Parameters into Functions with If-Statements?

    - by FlowofSoul
    I've been teaching myself Python for a little while now, and I've never programmed before. I just wrote a basic backup program that writes out the progress of each individual file while it is copying. I wrote a function that determines buffer size so that smaller files are copied with a smaller buffer, and bigger files are copied with a bigger buffer. The way I have the code set up now doesn't seem very efficient, as there is an if loop that then leads to another if loops, creating four options, and they all just call the same function with different parameters. import os import sys def smartcopy(filestocopy, dest_path, show_progress = False): """Determines what buffer size to use with copy() Setting show_progress to True calls back display_progress()""" #filestocopy is a list of dictionaries for the files needed to be copied #dictionaries are used as the fullpath, st_mtime, and size are needed if len(filestocopy.keys()) == 0: return None #Determines average file size for which buffer to use average_size = 0 for key in filestocopy.keys(): average_size += int(filestocopy[key]['size']) average_size = average_size/len(filestocopy.keys()) #Smaller buffer for smaller files if average_size < 1024*10000: #Buffer sizes determined by informal tests on my laptop if show_progress: for key in filestocopy.keys(): #dest_path+key is the destination path, as the key is the relative path #and the dest_path is the top level folder copy(filestocopy[key]['fullpath'], dest_path+key, callback = lambda pos, total: display_progress(pos, total, key)) else: for key in filestocopy.keys(): copy(filestocopy[key]['fullpath'], dest_path+key, callback = None) #Bigger buffer for bigger files else: if show_progress: for key in filestocopy.keys(): copy(filestocopy[key]['fullpath'], dest_path+key, 1024*2600, callback = lambda pos, total: display_progress(pos, total, key)) else: for key in filestocopy.keys(): copy(filestocopy[key]['fullpath'], dest_path+key, 1024*2600) def display_progress(pos, total, filename): percent = round(float(pos)/float(total)*100,2) if percent <= 100: sys.stdout.write(filename + ' - ' + str(percent)+'% \r') else: percent = 100 sys.stdout.write(filename + ' - Completed \n') Is there a better way to accomplish what I'm doing? Sorry if the code is commented poorly or hard to follow. I didn't want to ask someone to read through all 120 lines of my poorly written code, so I just isolated the two functions. Thanks for any help.

    Read the article

  • Android ListView: how to select an item?

    - by mmo
    I am having trouble with a ListView I created: I want an item to get selected when I click on it. My code for this looks like: protected void onResume() { ... ListView lv = getListView(); lv.setOnItemSelectedListener(new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) { Log.v(TAG, "onItemSelected(..., " + pos + ",...) => selected: " + getSelectedItemPosition()); } public void onNothingSelected(AdapterView<?> adapterView) { Log.v(TAG, "onNothingSelected(...) => selected: " + getSelectedItemPosition()); } }); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) { lv.setSelection(pos); Log.v(TAG, "onItemClick(..., " + pos + ",...) => selected: " + getSelectedItemPosition()); } }); ... } When I run this and click e.g. on the second item (i.e. pos=1) I get: 04-03 23:08:36.994: V/DisplayLists(663): onItemClick(..., 1,...) => selected: -1 i.e. even though the OnItemClickListener is called with the proper argument and calls a setSelection(1), there is no item selected (and hence also OnItemSelectedListener.onItemSelected(...) is never called) and getSelectedItemPosition() still yields -1 after the setSelection(1)-call. What am I missing? Michael PS.: My list does have =2 elements...

    Read the article

  • Heightmap in Shader not working

    - by CSharkVisibleBasix
    I'm trying to implement GPU based geometry clipmapping and have problems to apply a simple heightmap to my terrain. For the heightmap I use a simple texture with the surface format "single". I've taken the texture from here. To apply it to my terrain, I use the following shader code: texture Heightmap; sampler2D HeightmapSampler = sampler_state { Texture = <Heightmap>; MinFilter = Point; MagFilter = Point; MipFilter = Point; AddressU = Mirror; AddressV = Mirror; }; Vertex Shader: float4 worldPos = mul(float4(pos.x,0.0f,pos.y, 1.0f), worldMatrix); float elevation = tex2Dlod(HeightmapSampler, float4(worldPos.x, worldPos.z,0,0)); worldPos.y = elevation * 128; The complete vertex shader (also containig clipmapping transforms) looks like this: float4x4 View : View; float4x4 Projection : Projection; float3 CameraPos : CameraPosition; float LODscale; //The LOD ring index 0:highest x:lowest float2 Position; //The position of the part in the world texture Heightmap; sampler2D HeightmapSampler = sampler_state { Texture = <Heightmap>; MinFilter = Point; MagFilter = Point; MipFilter = Point; AddressU = Mirror; AddressV = Mirror; }; //Accept only float2 because we extract 3rd dim out of Heightmap float4 wireframe_VS(float2 pos : POSITION) : POSITION{ float4x4 worldMatrix = float4x4( LODscale, 0, 0, 0, 0, LODscale, 0, 0, 0, 0, LODscale, 0, - Position.x * 64 * LODscale + CameraPos.x, 0, Position.y * 64 * LODscale + CameraPos.z, 1); float4 worldPos = mul(float4(pos.x,0.0f,pos.y, 1.0f), worldMatrix); float elevation = tex2Dlod(HeightmapSampler, float4(worldPos.x, worldPos.z,0,0)); worldPos.y = elevation * 128; float4 viewPos = mul(worldPos, View); float4 projPos = mul(viewPos, Projection); return projPos; }

    Read the article

  • Any significant performance improvement by using bitwise operators instead of plain int sums in C#?

    - by tunnuz
    Hello, I started working with C# a few weeks ago and I'm now in a situation where I need to build up a "bit set" flag to handle different cases in an algorithm. I have thus two options: enum RelativePositioning { LEFT = 0, RIGHT = 1, BOTTOM = 2, TOP = 3, FRONT = 4, BACK = 5 } pos = ((eye.X < minCorner.X ? 1 : 0) << RelativePositioning.LEFT) + ((eye.X > maxCorner.X ? 1 : 0) << RelativePositioning.RIGHT) + ((eye.Y < minCorner.Y ? 1 : 0) << RelativePositioning.BOTTOM) + ((eye.Y > maxCorner.Y ? 1 : 0) << RelativePositioning.TOP) + ((eye.Z < minCorner.Z ? 1 : 0) << RelativePositioning.FRONT) + ((eye.Z > maxCorner.Z ? 1 : 0) << RelativePositioning.BACK); Or: enum RelativePositioning { LEFT = 1, RIGHT = 2, BOTTOM = 4, TOP = 8, FRONT = 16, BACK = 32 } if (eye.X < minCorner.X) { pos += RelativePositioning.LEFT; } if (eye.X > maxCorner.X) { pos += RelativePositioning.RIGHT; } if (eye.Y < minCorner.Y) { pos += RelativePositioning.BOTTOM; } if (eye.Y > maxCorner.Y) { pos += RelativePositioning.TOP; } if (eye.Z > maxCorner.Z) { pos += RelativePositioning.FRONT; } if (eye.Z < minCorner.Z) { pos += RelativePositioning.BACK; } I could have used something as ((eye.X > maxCorner.X) << 1) but C# does not allow implicit casting from bool to int and the ternary operator was similar enough. My question now is: is there any performance improvement in using the first version over the second? Thank you Tommaso

    Read the article

  • How to calculate where bullet hits

    - by lkjoel
    I have been trying to write an FPS in C/X11/OpenGL, but the issue that I have encountered is with calculating where the bullet hits. I have used a horrible technique, and it only sometimes works: pos size, p; size.x = 0.1; size.z = 0.1; // Since the game is technically top-down (but in a 3D perspective) // Positions are in X/Z, no Y float f; // Counter float d = FIRE_MAX + 1 /* Shortest Distance */, d1 /* Distance being calculated */; x = 0; // Index of object to hit for (f = 0.0; f < FIRE_MAX; f += .01) { // Go forwards p.x = player->pos.x + f * sin(toRadians(player->rot.x)); p.z = player->pos.z - f * cos(toRadians(player->rot.x)); // Get all objects that collide with the current position of the bullet short* objs = _colDetectGetObjects(p, size, objects); for (i = 0; i < MAX_OBJECTS; i++) { if (objs[i] == -1) { continue; } // Check the distance between the object and the player d1 = sqrt( pow((objects[i].pos.x - player->pos.x), 2) + pow((objects[i].pos.z - player->pos.z), 2)); // If it's closer, set it as the object to hit if (d1 < d) { x = i; d = d1; } } // If there was an object, hit it if (x > 0) { hit(&objects[x], FIRE_DAMAGE, explosions, currtime); break; } } It just works by making a for-loop and calculating any objects that might collide with where the bullet currently is. This, of course, is very slow, and sometimes doesn't even work. What would be the preferred way to calculate where the bullet hits? I have thought of making a line and seeing if any objects collide with that line, but I have no idea how to do that kind of collision detection. EDIT: I guess my question is this: How do I calculate the nearest object colliding in a line (that might not be a straight 45/90 degree angle)? Or are there any simpler methods of calculating where the bullet hits? The bullet is sort of like a laser, in the sense that gravity does not affect it (writing an old-school game, so I don't want it to be too realistic)

    Read the article

  • How do I draw an OpenGL point sprite using libgdx for Android?

    - by nbolton
    Here's a few snippets of what I have so far... void create() { renderer = new ImmediateModeRenderer(); tiles = Gdx.graphics.newTexture( Gdx.files.getFileHandle("res/tiles2.png", FileType.Internal), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); } void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); Gdx.gl.glClearColor(0.6f, 0.7f, 0.9f, 1); } void renderSprite() { int handle = tiles.getTextureObjectHandle(); Gdx.gl.glBindTexture(GL.GL_TEXTURE_2D, handle); Gdx.gl.glEnable(GL.GL_POINT_SPRITE); Gdx.gl11.glTexEnvi(GL.GL_POINT_SPRITE, GL.GL_COORD_REPLACE, GL.GL_TRUE); renderer.begin(GL.GL_POINTS); renderer.vertex(pos.x, pos.y, pos.z); renderer.end(); } create() is called once when the program starts, and renderSprites() is called for each sprite (so, pos is unique to each sprite) where the sprites are arranged in a sort-of 3D cube. Unfortunately though, this just renders a few white dots... I suppose that the texture isn't being bound which is why I'm getting white dots. Also, when I draw my sprites on anything other than 0 z-axis, they do not appear -- I read that I need to crease my zfar and znear, but I have no idea how to do this using libgdx (perhaps it's because I'm using ortho projection? What do I use instead?). I know that the texture is usable, since I was able to render it using a SpriteBatch, but I guess I'm not using it properly with OpenGL.

    Read the article

  • Problem setting command-line console resolution. vbeinfo in grub2 does not report all resolutions

    - by Kent
    I have a Asus EEE PC 1005P which I installed a Command-line system on using the Alternate Installer CD of Ubuntu Lucid Lynx. Altough I think this is a general linux and grub2 question. I do not have (or want) the X Window System installed. I want to change my console screen resolution (not inside X) to 1024x600. But it isn't reported when I use vbeinfo inside grub: grub> vbeinfo VBE info: version: 3.0 OEM software rev: 1.0 total memory: 8128 KiB List of compatible video modes: Legend: P=Packed pixel, D=Direct color, mask/pos=R/G/B/reserved 0x112: 640 x 480 x 32 Direct, mask: 8/8/8/8 pos: 16/8/0/24 0x114: 800 x 600 x 16 Direct, mask: 5/6/5/0 pos: 11/5/0/0 0x115: 800 x 600 x 32 Direct, mask: 8/8/8/8 pos: 16/8/0/24 0x101: 640 x 480 x 8 Packed 0x103: 800 x 600 x 8 Packed 0x111: 640 x 480 x 16 Direct, mask: 5/6/5/0 pos: 11/5/0/0 Configured VBE mode (vbe_mode) = ox101 grub> Relevant parts of sudo lspci -v: ... ... 00:02.0 VGA compatible controller: Intel Corporation N10 Family Integrated Graphics Controller Subsystem: ASUSTeK Computer Inc. Device 83ac Flags: bus master, fast devsel, latency 0, IRQ 28 ... Kernel driver in use: i915 Kernel modules: i915 00:02.1 Display controller: Intel Corporation N10 Family Integrated Graphics Controller Subsystem: ASUSTeK Computer Inc. Device 83ac Flags: bus master, fast devsel, latency 0, IRQ 28 ... ... ... Any ideas on how I can set the console resultion like I want it?

    Read the article

  • NRF Big Show 2011 -- Part 3

    - by David Dorf
    I'm back from the NRF show having been one of the lucky people who's flight was not canceled. The show was very crowded with a reported 20% increase in attendance and everyone seemed in high spirits. After two years of sluggish retail sales, things are really picking up and it was reflected in everyone's mood. The pop-up Disney Store in the Oracle booth was great and attracted lots of interest in their mobile POS. I know many attendees visited the Disney Store in Times Square to see the entire operation. It's an impressive two-story store that keeps kids engaged. The POS demonstration station, where most of our innovations were demoed, was always crowded. Unfortunately most of the demos used WiFi and the signals from other booths prevented anything from working reliably. Nevertheless, the demo team did an excellent job walking people through the scenarios and explaining how shopping is being impacted by mobile, analytics, and RFID. Big Show Links Disney uncovers its store magic Top 10 Things You Missed at the NRF Big Show 2011 Oracle Retail Stores Innovation Station at NRF Big Show 2011 (video) The buzz of the show was again around mobile solutions. Several companies are creating mobile POS using the iPod Touch, including integrations to Oracle POS for the following retailers: Disney Stores with InfoGain Victoria's Secret with InfoGain Urban Outfitters with Starmount The Gap with Global Bay Keeping with the mobile theme, the NRF release a revised version of their Mobile Blueprint at NRF. It will be posted to the NRF site very soon. The alternate payments section had a major rewrite that provides a great overview and proximity and remote payment technologies. NRF Mobile Blueprint Links New mobile blueprint provides fresh insights NRF Mobile Blueprint 2011 (slides) I hope to do some posts on some of the interesting companies I spoke with in the coming weeks.

    Read the article

  • How to Upload a file from client to server using OFBIZ?

    - by SIVAKUMAR.J
    Hi all, Im new to ofbiz.So is my question is have any mistake forgive me for my mistakes.Im new to ofbiz so i did not know some terminologies in ofbiz.Sometimes my question is not clear because of lack of knowledge in ofbiz.So try to understand my question and give me a good solution with respect to my level.Because some solutions are in very high level cannot able to understand for me.So please give the solution with good examples. My problem is i created a project inside the ofbiz/hot-deploy folder namely "productionmgntSystem".Inside the folder "ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem" i created a .ftl file namely "app_details_1.ftl" .The following are the coding of this file <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script TYPE="TEXT/JAVASCRIPT" language=""JAVASCRIPT"> function uploadFile() { //alert("Before calling upload.jsp"); window.location='<@ofbizUrl>testing_service1</@ofbizUrl>' } </script> </head> <!-- <form action="<@ofbizUrl>testing_service1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> --> <form action="<@ofbizUrl>logout1</@ofbizUrl>" enctype="multipart/form-data" name="app_details_frm"> <center style="height: 299px; "> <table border="0" style="height: 177px; width: 788px"> <tr style="height: 115px; "> <td style="width: 103px; "> <td style="width: 413px; "><h1>APPLICATION DETAILS</h1> <td style="width: 55px; "> </tr> <tr> <td style="width: 125px; ">Application name : </td> <td> <input name="app_name_txt" id="txt_1" value=" " /> </td> </tr> <tr> <td style="width: 125px; ">Excell sheet &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: </td> <td> <input type="file" name="filename"/> </td> </tr> <tr> <td> <!-- <input type="button" name="logout1_cmd" value="Logout" onclick="logout1()"/> --> <input type="submit" name="logout_cmd" value="logout"/> </td> <td> <!-- <input type="submit" name="upload_cmd" value="Submit" /> --> <input type="button" name="upload1_cmd" value="Upload" onclick="uploadFile()"/> </td> </tr> </table> </center> </form> </html> the following coding is present in the file "ofbiz\hot-deploy\productionmgntSystem\webapp\productionmgntSystem\WEB-INF\controller.xml" ...... ....... ........ <request-map uri="testing_service1"> <security https="true" auth="true"/> <event type="java" path="org.ofbiz.productionmgntSystem.web_app_req.WebServices1" invoke="testingService"/> <response name="ok" type="view" value="ok_view"/> <response name="exception" type="view" value="exception_view"/> </request-map> .......... ............ .......... <view-map name="ok_view" type="ftl" page="ok_view.ftl"/> <view-map name="exception_view" type="ftl" page="exception_view.ftl"/> ................ ............. ............. The following are the coding present in the file "ofbiz\hot-deploy\productionmgntSystem\src\org\ofbiz\productionmgntSystem\web_app_req\WebServices1.java" package org.ofbiz.productionmgntSystem.web_app_req; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException; public class WebServices1 { public static String testingService(HttpServletRequest request, HttpServletResponse response) { //int i=0; String result="ok"; System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- Start"); String contentType=request.getContentType(); System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- contentType : "+contentType); String str=new String(); // response.setContentType("text/html"); //PrintWriter writer; if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) { System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) after if (contentType != null)"); try { // writer=response.getWriter(); System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try Start"); DataInputStream in = new DataInputStream(request.getInputStream()); int formDataLength = request.getContentLength(); byte dataBytes[] = new byte[formDataLength]; int byteRead = 0; int totalBytesRead = 0; //this loop converting the uploaded file into byte code while (totalBytesRead < formDataLength) { byteRead = in.read(dataBytes, totalBytesRead,formDataLength); totalBytesRead += byteRead; } String file = new String(dataBytes); //for saving the file name String saveFile = file.substring(file.indexOf("filename=\"") + 10); saveFile = saveFile.substring(0, saveFile.indexOf("\n")); saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\"")); int lastIndex = contentType.lastIndexOf("="); String boundary = contentType.substring(lastIndex + 1,contentType.length()); int pos; //extracting the index of file pos = file.indexOf("filename=\""); pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; pos = file.indexOf("\n", pos) + 1; int boundaryLocation = file.indexOf(boundary, pos) - 4; int startPos = ((file.substring(0, pos)).getBytes()).length; int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length; //creating a new file with the same name and writing the content in new file FileOutputStream fileOut = new FileOutputStream("/"+saveFile); fileOut.write(dataBytes, startPos, (endPos - startPos)); fileOut.flush(); fileOut.close(); System.out.println("\n\n\t**********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - try End"); } catch(IOException ioe) { System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch IOException"); //ioe.printStackTrace(); return("exception"); } catch(Exception ex) { System.out.println("\n\n\t*********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) - Catch Exception"); return("exception"); } } else { System.out.println("\n\n\t********************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response) else part"); result="exception"; } System.out.println("\n\n\t*************************************\n\tInside WebServices1.testingService(HttpServletRequest request, HttpServletResponse response)- End"); return(result); } } I want to upload a file to the server.The file is get from user "<input type="file"..> tag in the "app_details_1.ftl" file & it is updated into the server by using the method "testingService(HttpServletRequest request, HttpServletResponse response)" in the class "WebServices1".But the file is not uploaded. Give me a good solution for uploading a file to the server. Thanks & Regards, Sivakumar.J

    Read the article

  • How do I align the bottom edges of two monitors with xrandr?

    - by denaje
    I have two outputs that I'd like to use on my laptop: LVDS1 - 1366x768 HDMI1 - 1920x1080 I set my monitors up like so: xrandr --output LVDS1 --auto --output HDMI1 --auto --right-of LVDS1 This is all well and good, but my laptop sits considerably lower than my external monitor, and with the top edges of the screens being aligned, it makes the jump from one screen to the other rather unintuitive. Is there a way I can align the bottom edges instead? I thought I could use the --pos flag to do this, but I have tried and not seen any difference (perhaps I do not know how to use it properly). EDIT: Solved. Thanks to tink's link, I deconstructed the Python script and discovered the way to do this is as follows: xrandr --output LVDS1 --pos 0x312 # 312 = 1280 - 768 xrandr --output HDMI1 --pos 1366x0 Not sure I understand exactly what the --pos flags are doing here, but it at least works!

    Read the article

  • Fog shader camera problem

    - by MaT
    I have some difficulties with my vertex-fragment fog shader in Unity. I have a good visual result but the problem is that the gradient is based on the camera's position, it moves as the camera moves. I don't know how to fix it. Here is the shader code. struct v2f { float4 pos : SV_POSITION; float4 grabUV : TEXCOORD0; float2 uv_depth : TEXCOORD1; float4 interpolatedRay : TEXCOORD2; float4 screenPos : TEXCOORD3; }; v2f vert(appdata_base v) { v2f o; o.pos = mul(UNITY_MATRIX_MVP, v.vertex); o.uv_depth = v.texcoord.xy; o.grabUV = ComputeGrabScreenPos(o.pos); half index = v.vertex.z; o.screenPos = ComputeScreenPos(o.pos); o.interpolatedRay = mul(UNITY_MATRIX_MV, v.vertex); return o; } sampler2D _GrabTexture; float4 frag(v2f IN) : COLOR { float3 uv = UNITY_PROJ_COORD(IN.grabUV); float dpth = UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture, uv)); dpth = LinearEyeDepth(dpth); float4 wsPos = (IN.screenPos + dpth * IN.interpolatedRay); // Here is the problem but how to fix it float fogVert = max(0.0, (wsPos.y - _Depth) * (_DepthScale * 0.1f)); fogVert *= fogVert; fogVert = (exp (-fogVert)); return fogVert; } Thanks a lot !

    Read the article

  • C++ and function pointers assessment: lack of inspiration

    - by OlivierDofus
    I've got an assessment to give to my students. It's about C++ and function pointers. Their skill is middle: it the first year of a programming school after bachelor. To give you something precise, here's a sample of a solution of one of 3 exercices they had to do in 30 minutes (the question was: "here's a version of a code that could be written with function pointers, write down the same thing but with function pointers"): typedef void (*fcPtr) (istream &); fcPtr ArrayFct [] = { Delete , Insert, Swap, Move }; void HandleCmd (const string && Cmd) { string AvalaibleCommands ("DISM"); string::size_type Pos; istringstream Flux (Cmd); char CodeOp; Flux >> CodeOp; Pos = AvalaibleCommands.find (toupper (CodeOp)); if (Pos != string::npos) { ArrayFct [Pos](Flux); } } Any idea where I could find some inspiration? Some of the students have understood the principles, even though it's very hard for them to write C++ code. I know them, I know they're clever, and I'm pretty sure they should be very good project managers. So, writing C++ code is not that important after all. Understanding is the most important part (IMHO). I'm wondering about maybe break the habits, and give half of the questions about the principle, or even better, give some sample in other language and ask them why it's better to use function pointers instead of classical programming (usually a big switch case). Any idea where I could look? Find some inspiration?

    Read the article

  • Unity3D: How to make the camera focus a moving game object with ITween?

    - by nathan
    I'm trying to write a solar system with Unity3D. Planets are sphere game objects rotating around another sphere game object representing the star. What i want to achieve is let the user click on a planet and then zoom the camera on this planet and then make the camera follow and keep it centered on the screen while it keep moving around the star. I decided to use iTween library and so far i was able to create the zoom effect using iTween.MoveUpdate. My problem is that the focused planet does not say properly centered as it moves. Here is the relevant part of my script: void Update () { if (Input.GetButtonDown("Fire1")) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, Mathf.Infinity, concernedLayers)) { selectedPlanet = hit.collider.gameObject; } } } void LateUpdate() { if (selectedPlanet != null) { Vector3 pos = selectedPlanet.transform.position; pos.z = selectedPlanet.transform.position.z - selectedPlanet.transform.localScale.z; pos.y = selectedPlanet.transform.position.y; iTween.MoveUpdate(Camera.main.gameObject, pos, 2); } } What do i need to add to this script to make the selected planet stay centered on the screen? I hosted my current project as a webplayer application so you see what's going wrong. You can access it here.

    Read the article

  • How do I draw a point sprite using OpenGL ES on Android?

    - by nbolton
    Edit: I'm using the GL enum, which is incorrect since it's not part of OpenGL ES (see my answer). I should have used GL10, GL11 or GL20 instead. Here's a few snippets of what I have so far... void create() { renderer = new ImmediateModeRenderer(); tiles = Gdx.graphics.newTexture( Gdx.files.getFileHandle("res/tiles2.png", FileType.Internal), TextureFilter.MipMap, TextureFilter.Linear, TextureWrap.ClampToEdge, TextureWrap.ClampToEdge); } void render() { Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); Gdx.gl.glClearColor(0.6f, 0.7f, 0.9f, 1); } void renderSprite() { int handle = tiles.getTextureObjectHandle(); Gdx.gl.glBindTexture(GL.GL_TEXTURE_2D, handle); Gdx.gl.glEnable(GL.GL_POINT_SPRITE); Gdx.gl11.glTexEnvi(GL.GL_POINT_SPRITE, GL.GL_COORD_REPLACE, GL.GL_TRUE); renderer.begin(GL.GL_POINTS); renderer.vertex(pos.x, pos.y, pos.z); renderer.end(); } create() is called once when the program starts, and renderSprites() is called for each sprite (so, pos is unique to each sprite) where the sprites are arranged in a sort-of 3D cube. Unfortunately though, this just renders a few white dots... I suppose that the texture isn't being bound which is why I'm getting white dots. Also, when I draw my sprites on anything other than 0 z-axis, they do not appear -- I read that I need to crease my zfar and znear, but I have no idea how to do this using libgdx (perhaps it's because I'm using ortho projection? What do I use instead?). I know that the texture is usable, since I was able to render it using a SpriteBatch, but I guess I'm not using it properly with OpenGL.

    Read the article

  • 3D rotation matrices deform object while rotating

    - by Kevin
    I'm writing a small 3D renderer (using an orthographic projection right now). I've run into some trouble with my 3D rotation matrices. They seem to squeeze my 3D object (a box primitive) at certain angles. Here's a live demo (only tested in Google Chrome): http://dl.dropbox.com/u/109400107/3D/index.html The box is viewed from the top along the Y axis and is rotating around the X and Z axis. These are my 3 rotation matrices (Only rX and rZ are being used): var rX = new Matrix([ [1, 0, 0], [0, Math.cos(radiants), -Math.sin(radiants)], [0, Math.sin(radiants), Math.cos(radiants)] ]); var rY = new Matrix([ [Math.cos(radiants), 0, Math.sin(radiants)], [0, 1, 0], [-Math.sin(radiants), 0, Math.cos(radiants)] ]); var rZ = new Matrix([ [Math.cos(radiants), -Math.sin(radiants), 0], [Math.sin(radiants), Math.cos(radiants), 0], [0, 0, 1] ]); Before projecting the verticies I multiply them by rZ and rX like so: vert1.multiply(rZ); vert1.multiply(rX); vert2.multiply(rZ); vert2.multiply(rX); vert3.multiply(rZ); vert3.multiply(rX); The projection itself looks like this: bX = (pos.x + (vert1.x*scale)); bY = (pos.y + (vert1.z*scale)); Where "pos.x" and "pos.y" is an offset for centering the box on the screen. I just can't seem to find a solution to this and I'm still relativly new to working with Matricies. You can view the source-code of the demo page if you want to see the whole thing.

    Read the article

  • How to automatically render all opaque meshes with a specific shader?

    - by dsilva.vinicius
    I have a specular outline shader that I want to be used on all opaque meshes of the scene whenever a specific camera renders. The shader is working properly when it is manually applied to some material. The shader is as follows: Shader "Custom/Outline" { Properties { _Color ("Main Color", Color) = (.5,.5,.5,1) _OutlineColor ("Outline Color", Color) = (1,0.5,0,1) _Outline ("Outline width", Range (0.0, 0.1)) = .05 _SpecColor ("Specular Color", Color) = (0.5, 0.5, 0.5, 1) _Shininess ("Shininess", Range (0.03, 1)) = 0.078125 _MainTex ("Base (RGB) Gloss (A)", 2D) = "white" {} } SubShader { Tags { "Queue"="Overlay" "RenderType"="Opaque" } Pass { Name "OUTLINE" Tags { "LightMode" = "Always" } Cull Off ZWrite Off // Uncomment to show outline always. //ZTest Always CGPROGRAM #pragma target 3.0 #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float3 normal : NORMAL; }; struct v2f { float4 pos : POSITION; float4 color : COLOR; }; float _Outline; float4 _OutlineColor; v2f vert(appdata v) { // just make a copy of incoming vertex data but scaled according to normal direction v2f o; o.pos = mul(UNITY_MATRIX_MVP, v.vertex); float3 norm = mul ((float3x3)UNITY_MATRIX_IT_MV, v.normal); float2 offset = TransformViewToProjection(norm.xy); o.pos.xy += offset * o.pos.z * _Outline; o.color = _OutlineColor; return o; } float4 frag(v2f fromVert) : COLOR { return fromVert.color; } ENDCG } UsePass "Specular/FORWARD" } FallBack "Specular" } The camera used fot the effect has just a script component which setups the shader replacement: using UnityEngine; using System.Collections; public class DetectiveEffect : MonoBehaviour { public Shader EffectShader; // Use this for initialization void Start () { this.camera.SetReplacementShader(EffectShader, "RenderType=Opaque"); } // Update is called once per frame void Update () { } } Unfortunately, whenever I use this camera I just see the background color. Any ideas?

    Read the article

  • Moving sprite from one vector to the other

    - by user2002495
    I'm developing a game where enemy can shoot bullets towards the player. I'm using 2 vector that is normalized later to determine where the bullets will go. Here is the code where enemy shoots: private void UpdateCommonBullet(GameTime gt) { foreach (CommonEnemyBullet ceb in bulletList) { ceb.pos += ceb.direction * 1.5f * (float)gt.ElapsedGameTime.TotalSeconds; if (ceb.pos.Y >= 600) ceb.hasFired = false; } for (int i = 0; i < bulletList.Count; i++) { if (!bulletList[i].hasFired) { bulletList.RemoveAt(i); i--; } } } And here is where i get the direction (in the constructor of the bullet): direction = Global.currentPos - this.pos; direction.Normalize(); Global.currentPos is a Vector2 where currently player is located, and is updated eveytime the player moves. This all works fine except that the bullet won't go to player's location. Instead, it tends goes to the "far right" of the player's position. I think it might be the problem where the bullet (this.pos in the direction) is created (at the position of the enemy). But I found no solution of it, please help me.

    Read the article

  • opengl, Black lines in-between tiles

    - by MiJyn
    When its translated in an integral value (1,2,3, etc....), there are no black lines in-between the tiles, it looks fine. But when it's translated to a non-integral (1.1, 1.5, 1.67), there are small blackish lines between each tile (I'm imagining that it's due to subpixel rendering, right?) ... and it doesn't look pretty =P So... what should I do? This is my image-loading code, by the way: bool Image::load_opengl() { this->id = 0; glGenTextures(1, &this->id); this->bind(); // Parameters... TODO: Should we change this? glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, this->size.x, this->size.y, 0, GL_BGRA, GL_UNSIGNED_BYTE, (void*) FreeImage_GetBits(this->data)); this->unbind(); return true; } I've also tried using: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); and: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); Here is my image drawing code: void Image::draw(Pos pos, CROP crop, SCALE scale) { if (!this->loaded || this->id == 0) { return; } // Start position & size Pos s_p; Pos s_s; // End size Pos e_s; if (crop.active) { s_p = crop.pos / this->size; s_s = crop.size / this->size; //debug("%f %f", s_s.x, s_s.y); s_s = s_s + s_p; s_s.clamp(1); //debug("%f %f", s_s.x, s_s.y); } else { s_s = 1; } if (scale.active) { e_s = scale.size; } else if (crop.active) { e_s = crop.size; } else { e_s = this->size; } // FIXME: Is this okay? s_p.y = 1 - s_p.y; s_s.y = 1 - s_s.y; // TODO: Make this use VAO/VBO's!! glPushMatrix(); glTranslate(pos.x, pos.y, 0); this->bind(); glBegin(GL_QUADS); glTexCoord2(s_p.x, s_p.y); glVertex2(0, 0); glTexCoord2(s_s.x, s_p.y); glVertex2(e_s.x, 0); glTexCoord2(s_s.x, s_s.y); glVertex2(e_s.x, e_s.y); glTexCoord2(s_p.x, s_s.y); glVertex2(0, e_s.y); glEnd(); this->unbind(); glPopMatrix(); } OpenGL Initialization code: void game__gl_init() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, config.window.size.x, config.window.size.y, 0.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glEnable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } Screenshots of the issue:

    Read the article

  • Is it bad form to stage a function's steps in intermediate variables (let bindings)?

    - by octopusgrabbus
    I find I tend to need intermediate variables. In Clojure that's in the form of let bindings, like cmp-result-1 and cmp-result-2 in the following function. (defn str-cmp "Takes two strings and compares them. Returns the string if a match; and nil if not." [str-1 str-2 start-pos substr-len] (let [cmp-result-1 (subs str-1 start-pos substr-len) cmp-result-2 (subs str-2 start-pos substr-len)] (compare cmp-result-1 cmp-result-2))) I could re-write this function without them, but to me, the function's purpose looks clearer. I tend to do this quite in a bit in my main, and that is primarily for debugging purposes, so I can pass a variable to print out intermediate output. Is this bad form, and, if so, why? Thanks.

    Read the article

  • What are the steps taken by this GLSL code?

    - by user827992
    1 void main(void) 2 { 3 vec2 pos = mod(gl_FragCoord.xy, vec2(50.0)) - vec2(25.0); 4 float dist_squared = dot(pos, pos); 5 6 gl_FragColor = (dist_squared < 400.0) 7 ? vec4(.90, .90, .90, 1.0) 8 : vec4(.20, .20, .40, 1.0); 9 } taken from http://people.freedesktop.org/~idr/OpenGL_tutorials/03-fragment-intro.html Now, this looks really trivial and simple, but my problem is with the mod function. This function is taking 2 vec2 as inputs but is supposed to take just 2 atomic arguments according to the official documentation, also this function makes an implicit use of the floor function that only accepts, again, 1 atomic argument. Can someone explain this to me step by step and point out what I'm not getting here? It's some kind of OpenGL trick? OpenGL Math trick? in the GLSL docs i always find and explicit reference to the type accepted by the function and vec2 it's not there.

    Read the article

  • how to insert multiple characters into a string in C [closed]

    - by John Li
    I wish to insert some characters into a string in C: Example: char string[20] = "20120910T090000"; I want to make it something like "2012-09-10-T-0900-00" My code so far: void append(char subject[],char insert[], int pos) { char buf[100]; strncpy(buf, subject, pos); int len = strlen(buf); strcpy(buf+len, insert); len += strlen(insert); strcpy(buf+len, subject+pos); strcpy(subject, buf); } When I call this the first time I get: 2012-0910T090000 However when I call it a second time I get: 2012-0910T090000-10T090000 Any help is appreciated

    Read the article

  • jQuery UI Tabs Plugin Broke

    - by Warren J Thompson
    We are using the jquery ui tabs arrow plugin from this fiddle: http://jsfiddle.net/dECtZ/282/, but like many plugins, it breaks with the latest version of jQuery. We were able to get the csscur to work, but still get the following error in the jquery core (line 353): Uncaught TypeError: Cannot assign to read only property 'length' of function (e,t){if(!this._createWidget)return new o(e,t);arguments.length&&this._createWidget(e,t)} Code is as follows: (function($, undefined) { if (!$.xui) { $.xui = {}; } var tabs = $.extend({}, $.ui.tabs.prototype), _super = { _create: tabs._create, _destroy: tabs._destroy, _update: tabs._update }; $.xui.tabs = $.extend(tabs, { options: $.extend({}, tabs.options, { scrollable: false, changeOnScroll: false, closable: false, resizable: false, resizeHandles: "e,s,se" }), _create: function() { var self = this, o = self.options; _super._create.apply(self); if (o.scrollable) { self.element.addClass("ui-tabs-scrollable"); var scrollContainer = $('<div class="ui-tabs-scroll-container"></div>').prependTo(this.element); self.header = $('<div class="ui-tabs-nav-scrollable ui-widget-header ui-corner-all"></div>').prependTo(scrollContainer); var nav = self.element.find(".ui-tabs-nav:first").removeClass("ui-widget-header ui-corner-all").appendTo(this.header); var arrowsNav = $('<ol class="ui-helper-reset ui-helper-clearfix ui-tabs-nav-arrows"></ol>').prependTo(self.element); var navPrev = $('<li class="ui-tabs-arrow-previous ui-state-default ui-corner-bl ui-corner-tl" title="Previous"><a href="#"><span class="ui-icon ui-icon-carat-1-w">Previous tab</span></a></li>').prependTo(arrowsNav).hide(), navNext = $('<li class="ui-tabs-arrow-next ui-state-default ui-corner-tr ui-corner-br" title="Next"><a href="#"><span class="ui-icon ui-icon-carat-1-e">Next tab</span></a></li>').appendTo(arrowsNav).hide(); var scrollTo = function(to, delay) { var navWidth = 0, arrowWidth = navPrev.outerWidth(), marginLeft = -(parseInt(nav.css("marginLeft"), 10)), hwidth = self.header.width(), newMargin = 0; nav.find("li").each(function() { navWidth += $(this).outerWidth(true); }); if (to instanceof $.Event) { } else { newMargin = marginLeft+to; if (newMargin > (navWidth-hwidth)) { newMargin = (navWidth-hwidth); } else if (newMargin < 0) { newMargin = 0; } nav.stop(true).animate({ marginLeft: -(newMargin) }, delay, function(){ $(window).trigger("resize.tabs"); }); } } var holdTimer = false; navPrev.add(navNext).bind({ "click": function(e) { var isNext = this === navNext[0]; e.preventDefault(); if (o.changeOnScroll) { self.select(self.options.selected + (isNext ? 1 : -1)); } else { if (!holdTimer) scrollTo(isNext ? 150 : -150, 250); } }, "mousedown": function(e){ if (!o.changeOnScroll) { var isNext = this === navNext[0], duration = 10, pos = 15, timer; if (holdTimer) clearTimeout(holdTimer); holdTimer = setTimeout(timer = function(){ scrollTo(isNext ? pos : -(pos), duration); holdTimer = setTimeout(arguments.callee, duration); }, 150); } }, "mouseup mouseout": function(e){ if (!o.changeOnScroll) { clearTimeout(holdTimer); holdTimer = false; nav.stop(); } } }); self.header.bind('mousewheel', function(e, d, dX, dY) { e.preventDefault(); if (d === -1) { navNext.click(); } else if (d === 1) { navPrev.click(); } }); $(window).bind("resize.tabs", function(e) { var navWidth = 0; var arrowWidth = navPrev.outerWidth(); nav.find("li").each(function() { navWidth += $(this).outerWidth(true); }); var marginLeft = -(parseInt(nav.css("marginLeft"), 10)), hwidth = self.header.width(); if (navWidth > (hwidth+marginLeft)) { self.header.addClass("ui-tabs-arrow-r"); navNext.show("fade"); if (marginLeft > 0) { self.header.addClass("ui-tabs-arrow-l"); navPrev.show("fade"); } else { self.header.removeClass("ui-tabs-arrow-l"); navPrev.hide("fade"); } } else { self.header.removeClass("ui-tabs-arrows ui-tabs-arrow-l"); navNext.hide("fade"); if (marginLeft > 0) { self.header.addClass("ui-tabs-arrow-l"); navPrev.show("fade"); } else { self.header.removeClass("ui-tabs-arrow-l"); navPrev.hide("fade"); } } }).trigger("resize.tabs"); arrowsNav.find("li").bind({ "mouseenter focus": function(e) { $(this).addClass("ui-state-hover"); }, "mouseleave blur": function(e) { $(this).removeClass("ui-state-hover"); } }); this.anchors.bind("click.tabs", function(){ var li = $(this).parent(), arrowWidth = navPrev.outerWidth(), width = li.outerWidth(true), hwidth = self.header.width(), pos = li.position().left, marginLeft = -(parseInt(nav.stop(true,true).css("marginLeft"),10)), newMargin = -1; if (li.index() === 0) { newMargin = 0; } else if ((pos+width) >= (hwidth+marginLeft)) { newMargin = pos-hwidth+width; if ((li.index()+1) < nav.find("li").length) { newMargin += arrowWidth; } } else if (pos < marginLeft) { newMargin = pos-arrowWidth; } if (newMargin > -1) { nav.animate({ marginLeft: -(newMargin) }, 250, function(){ $(window).trigger("resize.tabs"); }); } }); } return self; }, _update: function(){ console.log(arguments); _super._update.apply(this); } }); $.widget("xui.tabs", $.xui.tabs); })(jQuery); $(function() { $("#tabs").tabs({ scrollable: true, changeOnScroll: false, closable: true }); $("#switcher").themeswitcher(); });

    Read the article

  • Problem with room/screen/menu controller in python game: old rooms are not removed from memory

    - by Jordan Magnuson
    I'm literally banging my head against a wall here (as in, yes, physically, at my current location, I am damaging my cranium). Basically, I've got a Python/Pygame game with some typical game "rooms", or "screens." EG title screen, high scores screen, and the actual game room. Something bad is happening when I switch between rooms: the old room (and its various items) are not removed from memory, or from my event listener. Not only that, but every time I go back to a certain room, my number of event listeners increases, as well as the RAM being consumed! (So if I go back and forth between the title screen and the "game room", for instance, the number of event listeners and the memory usage just keep going up and up. The main issue is that all the event listeners start to add up and really drain the CPU. I'm new to Python, and don't know if I'm doing something obviously wrong here, or what. I will love you so much if you can help me with this! Below is the relevant source code. Complete source code at http://www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip MAIN.PY class RoomController(object): """Controls which room is currently active (eg Title Screen)""" def __init__(self, screen, ev_manager): self.room = None self.screen = screen self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.room = self.set_room(config.room) def set_room(self, room_const): #Unregister old room from ev_manager if self.room: self.room.ev_manager.unregister_listener(self.room) self.room = None #Set new room based on const if room_const == config.TITLE_SCREEN: return rooms.TitleScreen(self.screen, self.ev_manager) elif room_const == config.GAME_MODE_ROOM: return rooms.GameModeRoom(self.screen, self.ev_manager) elif room_const == config.GAME_ROOM: return rooms.GameRoom(self.screen, self.ev_manager) elif room_const == config.HIGH_SCORES_ROOM: return rooms.HighScoresRoom(self.screen, self.ev_manager) def notify(self, event): if isinstance(event, ChangeRoomRequest): if event.game_mode: config.game_mode = event.game_mode self.room = self.set_room(event.new_room) #Run game def main(): pygame.init() screen = pygame.display.set_mode(config.screen_size) ev_manager = EventManager() spinner = CPUSpinnerController(ev_manager) room_controller = RoomController(screen, ev_manager) pygame_event_controller = PyGameEventController(ev_manager) spinner.run() EVENT_MANAGER.PY class EventManager: #This object is responsible for coordinating most communication #between the Model, View, and Controller. def __init__(self): from weakref import WeakKeyDictionary self.last_listeners = {} self.listeners = WeakKeyDictionary() self.eventQueue= [] self.gui_app = None #---------------------------------------------------------------------- def register_listener(self, listener): self.listeners[listener] = 1 #---------------------------------------------------------------------- def unregister_listener(self, listener): if listener in self.listeners: del self.listeners[listener] #---------------------------------------------------------------------- def clear(self): del self.listeners[:] #---------------------------------------------------------------------- def post(self, event): # if isinstance(event, MouseButtonLeftEvent): # debug(event.name) #NOTE: copying the list like this before iterating over it, EVERY tick, is highly inefficient, #but currently has to be done because of how new listeners are added to the queue while it is running #(eg when popping cards from a deck). Should be changed. See: http://dr0id.homepage.bluewin.ch/pygame_tutorial08.html #and search for "Watch the iteration" print 'Number of listeners: ' + str(len(self.listeners)) for listener in list(self.listeners): #NOTE: If the weakref has died, it will be #automatically removed, so we don't have #to worry about it. listener.notify(event) def notify(self, event): pass #------------------------------------------------------------------------------ class PyGameEventController: """...""" def __init__(self, ev_manager): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.input_freeze = False #---------------------------------------------------------------------- def notify(self, incoming_event): if isinstance(incoming_event, UserInputFreeze): self.input_freeze = True elif isinstance(incoming_event, UserInputUnFreeze): self.input_freeze = False elif isinstance(incoming_event, TickEvent) or isinstance(incoming_event, BoardCreationTick): #Share some time with other processes, so we don't hog the cpu pygame.time.wait(5) #Handle Pygame Events for event in pygame.event.get(): #If this event manager has an associated PGU GUI app, notify it of the event if self.ev_manager.gui_app: self.ev_manager.gui_app.event(event) #Standard event handling for everything else ev = None if event.type == QUIT: ev = QuitEvent() elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze: if event.button == 1: #Button 1 pos = pygame.mouse.get_pos() ev = MouseButtonLeftEvent(pos) elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze: if event.button == 2: #Button 2 pos = pygame.mouse.get_pos() ev = MouseButtonRightEvent(pos) elif event.type == pygame.MOUSEBUTTONUP and not self.input_freeze: if event.button == 2: #Button 2 Release pos = pygame.mouse.get_pos() ev = MouseButtonRightReleaseEvent(pos) elif event.type == pygame.MOUSEMOTION: pos = pygame.mouse.get_pos() ev = MouseMoveEvent(pos) #Post event to event manager if ev: self.ev_manager.post(ev) # elif isinstance(event, BoardCreationTick): # #Share some time with other processes, so we don't hog the cpu # pygame.time.wait(5) # # #If this event manager has an associated PGU GUI app, notify it of the event # if self.ev_manager.gui_app: # self.ev_manager.gui_app.event(event) #------------------------------------------------------------------------------ class CPUSpinnerController: def __init__(self, ev_manager): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.clock = pygame.time.Clock() self.cumu_time = 0 self.keep_going = True #---------------------------------------------------------------------- def run(self): if not self.keep_going: raise Exception('dead spinner') while self.keep_going: time_passed = self.clock.tick() fps = self.clock.get_fps() self.cumu_time += time_passed self.ev_manager.post(TickEvent(time_passed, fps)) if self.cumu_time >= 1000: self.cumu_time = 0 self.ev_manager.post(SecondEvent(fps=fps)) pygame.quit() #---------------------------------------------------------------------- def notify(self, event): if isinstance(event, QuitEvent): #this will stop the while loop from running self.keep_going = False EXAMPLE CLASS USING EVENT MANAGER class Timer(object): def __init__(self, ev_manager, time_left): self.ev_manager = ev_manager self.ev_manager.register_listener(self) self.time_left = time_left self.paused = False def __repr__(self): return str(self.time_left) def pause(self): self.paused = True def unpause(self): self.paused = False def notify(self, event): #Pause Event if isinstance(event, Pause): self.pause() #Unpause Event elif isinstance(event, Unpause): self.unpause() #Second Event elif isinstance(event, SecondEvent): if not self.paused: self.time_left -= 1

    Read the article

< Previous Page | 2 3 4 5 6 7 8 9 10 11 12 13  | Next Page >