Beispiel #1
0
def build_shielded_geometry():
    air = Material(0.1, color='white')
    u235_metal = Material(1.0, color='green')
    poly = Material(1.0, color='red')
    steel = Material(1.0, color='orange')

    box = create_hollow(create_rectangle(20., 10.), create_rectangle(18., 8.))

    hollow_circle = create_hollow(create_circle(3.9), create_circle(2.9))
    hollow_circle.translate([-9 + 3.9 + 0.1, 0.])

    small_box_1 = create_rectangle(2., 2.)
    small_box_1.translate([6., 2.])

    small_box_2 = create_rectangle(2., 2.)
    small_box_2.translate([6., -2.])

    #sim = Simulation(air, 50., 45., 'arc')
    sim = Simulation(air,
                     100,
                     diameter=50.,
                     detector='plane',
                     detector_width=30.)
    sim.detector.width = 30.
    sim.geometry.solids.append(Solid(box, steel, air))
    sim.geometry.solids.append(Solid(hollow_circle, steel, air))
    sim.geometry.solids.append(Solid(small_box_1, poly, air))
    sim.geometry.solids.append(Solid(small_box_2, steel, air))
    sim.geometry.flatten()

    return sim
Beispiel #2
0
def csg_to_solid(csg, as_tri=False):
    solid = Solid()
    for p in csg.polygons:
        indices = []
        for v in p.vertices:
            i = solid.append_vertex(v.as_array())
            indices.append(i)

        solid.append_polygon(indices, as_tri=as_tri)
    return solid
Beispiel #3
0
    def DrawStage(self, maxDim):
        # This method is only meant to be used for getting an overview of the stage during development!
        if self.stageWidth > self.stageHeight:
            stageToScreenFactor = maxDim / self.stageWidth
        else:
            stageToScreenFactor = maxDim / self.stageHeight
        screenWidth = int(stageToScreenFactor * self.stageWidth)
        screenHeight = int(stageToScreenFactor * self.stageHeight)

        screen = pygame.display.set_mode((screenWidth, screenHeight))

        screen.fill((0, 128, 255))
        drawSolids = [
            Solid(solid.color, [
                tuple(val * stageToScreenFactor for val in seg)
                for seg in solid.segments
            ]) for solid in self.solids
        ]
        for solid in drawSolids:
            solid.Draw(screen, screenWidth, screenHeight, 0, screenHeight)
        character = Character(screen,
                              int(self.character.x * stageToScreenFactor),
                              int(self.character.y * stageToScreenFactor),
                              self.character.color,
                              int(self.character.radius * stageToScreenFactor),
                              screenWidth, screenHeight)
        character.Draw()
        pygame.display.flip()
Beispiel #4
0
	def __init__( self , fovy , ratio , near , far , robot_files ) :
		self.fovy = fovy
		self.near = near 
		self.far = far
		self.ratio = ratio

		self.running = False
		self.speed = .5

		self.camera = Camera( ( 0 , 500 , -150 ) , ( 0 , 100 , 0 ) , ( 0 , 1 , 0 ) )
		self.plane  = Plane( (2,2) )
		self.solid  = Solid( (-150,-150,-150) , (150,150,150) , (100,100) )
		self.robot  = Robot( robot_files )
		self.load_path( 'data/t1.k16' )

		self.solid.set_cut( self.parser.next() )

		self.x = 0.0

		self.last_time = timer()
		self.ntime = int(self.last_time) + 1

		self.plane_alpha = 65.0 / 180.0 * m.pi

		self._make_plane_matrix()
Beispiel #5
0
    def test_generate_lines_for_face_Q4_XZ_plane(self):
        all_solids = split_compound(self.compound_Q4)
        intersections = SolidFaceValidator.get_intersections_for_face(
            all_solids, PL_XZ)

        self.assertEqual(len(intersections), len(all_solids))
        all_intersected_solids = list(
            {s
             for inter in intersections for s in inter})
        expected_all_intersected_solids = [Solid(s) for s in all_solids]
        self.assertCountEqual(expected_all_intersected_solids,
                              all_intersected_solids)
    def remove_if_valid(self, solid):
        """
        Checks if the shape resulting from removing the given solid is valid. If it is, returns True
        and removes the solid from its internal representation. Otherwise returns false and the internal
        representation is unchanged
        :param solid:
        :return:
        """
        assert isinstance(solid, TopoDS_Solid)
        _solid = Solid(solid)
        affected_lists = [
            l for l in self._xz_intersections + self._yz_intersections
            if _solid in l
        ]
        bad_lists = [l for l in affected_lists if len(l) == 1]
        if bad_lists:
            return False

        for l in affected_lists:
            l.remove(Solid(solid))

        return True
