0
\$\begingroup\$

Hello I'm trying to implement an octree, but when I query the centre positions they all return zero, but these should be offset from zero. Here is my code:

class Octree:

def __init__( self, _centre, _size ):
    '''
    Class to create an Octree

    @param: _centre: [float,float,float], position in world space for centre of octree
    @param: _size: float, length of one edge of the first cube, should be big enough to fit all data
    '''

    self.centre = _centre
    self.size = _size
    self.octreeNodes = []

def subdivideOctree( self, _subdivisions ):
    '''
    subdivides octree 

    @param: _subdivisions: int, number of times to subdivide octree
    '''



    for i in range(8):
        newCentre = self.centre

        if ((i&2) == 2):
                newCentre[0] += self.size * 0.25
        else:
                newCentre[0] -= self.size * 0.25

        if ((i&4) == 4):
                newCentre[1] += self.size * 0.25
        else:
                newCentre[1] -= self.size * 0.25

        if ((i&1) == 1):
                newCentre[2] += self.size * 0.25
        else:
                newCentre[2] -= self.size * 0.25

        print newCentre

        self.octreeNodes.append(Octree( newCentre, self.size * 0.5 ))

        if( _subdivisions > 0 ):
                self.octreeNodes[i].subdivideOctree( _subdivisions - 1 )

def isLeaf( self ):
    return self.octreeNodes == None

def getCentre( self ):
    return self.centre

def getSize( self ):
    return self.size

a = Octree([0,0,0], 2.0)
a.subdivideOctree(2)

print a.getCentre()
print a.octreeNodes[0].getCentre()
print a.octreeNodes[0]

for n in a.octreeNodes:
    for b in n.octreeNodes:
        print b.getCentre()
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

When you do

newCentre = self.centre

then that doesn't create a new array, but it uses the same object instead. If you modify newCentre, self.centre gets modified as well. It probably stays 0, because it's symmetric.

\$\endgroup\$
2
  • \$\begingroup\$ Oh how can I create a new array from self.centre? And when I create a new Octree object as I have done recursively, does each object have a unique self.centre? \$\endgroup\$ Commented Jan 4, 2018 at 22:17
  • 1
    \$\begingroup\$ @cee012 stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list and yes \$\endgroup\$ Commented Jan 4, 2018 at 22:55
-1
\$\begingroup\$

You have to do newCentre = self.centre[:]

\$\endgroup\$
1
  • \$\begingroup\$ Why is this being downvoted? That is the correct way to create a new list with the content from another list... \$\endgroup\$ Commented Apr 8, 2020 at 16:04

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.