Search Results

Search found 637 results on 26 pages for 'p1'.

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

  • Basic collision direction detection on 2d objects

    - by Osso Buko
    I am trying to develop a platform game for Android by using ANdroid GL Engine (ANGLE). And I am having trouble with collision detection. I have two objects which is shaped as rectangular. And no change in rotation. Here is a scheme of attributes of objects. What i am trying to do is when objects collide they block each other's movement on that direction. Every object has 4 boolean (bTop, bBottom, bRight, bLeft). For example when bBottom is true object can't advance on that direction. I came up with a solution but it seems it only works on one dimensional. Bottom and top or right and left. public void collisionPlatform (MyObject a, MyObject b) { // first obj is player and second is a wall or a platform Vector p1 = a.mPosition; // p1 = middle point of first object Vector d1 = a.mPosition2; // width(mX) and height of first object Vector mSpeed1 = a.mSpeed; // speed vector of first object Vector p2 = b.mPosition; // p1 = middle point of second object Vector d2 = b.mPosition2; // width(mX) and height of second object Vector mSpeed2 = b.mSpeed; // speed vector of second object float xDist, yDist; // distant between middle of two object float width , height; // this is average of two objects measurements width=(width1+width2)/2 xDist=(p1.mX - p2.mX); // calculate distance // if positive first object is at the right yDist=(p1.mY - p2.mY); // if positive first object is below width = d1.mX + d2.mX; // average measurements calculate height = d1.mY + d2.mY; width/=2; height/=2; if (Math.abs(xDist) < width && Math.abs(yDist) < height) { // Two object is collided if(p1.mY>p2.mY) { // first object is below second one a.bTop = true; if(a.mSpeed.mY<0) a.mSpeed.mY=0; b.bBottom = true; if(b.mSpeed.mY>0) b.mSpeed.mY=0; } else { a.bBottom = true; if(a.mSpeed.mY>0) a.mSpeed.mY=0; b.bTop = true; if(b.mSpeed.mY<0) b.mSpeed.mY=0; } } As seen in my code it simply will not work. when object comes from right or left it doesn't work. I tried couple of ways other than this one but none worked. I am guessing right method will include mSpeed vector. But I have no idea how to do it. I really appreciate if you could help. Sorry for my bad english.

    Read the article

  • graph with database

    - by Flip_novidade
    I need to make two graphs with data coming from the database. I do not know where I am going wrong. If someone can show me the correct way, or provide any examples. must be two graphs, a graph of a specific student another graph of all students thank you public class NotasBean { private Notas notas; private Notas selectedNotas; private List<Notas> filtroNotass; public Notas getNotas() { return notas; } public void setNotas(Notas notas) { this.notas = notas; } public Notas getSelectedNotas() { return selectedNotas; } public void setSelectedNotas(Notas selectedNotas) { this.selectedNotas = selectedNotas; } public List<Notas> getFiltroNotass() { return filtroNotass; } public void setFiltroNotass(List<Notas> filtroNotass) { this.filtroNotass = filtroNotass; } public void prepararAdicionarNotas(){ notas = new Notas(); } public void adicionarNotas(){ dao.NotasDao obj_dao = new dao.NotasDao(); obj_dao.save(notas); } } package dao; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import model.Aluno; import model.Notas; import model.Notas; public class NotasDao { private Conexao obj_conexao; public NotasDao() { obj_conexao = new Conexao(); } public List<Notas> list() { List<Notas> array_registros = new ArrayList<Notas>(); try { String sql = "Select alu_in_ra, dis_st_sigla, ald_fl_p1, ald_fl_p2, ald_fl_p3, ald_fl_trab1, ald_fl_trab2 from cad_aluno_disciplina"; Statement comando_sql = (Statement) obj_conexao.getConexao() .createStatement(); ResultSet obj_result = comando_sql.executeQuery(sql); while (obj_result.next()) { Notas obj_notas = new Notas(); obj_notas.setAlura(obj_result.getInt("alu_in_ra")); obj_notas.setDiscsigla(obj_result.getString("dis_st_sigla")); obj_notas.setP1(obj_result.getInt("ald_fl_p1")); obj_notas.setP2(obj_result.getInt("ald_fl_p2")); obj_notas.setP3(obj_result.getInt("ald_fl_p3")); obj_notas.setTrb1(obj_result.getInt("ald_fl_trab1")); obj_notas.setTrb2(obj_result.getInt("ald_fl_trab2")); array_registros.add(obj_notas); } } catch (Exception e) { System.out.println("Erro no select" + e.getMessage()); } finally { obj_conexao.fecharConexao(); } return array_registros; } public void select(Aluno obj_aluno){ FacesContext mensagem = FacesContext.getCurrentInstance(); try{ String comando_sql = "Select alu_in_ra, dis_st_sigla, ald_fl_p1, ald_fl_p2, ald_fl_p3, ald_fl_trab1, ald_fl_trab2 from cad_aluno_disciplina where alu_in_ra=?"; PreparedStatement obj_sql = (PreparedStatement) obj_conexao.getConexao().prepareStatement(comando_sql); obj_sql.setInt(1, obj_aluno.getRa()); obj_sql.executeUpdate(); mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Erro ao selecionar aluno!","Snif")); }catch(Exception e){ mensagem.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Erro na inclusão: "+e.getMessage()," Ocoreu o erro: "+e.getMessage())); }finally{ obj_conexao.fecharConexao(); } return; } }//fecha a classe package model; import java.io.Serializable; public class Notas implements Serializable{ private static final long serialVersionUID = 1L; private int alura; private String discsigla; private float p1; private float p2; private float p3; private float trb1; private float trb2; public Notas() { } public Notas (int alura, String discsigla, float p1, float p2, float p3, float trb1, float trb2){ super(); this.alura=alura; this.discsigla=discsigla; this.p1=p1; this.p2=p2; this.p3=p3; this.trb1=trb1; this.trb2=trb2; } public int getAlura() { return alura; } public void setAlura(int alura) { this.alura = alura; } public String getDiscsigla() { return discsigla; } public void setDiscsigla(String discsigla) { this.discsigla = discsigla; } public float getP1() { return p1; } public void setP1(float p1) { this.p1 = p1; } public float getP2() { return p2; } public void setP2(float p2) { this.p2 = p2; } public float getP3() { return p3; } public void setP3(float p3) { this.p3 = p3; } public float getTrb1() { return trb1; } public void setTrb1(float trb1) { this.trb1 = trb1; } public float getTrb2() { return trb2; } public void setTrb2(float trb2) { this.trb2 = trb2; } } <p:panel header="Grafico Notas Aluno" style="width: 550px"> <p:lineChart id="linear" value="#{notasDao.aluno.alura}" var="notas" xfield="#{notas.alura}" height="300px" width="500px" style="chartStyle"> <p:chartSeries label="Prova 1" value="#{notas.p1}" /> <p:chartSeries label="Prova 2" value="#{notas.p2}" /> <p:chartSeries label="Prova 3" value="#{notas.p3}" /> <p:chartSeries label="Trabalho 1" value="#{notas.trb1}" /> <p:chartSeries label="Trabalho 2" value="#{notas.trb2}" /> </p:lineChart> </p:panel> <p:panel header="Grafico Notas" style="width: 550px"> <p:lineChart id="linear" value="#{notasDao.natas}" var="notas" xfield="#{notas.p1}" height="300px" width="500px" style="chartStyle"> <p:chartSeries label="Prova 1" value="#{notas.p1}" /> <p:chartSeries label="Prova 2" value="#{notas.p2}" /> <p:chartSeries label="Prova 3" value="#{notas.p3}" /> <p:chartSeries label="Trabalho 1" value="#{notas.trb1}" /> <p:chartSeries label="Trabalho 2" value="#{notas.trb2}" /> </p:lineChart> </p:panel>

    Read the article

  • consistency of Trigger Procedure (before row trigger) Postgresql

    - by elgcom
    Using Postgresql. I try to use TRIGGER procedure to make some consistency check on INSERT. The question is ...... whether "BEFORE INSERT FOR EACH ROW" can make sure each row to insert "checked" and "inserted" one after another? do I need extra lock on table to survive from concurrent insert? check for new row1 - insert row1 - check for new row2 - insert row2 -- -- -- unexpired product name is unique. CREATE TABLE product ( "name" VARCHAR(100) NOT NULL, "expired" BOOLEAN NOT NULL ); CREATE OR REPLACE FUNCTION check_consistency() RETURNS TRIGGER AS $$ BEGIN IF EXISTS (SELECT * FROM product WHERE name=NEW.name AND expired='false') THEN RAISE EXCEPTION 'duplicated!!!'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER trigger_check_consistency BEFORE INSERT ON product FOR EACH ROW EXECUTE PROCEDURE check_consistency(); -- INSERT INTO product VALUES("prod1", true); INSERT INTO product VALUES("prod1", false); INSERT INTO product VALUES("prod1", false); // exception! this is OK name | expired ============== p1 | true p1 | true p1 | false This is not OK name | expired ============== p1 | true p1 | false p1 | false or maybe I should ask, how can I use Trigger to implement "Primary" or "Unique" constraint-like SQL.

    Read the article

  • Need of optimized code for hide and show div in jQuery

    - by novellino
    Hello, I have a div: <div id="p1" class="img-projects" style="margin-left:0;"> <a href="project1.php"> <img src="image1.png"/></a> <div id="p1" class="project-title">Bar Crawler</div> </div> On mouse-over I want to add an image with opacity and make the project-title shown. So I use this code: <script type="text/javascript"> $(function() { $('.project-title').hide(); $('#p1.img-projects img').mouseover( function() { $(this).stop().animate({ opacity: 0.3 }, 800); $('#p1.project-title').fadeIn(500); }); $('#p1.img-projects img').mouseout( function() { $(this).stop().animate({ opacity: 1.0 }, 800); $('#p1.project-title').fadeOut(); }); $('#p2.img-projects img').mouseover( function() { $(this).stop().animate({ opacity: 0.3 }, 800); $('#p2.project-title').fadeIn(500); }); $('#p2.img-projects img').mouseout( function() { $(this).stop().animate({ opacity: 1.0 }, 800); $('#p2.project-title').fadeOut(); }); }); </script> The code works fine but does anyone know a way to optimize my code? Thank you

    Read the article

  • C++ const qualifier

    - by avd
    I have a Point2D class as follows: class Point2D{ int x; int y; public: Point2D(int inX, int inY){ x = inX; y = inY; }; int getX(){return x;}; int getY(){return y;}; }; Now I have defined a class Line as: class Line { Point2D p1,p2; public: LineVector(const Point2D &p1,const Point2D &p2):p1(p1),p2(p2) { int x1,y1,x2,y2; x1=p1.getX();y1=p1.getY();x2=p2.getX();y2=p2.getY(); } }; Now the compiler gives the error in the last line( where getX() etc are called): error: passing `const Point2D' as `this' argument of `int Point2D::getX()' discards qualifiers If I remove the const keyword at both places, then it compiles successfully. What is the error? Is it because getX() etc are defined inline? Is there any way to recify this retaining them inline?

    Read the article

  • Finding Z given X & Y coordinates on terrain?

    - by mrky
    I need to know what the most efficient way of finding Z given X & Y coordinates on terrain. My terrain is set up as a grid, each grid block consisting of two triangles, which may be flipped in any direction. I want to move game objects smoothly along the floor of the terrain without "stepping." I'm currently using the following method with unexpected results: double mapClass::getZ(double x, double y) { int vertexIndex = ((floor(y))*width*2)+((floor(x))*2); vec3ray ray = {glm::vec3(x, y, 2), glm::vec3(x, y, 0)}; vec3triangle tri1 = { glmFrom(vertices[vertexIndex].v1), glmFrom(vertices[vertexIndex].v2), glmFrom(vertices[vertexIndex].v3) }; vec3triangle tri2 = { glmFrom(vertices[vertexIndex+1].v1), glmFrom(vertices[vertexIndex+1].v2), glmFrom(vertices[vertexIndex+1].v3) }; glm::vec3 intersect; if (!intersectRayTriangle(tri1, ray, intersect)) { intersectRayTriangle(tri2, ray, intersect); } return intersect.z; } intersectRayTriangle() and glmFrom() are as follows: bool intersectRayTriangle(vec3triangle tri, vec3ray ray, glm::vec3 &worldIntersect) { glm::vec3 barycentricIntersect; if (glm::intersectLineTriangle(ray.origin, ray.direction, tri.p0, tri.p1, tri.p2, barycentricIntersect)) { // Convert barycentric to world coordinates double u, v, w; u = barycentricIntersect.x; v = barycentricIntersect.y; w = 1 - (u+v); worldIntersect.x = (u * tri.p0.x + v * tri.p1.x + w * tri.p2.x); worldIntersect.y = (u * tri.p0.y + v * tri.p1.y + w * tri.p2.y); worldIntersect.z = (u * tri.p0.z + v * tri.p1.z + w * tri.p2.z); return true; } else { return false; } } glm::vec3 glmFrom(s_point3f point) { return glm::vec3(point.x, point.y, point.z); } My convenience structures are defined as: struct s_point3f { GLfloat x, y, z; }; struct s_triangle3f { s_point3f v1, v2, v3; }; struct vec3ray { glm::vec3 origin, direction; }; struct vec3triangle { glm::vec3 p0, p1, p2; }; vertices is defined as: std::vector<s_triangle3f> vertices; Basically, I'm trying to get the intersect of a ray (which is positioned at the x, and y coordinates specified facing pointing downwards toward the terrain) and one of the two triangles on the grid. getZ() rarely returns anything but 0. Other times, the numbers it generates seem to be completely off. Am I taking the wrong approach? Can anyone see a problem with my code? Any help or critique is appreciated!

    Read the article

  • FluentNhibernate many-to-many mapping - resolving record is not inserted

    - by Dmitriy Nagirnyak
    Hi, I have a many-to-many mapping defined (only relevant fields included): // MODEL: public class User : IPersistentObject { public User() { Permissions = new HashedSet<Permission>(); } public virtual int Id { get; protected set; } public virtual ISet<Permission> Permissions { get; set; } } public class Permission : IPersistentObject { public Permission() { } public virtual int Id { get; set; } } // MAPPING: public class UserMap : ClassMap<User> { public UserMap() { Id(x => x.Id); HasManyToMany(x => x.Permissions).Cascade.All().AsSet(); } } public class PermissionMap : ClassMap<Permission> { public PermissionMap() { Id(x => x.Id).GeneratedBy.Assigned(); Map(x => x.Description); } } The following test fails as there is no record inserted into User_Permission table: [Test] public void AddingANewUserPrivilegeShouldSaveIt() { var p1 = new Permission { Id = 123, Description = "p1" }; Session.Save(p1); var u = new User { Email = "[email protected]" }; u.Permissions.Add(p1); Session.Save(u); var userId = u.Id; Session.Evict(u); Session.Get<User>(userId).Permissions.Should().Not.Be.Empty(); } The SQL executed is (SQLite): INSERT INTO "Permission" (Description, Id) VALUES (@p0, @p1);@p0 = 'p1', @p1 = 1 INSERT INTO "User" (Email) VALUES (@p0); select last_insert_rowid();@p0 = '[email protected]' SELECT user0_.Id as Id2_0_, user0_.Email as Email2_0_ FROM "User" user0_ WHERE user0_.Id=@p0;@p0 = 1 SELECT permission0_.UserId as UserId1_, permission0_.PermissionId as Permissi2_1_, permission1_.Id as Id4_0_, permission1_.Description as Descript2_4_0_ FROM User_Permissions permission0_ left outer join "Permission" permission1_ on permission0_.PermissionId=permission1_.Id WHERE permission0_.UserId=@p0;@p0 = 1 We can clearly see that there is no record inserted into the User_Permissions table where it should be. Not sure what I am doing wrong and need an advice. So can you please help me to pass this test. Thanks, Dmitriy.

    Read the article

  • Can you pass by reference in Java?

    - by dbones
    Hi. Sorry if this sounds like a newbie question, but the other day a Java developer mentioned about passing a paramter by reference (by which it was ment just pass a Reference object) From a C# perspective I can pass a reference type by value or by reference, this is also true to value types I have written a noddie console application to show what i mean.. can i do this in Java? namespace ByRefByVal { class Program { static void Main(string[] args) { //Creating of the object Person p1 = new Person(); p1.Name = "Dave"; PrintIfObjectIsNull(p1); //should not be null //A copy of the Reference is made and sent to the method PrintUserNameByValue(p1); PrintIfObjectIsNull(p1); //the actual reference is passed to the method PrintUserNameByRef(ref p1); //<-- I know im passing the Reference PrintIfObjectIsNull(p1); Console.ReadLine(); } private static void PrintIfObjectIsNull(Object o) { if (o == null) { Console.WriteLine("object is null"); } else { Console.WriteLine("object still references something"); } } /// <summary> /// this takes in a Reference type of Person, by value /// </summary> /// <param name="person"></param> private static void PrintUserNameByValue(Person person) { Console.WriteLine(person.Name); person = null; //<- this cannot affect the orginal reference, as it was passed in by value. } /// <summary> /// this takes in a Reference type of Person, by reference /// </summary> /// <param name="person"></param> private static void PrintUserNameByRef(ref Person person) { Console.WriteLine(person.Name); person = null; //this has access to the orginonal reference, allowing us to alter it, either make it point to a different object or to nothing. } } class Person { public string Name { get; set; } } } If it java cannot do this, then its just passing a reference type by value? (is that fair to say) Many thanks Bones

    Read the article

  • MySQL – How to Write Loop in MySQL

    - by Pinal Dave
    Since, I have written courses on MySQL, I quite often get emails about MySQL courses. Here is the question, which I have received quite often. “How do I loop queries in MySQL?” Well, currently MySQL does not allow to write loops with the help of ad-hoc SQL. You have to write stored procedure (routine) for the same. Here is the example, how we can create a procedure in MySQL which will look over the code. In this example I have used SELECT 1 statement and looped over it. In reality you can put there any code and loop over it. This procedure accepts one parameter which is the number of the count the loop will iterate itself. delimiter // CREATE PROCEDURE doiterate(p1 INT) BEGIN label1: LOOP SET p1 = p1 - 1; IF p1 > 0 THEN SELECT 1; ITERATE label1; END IF; LEAVE label1; END LOOP label1; END// delimiter ; CALL doiterate(100); You can also use WHILE to loop as well, we will see that in future blog posts. Reference: Pinal Dave (http://blog.sqlauthority.com)Filed under: MySQL, PostADay, SQL, SQL Authority, SQL Query, SQL Tips and Tricks, T SQL

    Read the article

  • crash with CoUnintialize() api of COM

    - by jbp117
    My main process(main.exe) initilaized COM library and created a thread which creates a new process(p1.exe) this new process is again initializing COM library and after making all references as zero unintialized COM here.. the unintailezed COM in the main process (i.e main.exe) also.... When i run p1.exe individually it is successful.. but it is crashing when i create a process for p1.exe from main.exe

    Read the article

  • Two-page view in Word, shouldn't the first page be on the right?

    - by Cylindric
    Greetings Superusers, I'm putting together a lengthy document in Word, and it's going to be printed and bound duplex. I've put page-numbers "outside" etc, and all is pretty. The problem is, in the "Two Pages" view, it puts p1 on the left, then p2 on the right, then p3 below on the left, and p4 on the right. p1 p2 p3 p4 p5 p6 Shouldn't this be slightly different though? When I get to print it, p1 is on the right, not the left, so the preview should go p1 p2 p3 p4 p5 p6 Because when I "open" the book, it's pages 2 and 3 that are side-by-side. This makes layout tweaking confusing, because it's not instantly obvious which pages will be "visible" to the reader at the same time together. Have I missed something? I can't just put a blank page first, because that would bugger up the printing, as the printer automatically duplexes and binds etc. (Office 2008, by the way)

    Read the article

  • State Design Pattern .NET Code Sample

    using System;using System.Collections.Generic;using System.Linq;using System.Text;class Program{ static void Main(string[] args) { Person p1 = new Person("P1"); Person p2 = new Person("P2"); p1.EatFood(); p2.EatFood(); p1.Vomit(); p2.Vomit(); }}interface StomachState{ void Eat(Person p); void Vomit(Person p);}class StomachFull : StomachState{ public void Eat(Person p) { Console.WriteLine("Can't eat more."); } public void Vomit(Person p) { Console.WriteLine("I've just Vomited."); p.StomachState = new StomachEmpty(); }}class StomachEmpty : StomachState{ public void Eat(Person p) { Console.WriteLine("I've just had food."); p.StomachState = new StomachFull(); } public void Vomit(Person p) { Console.WriteLine("Nothing to Vomit."); }}class Person{ private StomachState stomachState; private String personName; public Person(String personName) { this.personName = personName; StomachState = new StomachEmpty(); } public StomachState StomachState { get { return stomachState; } set { stomachState = value; Console.WriteLine(personName + " Stomach State Changed to " + StomachState.GetType().Name); Console.WriteLine("***********************************************\n"); } } public Person(StomachState StomachState) { this.StomachState = StomachState; } public void EatFood() { StomachState.Eat(this); } public void Vomit() { StomachState.Vomit(this); }} span.fullpost {display:none;}

    Read the article

  • JUnit testing, exception in threa main

    - by Crystal
    I am new to JUnit and am trying to follow my prof's example. I have a Person class and a PersonTest class. When I try to compile PersonTest.java, I get the following error: Exception in thread "main" java.lang.NoSuchMethodError: main I am not really sure why since I followed his example. Person.java public class Person implements Comparable { String firstName; String lastName; String telephone; String email; public Person() { firstName = ""; lastName = ""; telephone = ""; email = ""; } public Person(String firstName) { this.firstName = firstName; } public Person(String firstName, String lastName, String telephone, String email) { this.firstName = firstName; this.lastName = lastName; this.telephone = telephone; this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int compareTo(Object o) { String s1 = this.lastName + this.firstName; String s2 = ((Person) o).lastName + ((Person) o).firstName; return s1.compareTo(s2); } public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) { return true; } // must return false if the explicit parameter is null if (otherObject == null) { return false; } if (!(otherObject instanceof Person)) { return false; } Person other = (Person) otherObject; return firstName.equals(other.firstName) && lastName.equals(other.lastName) && telephone.equals(other.telephone) && email.equals(other.email); } public int hashCode() { return this.email.toLowerCase().hashCode(); } public String toString() { return getClass().getName() + "[firstName = " + firstName + '\n' + "lastName = " + lastName + '\n' + "telephone = " + telephone + '\n' + "email = " + email + "]"; } } PersonTest.java import org.junit.Test; // JDK 5.0 annotation support import static org.junit.Assert.assertTrue; // Using JDK 5.0 static imports import static org.junit.Assert.assertFalse; // Using JDK 5.0 static imports import junit.framework.JUnit4TestAdapter; // Need this to be compatible with old test driver public class PersonTest { /** A test to verify equals method. */ @Test public void checkEquals() { Person p1 = new Person("jj", "aa", "[email protected]", "1112223333"); assertTrue(p1.equals(p1)); // first check in equals method assertFalse(p1.equals(null)); // second check in equals method assertFalse(p1.equals(new Object())); // third chk in equals method Person p2 = new Person("jj", "aa", "[email protected]", "1112223333"); assertTrue(p1.equals(p2)); // check for deep comparison p1 = new Person("jj", "aa", "[email protected]", "1112223333"); p2 = new Person("kk", "aa", "[email protected]", "1112223333"); assertFalse(p1.equals(p2)); // check for deep comkparison } }

    Read the article

  • Did I implement this correctly?

    - by user146780
    I'm trying to implement line thickness as denoted here: start = line start = vector(x1, y1) end = line end = vector(x2, y2) dir = line direction = end - start = vector(x2-x1, y2-y1) ndir = normalized direction = dir*1.0/length(dir) perp = perpendicular to direction = vector(dir.x, -dir.y) nperp = normalized perpendicular = perp*1.0/length(perp) perpoffset = nperp*w*0.5 diroffset = ndir*w*0.5 p0, p1, p2, p3 = polygon points: p0 = start + perpoffset - diroffset p1 = start - perpoffset - diroffset p2 = end + perpoffset + diroffset p3 = end - perpoffset + diroffset I'v implemented this like so: void OGLENGINEFUNCTIONS::GenerateLinePoly(const std::vector<std::vector<GLdouble>> &input, std::vector<GLfloat> &output, int width) { output.clear(); float temp; float dirlen; float perplen; POINTFLOAT start; POINTFLOAT end; POINTFLOAT dir; POINTFLOAT ndir; POINTFLOAT perp; POINTFLOAT nperp; POINTFLOAT perpoffset; POINTFLOAT diroffset; POINTFLOAT p0, p1, p2, p3; for(int i = 0; i < input.size() - 1; ++i) { start.x = input[i][0]; start.y = input[i][1]; end.x = input[i + 1][0]; end.y = input[i + 1][1]; dir.x = end.x - start.x; dir.y = end.y - start.y; dirlen = sqrt((dir.x * dir.x) + (dir.y * dir.y)); ndir.x = dir.x * (1.0 / dirlen); ndir.y = dir.y * (1.0 / dirlen); perp.x = dir.x; perp.y = -dir.y; perplen = sqrt((perp.x * perp.x) + (perp.y * perp.y)); nperp.x = perp.x * (1.0 / perplen); nperp.y = perp.y * (1.0 / perplen); perpoffset.x = nperp.x * width * 0.5; perpoffset.y = nperp.y * width * 0.5; diroffset.x = ndir.x * width * 0.5; diroffset.y = ndir.x * width * 0.5; // p0 = start + perpoffset - diroffset //p1 = start - perpoffset - diroffset //p2 = end + perpoffset + diroffset // p3 = end - perpoffset + diroffset p0.x = start.x + perpoffset.x - diroffset.x; p0.y = start.y + perpoffset.y - diroffset.y; p1.x = start.x - perpoffset.x - diroffset.x; p1.y = start.y - perpoffset.y - diroffset.y; p2.x = end.x + perpoffset.x + diroffset.x; p2.y = end.y + perpoffset.y + diroffset.y; p3.x = end.x - perpoffset.x + diroffset.x; p3.y = end.y - perpoffset.y + diroffset.y; output.push_back(p0.x); output.push_back(p0.y); output.push_back(p1.x); output.push_back(p1.y); output.push_back(p2.x); output.push_back(p2.y); output.push_back(p3.x); output.push_back(p3.y); } } But right now the lines look perpendicular and wrong, it should be giving me quads to render which is what i'm rendering, but the points it is outputing are strange. Have I done this wrong? Thanks

    Read the article

  • Trying to detect collision between two polygons using Separating Axis Theorem

    - by Holly
    The only collision experience i've had was with simple rectangles, i wanted to find something that would allow me to define polygonal areas for collision and have been trying to make sense of SAT using these two links Though i'm a bit iffy with the math for the most part i feel like i understand the theory! Except my implementation somewhere down the line must be off as: (excuse the hideous font) As mentioned above i have defined a CollisionPolygon class where most of my theory is implemented and then have a helper class called Vect which was meant to be for Vectors but has also been used to contain a vertex given that both just have two float values. I've tried stepping through the function and inspecting the values to solve things but given so many axes and vectors and new math to work out as i go i'm struggling to find the erroneous calculation(s) and would really appreciate any help. Apologies if this is not suitable as a question! CollisionPolygon.java: package biz.hireholly.gameplay; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import biz.hireholly.gameplay.Types.Vect; public class CollisionPolygon { Paint paint; private Vect[] vertices; private Vect[] separationAxes; CollisionPolygon(Vect[] vertices){ this.vertices = vertices; //compute edges and separations axes separationAxes = new Vect[vertices.length]; for (int i = 0; i < vertices.length; i++) { // get the current vertex Vect p1 = vertices[i]; // get the next vertex Vect p2 = vertices[i + 1 == vertices.length ? 0 : i + 1]; // subtract the two to get the edge vector Vect edge = p1.subtract(p2); // get either perpendicular vector Vect normal = edge.perp(); // the perp method is just (x, y) => (-y, x) or (y, -x) separationAxes[i] = normal; } paint = new Paint(); paint.setColor(Color.RED); } public void draw(Canvas c, int xPos, int yPos){ for (int i = 0; i < vertices.length; i++) { Vect v1 = vertices[i]; Vect v2 = vertices[i + 1 == vertices.length ? 0 : i + 1]; c.drawLine( xPos + v1.x, yPos + v1.y, xPos + v2.x, yPos + v2.y, paint); } } /* consider changing to a static function */ public boolean intersects(CollisionPolygon p){ // loop over this polygons separation exes for (Vect axis : separationAxes) { // project both shapes onto the axis Vect p1 = this.minMaxProjection(axis); Vect p2 = p.minMaxProjection(axis); // do the projections overlap? if (!p1.overlap(p2)) { // then we can guarantee that the shapes do not overlap return false; } } // loop over the other polygons separation axes Vect[] sepAxesOther = p.getSeparationAxes(); for (Vect axis : sepAxesOther) { // project both shapes onto the axis Vect p1 = this.minMaxProjection(axis); Vect p2 = p.minMaxProjection(axis); // do the projections overlap? if (!p1.overlap(p2)) { // then we can guarantee that the shapes do not overlap return false; } } // if we get here then we know that every axis had overlap on it // so we can guarantee an intersection return true; } /* Note projections wont actually be acurate if the axes aren't normalised * but that's not necessary since we just need a boolean return from our * intersects not a Minimum Translation Vector. */ private Vect minMaxProjection(Vect axis) { float min = axis.dot(vertices[0]); float max = min; for (int i = 1; i < vertices.length; i++) { float p = axis.dot(vertices[i]); if (p < min) { min = p; } else if (p > max) { max = p; } } Vect minMaxProj = new Vect(min, max); return minMaxProj; } public Vect[] getSeparationAxes() { return separationAxes; } public Vect[] getVertices() { return vertices; } } Vect.java: package biz.hireholly.gameplay.Types; /* NOTE: Can also be used to hold vertices! Projections, coordinates ect */ public class Vect{ public float x; public float y; public Vect(float x, float y){ this.x = x; this.y = y; } public Vect perp() { return new Vect(-y, x); } public Vect subtract(Vect other) { return new Vect(x - other.x, y - other.y); } public boolean overlap(Vect other) { if( other.x <= y || other.y >= x){ return true; } return false; } /* used specifically for my SAT implementation which i'm figuring out as i go, * references for later.. * http://www.gamedev.net/page/resources/_/technical/game-programming/2d-rotated-rectangle-collision-r2604 * http://www.codezealot.org/archives/55 */ public float scalarDotProjection(Vect other) { //multiplier = dot product / length^2 float multiplier = dot(other) / (x*x + y*y); //to get the x/y of the projection vector multiply by x/y of axis float projX = multiplier * x; float projY = multiplier * y; //we want to return the dot product of the projection, it's meaningless but useful in our SAT case return dot(new Vect(projX,projY)); } public float dot(Vect other){ return (other.x*x + other.y*y); } }

    Read the article

  • Error in my Separating Axis Theorem collision code

    - by Holly
    The only collision experience i've had was with simple rectangles, i wanted to find something that would allow me to define polygonal areas for collision and have been trying to make sense of SAT using these two links Though i'm a bit iffy with the math for the most part i feel like i understand the theory! Except my implementation somewhere down the line must be off as: (excuse the hideous font) As mentioned above i have defined a CollisionPolygon class where most of my theory is implemented and then have a helper class called Vect which was meant to be for Vectors but has also been used to contain a vertex given that both just have two float values. I've tried stepping through the function and inspecting the values to solve things but given so many axes and vectors and new math to work out as i go i'm struggling to find the erroneous calculation(s) and would really appreciate any help. Apologies if this is not suitable as a question! CollisionPolygon.java: package biz.hireholly.gameplay; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import biz.hireholly.gameplay.Types.Vect; public class CollisionPolygon { Paint paint; private Vect[] vertices; private Vect[] separationAxes; int x; int y; CollisionPolygon(Vect[] vertices){ this.vertices = vertices; //compute edges and separations axes separationAxes = new Vect[vertices.length]; for (int i = 0; i < vertices.length; i++) { // get the current vertex Vect p1 = vertices[i]; // get the next vertex Vect p2 = vertices[i + 1 == vertices.length ? 0 : i + 1]; // subtract the two to get the edge vector Vect edge = p1.subtract(p2); // get either perpendicular vector Vect normal = edge.perp(); // the perp method is just (x, y) => (-y, x) or (y, -x) separationAxes[i] = normal; } paint = new Paint(); paint.setColor(Color.RED); } public void draw(Canvas c, int xPos, int yPos){ for (int i = 0; i < vertices.length; i++) { Vect v1 = vertices[i]; Vect v2 = vertices[i + 1 == vertices.length ? 0 : i + 1]; c.drawLine( xPos + v1.x, yPos + v1.y, xPos + v2.x, yPos + v2.y, paint); } } public void update(int xPos, int yPos){ x = xPos; y = yPos; } /* consider changing to a static function */ public boolean intersects(CollisionPolygon p){ // loop over this polygons separation exes for (Vect axis : separationAxes) { // project both shapes onto the axis Vect p1 = this.minMaxProjection(axis); Vect p2 = p.minMaxProjection(axis); // do the projections overlap? if (!p1.overlap(p2)) { // then we can guarantee that the shapes do not overlap return false; } } // loop over the other polygons separation axes Vect[] sepAxesOther = p.getSeparationAxes(); for (Vect axis : sepAxesOther) { // project both shapes onto the axis Vect p1 = this.minMaxProjection(axis); Vect p2 = p.minMaxProjection(axis); // do the projections overlap? if (!p1.overlap(p2)) { // then we can guarantee that the shapes do not overlap return false; } } // if we get here then we know that every axis had overlap on it // so we can guarantee an intersection return true; } /* Note projections wont actually be acurate if the axes aren't normalised * but that's not necessary since we just need a boolean return from our * intersects not a Minimum Translation Vector. */ private Vect minMaxProjection(Vect axis) { float min = axis.dot(new Vect(vertices[0].x+x, vertices[0].y+y)); float max = min; for (int i = 1; i < vertices.length; i++) { float p = axis.dot(new Vect(vertices[i].x+x, vertices[i].y+y)); if (p < min) { min = p; } else if (p > max) { max = p; } } Vect minMaxProj = new Vect(min, max); return minMaxProj; } public Vect[] getSeparationAxes() { return separationAxes; } public Vect[] getVertices() { return vertices; } } Vect.java: package biz.hireholly.gameplay.Types; /* NOTE: Can also be used to hold vertices! Projections, coordinates ect */ public class Vect{ public float x; public float y; public Vect(float x, float y){ this.x = x; this.y = y; } public Vect perp() { return new Vect(-y, x); } public Vect subtract(Vect other) { return new Vect(x - other.x, y - other.y); } public boolean overlap(Vect other) { if(y > other.x && other.y > x){ return true; } return false; } /* used specifically for my SAT implementation which i'm figuring out as i go, * references for later.. * http://www.gamedev.net/page/resources/_/technical/game-programming/2d-rotated-rectangle-collision-r2604 * http://www.codezealot.org/archives/55 */ public float scalarDotProjection(Vect other) { //multiplier = dot product / length^2 float multiplier = dot(other) / (x*x + y*y); //to get the x/y of the projection vector multiply by x/y of axis float projX = multiplier * x; float projY = multiplier * y; //we want to return the dot product of the projection, it's meaningless but useful in our SAT case return dot(new Vect(projX,projY)); } public float dot(Vect other){ return (other.x*x + other.y*y); } }

    Read the article

  • Handling large integers in python [migrated]

    - by Sushma Palimar
    I had written a program in python to find b such that a prime number p divides b^2-8. The range for b is [1, (p+1)/2]. For small integers it works, say only up to 7 digits. But not for large integers, say for p = 140737471578113. I get the error message for i in range (2,p1,1): MemoryError I wrote the program as #!/usr/bin/python3 p=long(raw_input('enter the prime number:')) p1=long((p+1)/2) for i in range (2,p1,1): s = long((i*i)-8) if (s%p==0): print i

    Read the article

  • Compare base class part of sub class instance to another base class instance

    - by Anders Abel
    I have number of DTO classes in a system. They are organized in an inheritance hierarchy. class Person { public int Id { get; set; } public string FirstName { get; set; } public string ListName { get; set; } } class PersonDetailed : Person { public string WorkPhone { get; set; } public string HomePhone { get; set; } public byte[] Image { get; set; } } The reason for splitting it up is to be able to get a list of people for e.g. search results, without having to drag the heavy image and phone numbers along. Then the full PersonDetail DTO is loaded when the details for one person is selected. The problem I have run into is comparing these when writing unit tests. Assume I have Person p1 = myService.GetAPerson(); PersonDetailed p2 = myService.GetAPersonDetailed(); // How do I compare the base class part of p2 to p1? Assert.AreEqual(p1, p2); The Assert above will fail, as p1 and p2 are different classes. Is it possible to somehow only compare the base class part of p2 to p1? Should I implement IEquatable<> on Person? Other suggestions?

    Read the article

  • Very simple regex not working

    - by Thomas Wanner
    I have read that to match a word inside of a string using Regular expressions (in .NET), I can use the word boundary specifier (\b) within the regex. However, none of these calls result in any matches Regex.Match("INSERT INTO TEST(Col1,Col2) VALUES(@p1,@p2)", "\b@p1\b"); Regex.Match("INSERT INTO TEST(Col1,Col2) VALUES(@p1,@p2)", "\bINSERT\b"); Is there anything I am doing wrong ?

    Read the article

  • Nature of Lock is child table while deletion(sql server)

    - by Mubashar Ahmad
    Dear Devs From couple of days i am thinking of a following scenario Consider I have 2 tables with parent child relationship of kind one-to-many. On removal of parent row i have to delete the rows in child those are related to parents. simple right? i have to make a transaction scope to do above operation i can do this as following; (its psuedo code but i am doing this in c# code using odbc connection and database is sql server) begin transaction(read committed) Read all child where child.fk = p1 foreach(child) delete child where child.pk = cx delete parent where parent.pk = p1 commit trans OR begin transaction(read committed) delete all child where child.fk = p1 delete parent where parent.pk = p1 commit trans Now there are couple of questions in my mind Which one of above is better to use specially considering a scenario of real time system where thousands of other operations(select/update/delete/insert) are being performed within a span of seconds. does it ensure that no new child with child.fk = p1 will be added until transaction completes? If yes for 2nd question then how it ensures? do it take the table level locks or what. Is there any kind of Index locking supported by sql server if yes what it does and how it can be used. Regards Mubashar

    Read the article

  • n elements in singly linked list

    - by Codenotguru
    The following function is trying to find the nth to last element of a singly linked list. for ex: if the elements are 8-10-5-7-2-1-5-4-10-10 then the result is 7th to last node is 7. Can anybody help me on how this code is working or is there a better and simpler approach? LinkedListNode nthToLast(LinkedListNode head, int n) { if (head == null || n < 1) { return null; } LinkedListNode p1 = head; LinkedListNode p2 = head; for (int j = 0; j < n - 1; ++j) { // skip n-1 steps ahead if (p2 == null) { return null; // not found since list size < n } p2 = p2.next; } while (p2.next != null) { p1 = p1.next; p2 = p2.next; } return p1; }

    Read the article

  • JDBC ODBC.. (Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException)

    - by enthudrives
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { PreparedStatement p1; String s="insert into reg values(?,?)"; try { p1 = conn.prepareStatement(s); System.out.println("hi?"); p1.setString(1, num.getText()); p1.setString(2, name.getText()); p1.executeUpdate(); // TODO add your handling code here: } catch (SQLException ex) { Logger.getLogger(sample.class.getName()).log(Level.SEVERE, null, ex); } } This is my insert module.. This works in my friend's laptop. But not in mine :( I get the following error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at sample.jButton1ActionPerformed(sample.java:197) at sample.access$200(sample.java:20) at sample$3.actionPerformed(sample.java:92) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6263) at javax.swing.JComponent.processMouseEvent(JComponent.java:3267) at java.awt.Component.processEvent(Component.java:6028) at java.awt.Container.processEvent(Container.java:2041) at java.awt.Component.dispatchEventImpl(Component.java:4630) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168) at java.awt.Container.dispatchEventImpl(Container.java:2085) at java.awt.Window.dispatchEventImpl(Window.java:2478) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) Java Result: 1 PS: I am totally new to java. Is it a problem with my ODBC?

    Read the article

  • Why are there 3 conflicting OpenCV camera calibration formulas?

    - by John
    I'm having a problem with OpenCV's various parameterization of coordinates used for camera calibration purposes. The problem is that three different sources of information on image distortion formulae apparently give three non-equivalent description of the parameters and equations involved: (1) In their book "Learning OpenCV…" Bradski and Kaehler write regarding lens distortion (page 376): xcorrected = x * ( 1 + k1 * r^2 + k2 * r^4 + k3 * r^6 ) + [ 2 * p1 * x * y + p2 * ( r^2 + 2 * x^2 ) ], ycorrected = y * ( 1 + k1 * r^2 + k2 * r^4 + k3 * r^6 ) + [ p1 * ( r^2 + 2 * y^2 ) + 2 * p2 * x * y ], where r = sqrt( x^2 + y^2 ). Assumably, (x, y) are the coordinates of pixels in the uncorrected captured image corresponding to world-point objects with coordinates (X, Y, Z), camera-frame referenced, for which xcorrected = fx * ( X / Z ) + cx and ycorrected = fy * ( Y / Z ) + cy, where fx, fy, cx, and cy, are the camera's intrinsic parameters. So, having (x, y) from a captured image, we can obtain the desired coordinates ( xcorrected, ycorrected ) to produced an undistorted image of the captured world scene by applying the above first two correction expressions. However... (2) The complication arises as we look at OpenCV 2.0 C Reference entry under the Camera Calibration and 3D Reconstruction section. For ease of comparison we start with all world-point (X, Y, Z) coordinates being expressed with respect to the camera's reference frame, just as in #1. Consequently, the transformation matrix [ R | t ] is of no concern. In the C reference, it is expressed that: x' = X / Z, y' = Y / Z, x'' = x' * ( 1 + k1 * r'^2 + k2 * r'^4 + k3 * r'^6 ) + [ 2 * p1 * x' * y' + p2 * ( r'^2 + 2 * x'^2 ) ], y'' = y' * ( 1 + k1 * r'^2 + k2 * r'^4 + k3 * r'^6 ) + [ p1 * ( r'^2 + 2 * y'^2 ) + 2 * p2 * x' * y' ], where r' = sqrt( x'^2 + y'^2 ), and finally that u = fx * x'' + cx, v = fy * y'' + cy. As one can see these expressions are not equivalent to those presented in #1, with the result that the two sets of corrected coordinates ( xcorrected, ycorrected ) and ( u, v ) are not the same. Why the contradiction? It seems to me the first set makes more sense as I can attach physical meaning to each and every x and y in there, while I find no physical meaning in x' = X / Z and y' = Y / Z when the camera focal length is not exactly 1. Furthermore, one cannot compute x' and y' for we don't know (X, Y, Z). (3) Unfortunately, things get even murkier when we refer to the writings in Intel's Open Source Computer Vision Library Reference Manual's section Lens Distortion (page 6-4), which states in part: "Let ( u, v ) be true pixel image coordinates, that is, coordinates with ideal projection, and ( u ~, v ~ ) be corresponding real observed (distorted) image coordinates. Similarly, ( x, y ) are ideal (distortion-free) and ( x ~, y ~ ) are real (distorted) image physical coordinates. Taking into account two expansion terms gives the following: x ~ = x * ( 1 + k1 * r^2 + k2 * r^4 ) + [ 2 p1 * x * y + p2 * ( r^2 + 2 * x^2 ) ] y ~ = y * ( 1 + k1 * r^2 + k2 * r^4 ] + [ 2 p2 * x * y + p2 * ( r^2 + 2 * y^2 ) ], where r = sqrt( x^2 + y^2 ). ... "Because u ~ = cx + fx * u and v ~ = cy + fy * v , … the resultant system can be rewritten as follows: u ~ = u + ( u – cx ) * [ k1 * r^2 + k2 * r^4 + 2 * p1 * y + p2 * ( r^2 / x + 2 * x ) ] v ~ = v + ( v – cy ) * [ k1 * r^2 + k2 * r^4 + 2 * p2 * x + p1 * ( r^2 / y + 2 * y ) ] The latter relations are used to undistort images from the camera." Well, it would appear that the expressions involving x ~ and y ~ coincided with the two expressions given at the top of this writing involving xcorrected and ycorrected. However, x ~ and y ~ do not refer to corrected coordinates, according to the given description. I don't understand the distinction between the meaning of the coordinates ( x ~, y ~ ) and ( u ~, v ~ ), or for that matter, between the pairs ( x, y ) and ( u, v ). From their descriptions it appears their only distinction is that ( x ~, y ~ ) and ( x, y ) refer to 'physical' coordinates while ( u ~, v ~ ) and ( u, v ) do not. What is this distinction all about? Aren't they all physical coordinates? I'm lost! Thanks for any input!

    Read the article

  • crash with CoUnintailize() api of COM

    - by jbp117
    My main process(main.exe) initilaized COM library and created a thread which creates a new process(p1.exe) this new process is again initializing COM library and after making all references as zero unintialized COM here.. the unintailezed COM in the main process (i.e main.exe) also.... When i run p1.exe individually it is successful.. but it is crashing when i create a process for p1.exe from main.exe

    Read the article

  • mysql query clarification

    - by JPro
    I have a query which I am wondering if the result I am getting is the one that I am expecting. The table structure goes like this : Table : results ID TestCase Set Analyzed Verdict StartTime Platform 1 1010101 ros2 false fail 18/04/2010 20:23:44 P1 2 1010101 ros3 false fail 19/04/2010 22:22:33 P1 3 1232323 ros2 true pass 19/04/2010 22:22:33 P1 4 1232323 ros3 false fail 29/04/2010 22:22:33 P2 Table : testcases ID TestCase type 1 1010101 NOSNOS 2 1232323 N212NS is there any way to display only the latest fails on each platform? in the above case Result shoud be : ID TestCase Set Analyzed Verdict StartTime Platform type 2 1010101 ros3 false fail 19/04/2010 22:22:33 P1 NOSNOS 4 1232323 ros3 false fail 29/04/2010 22:22:33 P2 N212NS

    Read the article

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