Beispiel #7
0
def ray_trace_test_geometry():
    air = Material(0.0, color='white')
    steel = Material(1.0, color='red')

    box = create_hollow(create_rectangle(12., 12.), create_rectangle(10., 10.))
    ring = create_hollow(create_circle(12.), create_circle(10.))
    box.rotate(45.)

    sim = Simulation(air, diameter=50.)
    sim.detector.width = 30.
    sim.geometry.solids.append(Solid(ring, steel, air))
    sim.geometry.flatten()

    return sim
Beispiel #8
0
def read(filename):
    io = TextReader(filename)
    if not io.readline() == "ply":
        assert False, "file does not start ply: filename=%s" % filename
    if not io.readline() == "format ascii 1.0":
        assert False, "file is not ascii: filename=%s" % filename

    vertex_count = 0
    face_count = 0
    has_color = False

    while True:
        line = io.readline()
        if line == "end_header":
            break

        if line == "property uchar red":
            has_color = True

        match = re.match(r"element vertex (\d+)", line)
        if match:
            vertex_count = int(match.group(1))
            continue

        match = re.match(r"element face (\d+)", line)
        if match:
            face_count = int(match.group(1))
            continue

    if vertex_count == 0:
        assert False, "no vertex"

    solid = Solid()
    for i in xrange(vertex_count):
        line = io.readline()
        items = line.split(" ")
        solid.append_vertex([float(items[0]), float(items[1]), float(items[2])])

    for i in xrange(face_count):
        line = io.readline()
        items = line.split(" ")
        count = int(items[0]) - 1
        indices = []
        color = None
        for v in xrange(count):
            indices.append(int(items[v + 1]))

        if has_color:
            color = []
            for c in xrange(count, count + 3):
                color.append(int(items[c + 2]))

        solid.append_plane(indices, color)

    io.close()
    return solid
Beispiel #9
0
def create_solid(centers, offset=np.array([0., 0., 0.]), d=0.25):

    points = []

    for c in centers:
        points.append(c + offset + np.array([-d, -d, -d]))
        points.append(c + offset + np.array([d, -d, -d]))
        points.append(c + offset + np.array([d, d, -d]))
        points.append(c + offset + np.array([-d, d, -d]))
        points.append(c + offset + np.array([-d, d, d]))
        points.append(c + offset + np.array([-d, -d, d]))
        points.append(c + offset + np.array([d, -d, d]))
        points.append(c + offset + np.array([d, d, d]))

    return Solid(points, len(points) * [2.])
    def get_intersections_for_face(self, solids, pln):
        # TODO: better comment. Doesn't explain where lines come from
        """
        :param solids: The list of solids making up the overall solid
        :param pln: The plane of the face
        :return: A list of lists, where the inner lists are lists of solids that each line intersects
        """
        pts = []
        for s in solids:
            props = GlobalProperties(OCCUtilsSolid(s))
            p = props.centre()
            if point_in_solid(OCCUtilsSolid(s), p):
                pts.append(p)
            else:
                raise NotImplementedError("Need to handle odd shapes")

        normal_vec = normal_vector_from_plane(pln)
        normal_dir = gp_Dir(normal_vec)
        lines = [gp_Lin(p, normal_dir) for p in pts]

        # remove redundant lines
        groups = []
        for l in lines:
            for g in groups:
                if any([l.Distance(gl) < 0.0000000001 for gl in g]):
                    g.add(l)
                    break
            else:
                groups.append({l})

        lines = [g.pop() for g in groups]

        # We have to use lists here rather than sets or dicts, because the solids undergo very minor deviations
        # while operated on by OCC, so we can't get matching hashes
        result = []
        for line in lines:
            result.append([
                Solid(s) for s in solids
                if self.get_shape_line_intersections(s, line)
            ])

        return result
Beispiel #11
0
 def test_creat_solid(self):
     my_solid = Solid(BRepPrimAPI_MakeBox(10, 20, 30).Solid())
     assert my_solid.tolerance == 1e-06
Beispiel #12
0
 def test_hash_equality(self):
     solid = Solid(split_compound(self.compound_HE)[0])
     self.assertEqual(solid.__hash__(), copy.deepcopy(solid).__hash__())
Beispiel #13
0
 def test_equality_deep_copy(self):
     solid = Solid(split_compound(self.compound_HE)[0])
     self.assertEqual(solid, copy.deepcopy(solid))
Beispiel #14
0
 def test_equality(self):
     solid = Solid(split_compound(self.compound_HE)[0])
     self.assertEqual(solid, solid)
Beispiel #15
0
class Scene :
	def __init__( self , fovy , ratio , near , far , robot_files ) :
		self.fovy = fovy
		self.near = near 
		self.far = far
		self.ratio = ratio

		self.running = False
		self.speed = .5

		self.camera = Camera( ( 0 , 500 , -150 ) , ( 0 , 100 , 0 ) , ( 0 , 1 , 0 ) )
		self.plane  = Plane( (2,2) )
		self.solid  = Solid( (-150,-150,-150) , (150,150,150) , (100,100) )
		self.robot  = Robot( robot_files )
		self.load_path( 'data/t1.k16' )

		self.solid.set_cut( self.parser.next() )

		self.x = 0.0

		self.last_time = timer()
		self.ntime = int(self.last_time) + 1

		self.plane_alpha = 65.0 / 180.0 * m.pi

		self._make_plane_matrix()

	def set_speed( self , s ) :
		self.speed = s

	def _make_plane_matrix( self ) :
		r = tr.rotation_matrix( self.plane_alpha , (0,0,1) )
		s = tr.scale_matrix( 1 )
		t = tr.translation_matrix( (-1.25,.7,.05) )

		self.m = np.dot( np.dot( t , s ) , r )
		self.im = la.inv( self.m )
		self.im[3] = [ 0 , 0 , 0 , 1 ]

	def gfx_init( self ) :
		self._update_proj()
		self._set_lights()

		glEnable( GL_DEPTH_TEST )
		glEnable( GL_NORMALIZE )
		glEnable( GL_CULL_FACE )
		glEnable( GL_COLOR_MATERIAL )
		glColorMaterial( GL_FRONT_AND_BACK , GL_AMBIENT_AND_DIFFUSE )

		self.solid.gfx_init()

	def fast_cut( self , pb ) :
		while True :
			n = self.parser.next()
			if not n : break
			self.solid.next_cut( n )

	def draw( self ) :
		self.time = timer()

		dt = self.time - self.last_time

		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()

		self.camera.look()

		self._draw_scene()

		self.robot.update( dt )

		if self.running and self.time > self.ntime :
			self.solid.next_cut( self.parser.next() )
			self.ntime = self.time + self.speed

		self.x+=dt*.3

		self.last_time = self.time

	def _draw_scene( self ) :
		pos = np.dot( self.m , np.array( [ m.sin(self.x*7)*m.cos(self.x/3.0) , 0 , m.cos(self.x*5) , 1 ] ) )
		nrm = np.dot( self.m , np.array( [      0        ,-1 ,      0        , 0 ] ) )

#        self.robot.resolve( pos , nrm )

		glPushMatrix();
		glScalef(100,100,100)

		glClearStencil(0);
		glClear(GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);

		glDisable(GL_DEPTH_TEST)
		glEnable(GL_STENCIL_TEST)
		glStencilFunc(GL_ALWAYS, 1, 1)
		glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)

		glColorMask(0,0,0,0);
		glFrontFace(GL_CCW);
#        self.plane.draw( self.m )

		glEnable(GL_DEPTH_TEST)

		glColorMask(1,1,1,1);
		glStencilFunc(GL_EQUAL, 1, 1);
		glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

		glPushMatrix()
		glMultTransposeMatrixf( self.m )
		glScalef(1,-1,1)
		glMultTransposeMatrixf( self.im )

		glFrontFace(GL_CW);
#        self.robot.draw()

		glPopMatrix();
		glFrontFace(GL_CCW);

		glDisable(GL_STENCIL_TEST)

		glEnable( GL_BLEND )
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

		glColor4f(.7,.7,.7,.85)

#        self.plane.draw( self.m )

		glDisable( GL_BLEND )

#        self.robot.draw()
		
		glPopMatrix()

		self.solid.draw()

	def _update_proj( self ) :
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		gluPerspective( self.fovy , self.ratio , self.near , self.far )
		glMatrixMode(GL_MODELVIEW)

	def _set_lights( self ) :
		glEnable(GL_LIGHTING);
		glLightfv(GL_LIGHT0, GL_AMBIENT, [ 0.2 , 0.2 , 0.2 ] );
		glLightfv(GL_LIGHT0, GL_DIFFUSE, [ 0.9 , 0.9 , 0.9 ] );
		glLightfv(GL_LIGHT0, GL_SPECULAR,[ 0.3 , 0.3 , 0.3 ] );
		glLightfv(GL_LIGHT0, GL_POSITION, [ 0 , 200 , 0 ] );
		glEnable(GL_LIGHT0); 
						 
	def set_fov( self , fov ) :
		self.fov = fov
		self._update_proj()

	def set_near( self , near ) :
		self.near = near
		self._update_proj()

	def set_ratio( self , ratio ) :
		self.ratio = ratio
		self._update_proj()

	def set_screen_size( self , w , h ) :
		self.width  = w 
		self.height = h
		self.set_ratio( float(w)/float(h) )

	def mouse_move( self , df ) :
		self.camera.rot( *map( lambda x : -x*.2 , df ) )

	def key_pressed( self , mv ) :
		self.camera.move( *map( lambda x : x*2.5 , mv ) )

	def set_flat_drill( self , s ) :
		self.solid.set_flat_drill( s )

	def set_round_drill( self , s ) :
		self.solid.set_round_drill( s )

	def sim_run( self ) :
		self.running = True

	def sim_stop( self ) :
		self.running = False

	def reset( self ) :
		self.parser.set_off( self.solid.newbeg )
		self.parser.reset()
		self.solid.reset()
		self.reset_drill( self.parser.get_drill() )
		return self.parser.get_drill() 

	def load_path( self , filename ) :
		self.parser = Parser( filename , self.solid.newbeg )
		self.reset_drill( self.parser.get_drill() )
		return self.parser.get_drill() 
	
	def reset_drill( self , drill ) :
		if drill[0] == Parser.FLAT :
			self.solid.set_flat_drill( drill[1] )
		elif drill[0] == Parser.ROUND :
			self.solid.set_round_drill( drill[1] )

	def set_precision( self , prec ) :
		self.solid.set_prec( (prec,prec) )

	def set_size( self , beg , end ) :
		self.solid.set_size( beg , end )

	def set_drill_len( self , l ) :
		self.solid.set_drill_len( l )
Beispiel #16
0
from character import Character
from solid import Solid
import movement_constants

GRAVITY_CONSTANT_Y = -5000
GRAVITY_CONSTANT_X = 0
WIDTH = 800
HEIGHT = 600
FPS = 60
D_T = 1 / FPS

EXAMPLE_SOLIDS = []
EXAMPLE_SOLIDS.append(
    Solid((int(255 / 2), 0, 0),
          [(0, 200, math.floor(WIDTH / 3), 200),
           (math.floor(WIDTH / 3), 100, math.floor(WIDTH / 3), 100),
           (math.floor(WIDTH / 3) * 2, 200,
            (WIDTH - 1 + math.floor(WIDTH / 3) * 2), 200)]))
EXAMPLE_SOLIDS.append(
    Solid((0, int(255 / 3 * 2), 0), [(0, int(HEIGHT * 2 / 3), 250, 50)]))

YELLOW = (255, 215, 0)


class Stage:
    def __init__(self,
                 screen,
                 character,
                 isPeriodic,
                 stageWidth,
                 stageHeight,
Beispiel #17
0
WHITE = (255, 255, 255)

STAGE_X_SHIFT = 600

STAGE_WIDTH = 4400 + STAGE_X_SHIFT
STAGE_HEIGHT = 3500 + STAGE_X_SHIFT

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
character = Character(screen, int(WIDTH / 2), int(HEIGHT / 2), (255, 215, 0),
                      50)

solids = []

groundLevel = 100
ground = Solid(GREEN, [(0, groundLevel, STAGE_WIDTH, groundLevel)])
solids.append(ground)

platformSpacing = 200
platformWidth = 200
startPlatforms = Solid(RED, [
    (STAGE_X_SHIFT + 0, groundLevel + platformSpacing, platformWidth, 50),
    (STAGE_X_SHIFT + 400, groundLevel + platformSpacing * 2, platformWidth,
     50),
    (STAGE_X_SHIFT + 0, groundLevel + platformSpacing * 3, platformWidth, 50),
    (STAGE_X_SHIFT + 400, groundLevel + platformSpacing * 4, platformWidth, 50)
])
solids.append(startPlatforms)

pipeThickness = 70
pipeWidth = 300
Beispiel #18
0
HEIGHT = 600
BROWN = (int(255 / 2), 0, 0)
GREEN = (0, int(255 / 3 * 2), 0)
WHITE = (255, 255, 255)

STAGE_WIDTH = WIDTH
STAGE_HEIGHT = HEIGHT + 300

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
character = Character(screen, int(WIDTH / 2), int(HEIGHT / 2), (255, 215, 0),
                      50)
solids = []
ground = Solid(BROWN,
               [(0, 200, math.floor(WIDTH / 3), 200),
                (math.floor(WIDTH / 3), 100, math.floor(WIDTH / 3), 100),
                (math.floor(WIDTH / 3) * 2, 200,
                 (WIDTH - 1 - math.floor(WIDTH / 3) * 2), 200)])
platform = Solid(GREEN, [(0, int(HEIGHT * 2 / 3), 250, 50)])

goalWidth = 100
goalHeight = 150
goal = Goal(
    WHITE,
    [(STAGE_WIDTH - goalWidth - 50, 700 + goalHeight, goalWidth, goalHeight)])

solids.append(ground)
solids.append(platform)
solids.append(goal)
isPeriodic = True
stage = Stage(screen, character, isPeriodic, STAGE_WIDTH, STAGE_HEIGHT, solids)
from solid import Goal
from solid import Trap
from solid import MovingSolidX
import color_palette

WIDTH = 800
HEIGHT = 600
secretGapWidth = 300
STAGE_WIDTH = 1200 * 3 + 150 + secretGapWidth
STAGE_HEIGHT = 1000

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
solids = []

underWaterCatcher = Solid((0, 0, 0), [(0, -500, STAGE_WIDTH, 50)])
solids.append(underWaterCatcher)

waterLevel = 100
water = Trap(color_palette.TEAL, [(0, waterLevel, STAGE_WIDTH, waterLevel)])

plankThickness = 50
plankLength = 300
correctionTerm1 = 50
correctionTerm2 = correctionTerm1 + 150
plank = Solid(color_palette.BROWN, [
    (plankThickness, waterLevel + plankThickness, plankLength, plankThickness),
    (plankThickness + 6 * plankLength, waterLevel + plankThickness,
     plankLength, plankThickness),
    (correctionTerm1 + plankThickness + 7 * plankLength + plankThickness * 2,
     waterLevel + plankThickness * 5, plankThickness * 2, plankThickness * 2),
Beispiel #20
0
l1 = Line(Point(
    0,
    0,
    0,
), Point(1, 1, 1))
l2 = Line(Point(
    0,
    0,
    0,
), Point(1, 1, 1))

print(l1.intersect_point(l2))

exit()

solid = Solid(filename, 0)
solid_ = Solid(filename, 0)

#print("Object:")
#solid_.print()
#print('-----')

#solid.print()
solid.refactor()

exit()
cf = solid.concave_faces()
to_merge = []
for f1, f2 in cf:
    l = f1.intersect_line(f2)
    e1 = Face(f1.edges_along_line(l))